wgpu_hal/vulkan/
instance.rs

1use alloc::{borrow::ToOwned as _, boxed::Box, ffi::CString, string::String, sync::Arc, vec::Vec};
2use core::{
3    ffi::{c_void, CStr},
4    marker::PhantomData,
5    mem::ManuallyDrop,
6    slice,
7    str::FromStr,
8};
9use std::thread;
10
11use arrayvec::ArrayVec;
12use ash::{ext, khr, vk};
13use parking_lot::RwLock;
14
15unsafe extern "system" fn debug_utils_messenger_callback(
16    message_severity: vk::DebugUtilsMessageSeverityFlagsEXT,
17    message_type: vk::DebugUtilsMessageTypeFlagsEXT,
18    callback_data_ptr: *const vk::DebugUtilsMessengerCallbackDataEXT,
19    user_data: *mut c_void,
20) -> vk::Bool32 {
21    use alloc::borrow::Cow;
22
23    if thread::panicking() {
24        return vk::FALSE;
25    }
26
27    let cd = unsafe { &*callback_data_ptr };
28    let user_data = unsafe { &*user_data.cast::<super::DebugUtilsMessengerUserData>() };
29
30    const VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912: i32 = 0x56146426;
31    if cd.message_id_number == VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912 {
32        // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/5671
33        // Versions 1.3.240 through 1.3.250 return a spurious error here if
34        // the debug range start and end appear in different command buffers.
35        if let Some(layer_properties) = user_data.validation_layer_properties.as_ref() {
36            if layer_properties.layer_description.as_ref() == c"Khronos Validation Layer"
37                && layer_properties.layer_spec_version >= vk::make_api_version(0, 1, 3, 240)
38                && layer_properties.layer_spec_version <= vk::make_api_version(0, 1, 3, 250)
39            {
40                return vk::FALSE;
41            }
42        }
43    }
44
45    // Silence Vulkan Validation error "VUID-VkSwapchainCreateInfoKHR-pNext-07781"
46    // This happens when a surface is configured with a size outside the allowed extent.
47    // It's a false positive due to the inherent racy-ness of surface resizing.
48    const VUID_VKSWAPCHAINCREATEINFOKHR_PNEXT_07781: i32 = 0x4c8929c1;
49    if cd.message_id_number == VUID_VKSWAPCHAINCREATEINFOKHR_PNEXT_07781 {
50        return vk::FALSE;
51    }
52
53    // Silence Vulkan Validation error "VUID-VkRenderPassBeginInfo-framebuffer-04627"
54    // if the OBS layer is enabled. This is a bug in the OBS layer. As the OBS layer
55    // does not have a version number they increment, there is no way to qualify the
56    // suppression of the error to a specific version of the OBS layer.
57    //
58    // See https://github.com/obsproject/obs-studio/issues/9353
59    const VUID_VKRENDERPASSBEGININFO_FRAMEBUFFER_04627: i32 = 0x45125641;
60    if cd.message_id_number == VUID_VKRENDERPASSBEGININFO_FRAMEBUFFER_04627
61        && user_data.has_obs_layer
62    {
63        return vk::FALSE;
64    }
65
66    // Silence Vulkan Validation error "VUID-vkCmdCopyImageToBuffer-pRegions-00184".
67    // While we aren't sure yet, we suspect this is probably a VVL issue.
68    // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/9276
69    const VUID_VKCMDCOPYIMAGETOBUFFER_PREGIONS_00184: i32 = 0x45ef177c;
70    if cd.message_id_number == VUID_VKCMDCOPYIMAGETOBUFFER_PREGIONS_00184 {
71        return vk::FALSE;
72    }
73
74    // Silence Vulkan Validation error "VUID-StandaloneSpirv-None-10684".
75    //
76    // This is a bug. To prevent massive noise in the tests, lets suppress it for now.
77    // https://github.com/gfx-rs/wgpu/issues/7696
78    const VUID_STANDALONESPIRV_NONE_10684: i32 = 0xb210f7c2_u32 as i32;
79    if cd.message_id_number == VUID_STANDALONESPIRV_NONE_10684 {
80        return vk::FALSE;
81    }
82
83    let level = match message_severity {
84        // We intentionally suppress info messages down to debug
85        // so that users are not innundated with info messages from the runtime.
86        vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE => log::Level::Trace,
87        vk::DebugUtilsMessageSeverityFlagsEXT::INFO => log::Level::Debug,
88        vk::DebugUtilsMessageSeverityFlagsEXT::WARNING => log::Level::Warn,
89        vk::DebugUtilsMessageSeverityFlagsEXT::ERROR => log::Level::Error,
90        _ => log::Level::Warn,
91    };
92
93    let message_id_name =
94        unsafe { cd.message_id_name_as_c_str() }.map_or(Cow::Borrowed(""), CStr::to_string_lossy);
95    let message = unsafe { cd.message_as_c_str() }.map_or(Cow::Borrowed(""), CStr::to_string_lossy);
96
97    let _ = std::panic::catch_unwind(|| {
98        log::log!(
99            level,
100            "{:?} [{} (0x{:x})]\n\t{}",
101            message_type,
102            message_id_name,
103            cd.message_id_number,
104            message,
105        );
106    });
107
108    if cd.queue_label_count != 0 {
109        let labels =
110            unsafe { slice::from_raw_parts(cd.p_queue_labels, cd.queue_label_count as usize) };
111        let names = labels
112            .iter()
113            .flat_map(|dul_obj| unsafe { dul_obj.label_name_as_c_str() }.map(CStr::to_string_lossy))
114            .collect::<Vec<_>>();
115
116        let _ = std::panic::catch_unwind(|| {
117            log::log!(level, "\tqueues: {}", names.join(", "));
118        });
119    }
120
121    if cd.cmd_buf_label_count != 0 {
122        let labels =
123            unsafe { slice::from_raw_parts(cd.p_cmd_buf_labels, cd.cmd_buf_label_count as usize) };
124        let names = labels
125            .iter()
126            .flat_map(|dul_obj| unsafe { dul_obj.label_name_as_c_str() }.map(CStr::to_string_lossy))
127            .collect::<Vec<_>>();
128
129        let _ = std::panic::catch_unwind(|| {
130            log::log!(level, "\tcommand buffers: {}", names.join(", "));
131        });
132    }
133
134    if cd.object_count != 0 {
135        let labels = unsafe { slice::from_raw_parts(cd.p_objects, cd.object_count as usize) };
136        //TODO: use color fields of `vk::DebugUtilsLabelExt`?
137        let names = labels
138            .iter()
139            .map(|obj_info| {
140                let name = unsafe { obj_info.object_name_as_c_str() }
141                    .map_or(Cow::Borrowed("?"), CStr::to_string_lossy);
142
143                format!(
144                    "(type: {:?}, hndl: 0x{:x}, name: {})",
145                    obj_info.object_type, obj_info.object_handle, name
146                )
147            })
148            .collect::<Vec<_>>();
149        let _ = std::panic::catch_unwind(|| {
150            log::log!(level, "\tobjects: {}", names.join(", "));
151        });
152    }
153
154    #[cfg(feature = "validation_canary")]
155    if cfg!(debug_assertions) && level == log::Level::Error {
156        use alloc::string::ToString as _;
157
158        // Set canary and continue
159        crate::VALIDATION_CANARY.add(message.to_string());
160    }
161
162    vk::FALSE
163}
164
165impl super::DebugUtilsCreateInfo {
166    fn to_vk_create_info(&self) -> vk::DebugUtilsMessengerCreateInfoEXT<'_> {
167        let user_data_ptr: *const super::DebugUtilsMessengerUserData = &*self.callback_data;
168        vk::DebugUtilsMessengerCreateInfoEXT::default()
169            .message_severity(self.severity)
170            .message_type(self.message_type)
171            .user_data(user_data_ptr as *mut _)
172            .pfn_user_callback(Some(debug_utils_messenger_callback))
173    }
174}
175
176impl super::InstanceShared {
177    pub fn entry(&self) -> &ash::Entry {
178        &self.entry
179    }
180
181    pub fn raw_instance(&self) -> &ash::Instance {
182        &self.raw
183    }
184
185    pub fn instance_api_version(&self) -> u32 {
186        self.instance_api_version
187    }
188
189    pub fn extensions(&self) -> &[&'static CStr] {
190        &self.extensions[..]
191    }
192}
193
194impl super::Instance {
195    pub fn shared_instance(&self) -> &super::InstanceShared {
196        &self.shared
197    }
198
199    fn enumerate_instance_extension_properties(
200        entry: &ash::Entry,
201        layer_name: Option<&CStr>,
202    ) -> Result<Vec<vk::ExtensionProperties>, crate::InstanceError> {
203        let instance_extensions = {
204            profiling::scope!("vkEnumerateInstanceExtensionProperties");
205            unsafe { entry.enumerate_instance_extension_properties(layer_name) }
206        };
207        instance_extensions.map_err(|e| {
208            crate::InstanceError::with_source(
209                String::from("enumerate_instance_extension_properties() failed"),
210                e,
211            )
212        })
213    }
214
215    /// Return the instance extension names wgpu would like to enable.
216    ///
217    /// Return a vector of the names of instance extensions actually available
218    /// on `entry` that wgpu would like to enable.
219    ///
220    /// The `instance_api_version` argument should be the instance's Vulkan API
221    /// version, as obtained from `vkEnumerateInstanceVersion`. This is the same
222    /// space of values as the `VK_API_VERSION` constants.
223    ///
224    /// Note that wgpu can function without many of these extensions (for
225    /// example, `VK_KHR_wayland_surface` is certainly not going to be available
226    /// everywhere), but if one of these extensions is available at all, wgpu
227    /// assumes that it has been enabled.
228    pub fn desired_extensions(
229        entry: &ash::Entry,
230        _instance_api_version: u32,
231        flags: wgt::InstanceFlags,
232    ) -> Result<Vec<&'static CStr>, crate::InstanceError> {
233        let instance_extensions = Self::enumerate_instance_extension_properties(entry, None)?;
234
235        // Check our extensions against the available extensions
236        let mut extensions: Vec<&'static CStr> = Vec::new();
237
238        // VK_KHR_surface
239        extensions.push(khr::surface::NAME);
240
241        // Platform-specific WSI extensions
242        if cfg!(all(
243            unix,
244            not(target_os = "android"),
245            not(target_os = "macos")
246        )) {
247            // VK_KHR_xlib_surface
248            extensions.push(khr::xlib_surface::NAME);
249            // VK_KHR_xcb_surface
250            extensions.push(khr::xcb_surface::NAME);
251            // VK_KHR_wayland_surface
252            extensions.push(khr::wayland_surface::NAME);
253        }
254        if cfg!(target_os = "android") {
255            // VK_KHR_android_surface
256            extensions.push(khr::android_surface::NAME);
257        }
258        if cfg!(target_os = "windows") {
259            // VK_KHR_win32_surface
260            extensions.push(khr::win32_surface::NAME);
261        }
262        if cfg!(target_os = "macos") {
263            // VK_EXT_metal_surface
264            extensions.push(ext::metal_surface::NAME);
265            extensions.push(khr::portability_enumeration::NAME);
266        }
267        if cfg!(all(
268            unix,
269            not(target_vendor = "apple"),
270            not(target_family = "wasm")
271        )) {
272            // VK_EXT_acquire_drm_display -> VK_EXT_direct_mode_display -> VK_KHR_display
273            extensions.push(ext::acquire_drm_display::NAME);
274            extensions.push(ext::direct_mode_display::NAME);
275            extensions.push(khr::display::NAME);
276            extensions.push(khr::get_physical_device_properties2::NAME);
277            extensions.push(khr::get_display_properties2::NAME);
278        }
279
280        if flags.contains(wgt::InstanceFlags::DEBUG) {
281            // VK_EXT_debug_utils
282            extensions.push(ext::debug_utils::NAME);
283        }
284
285        // VK_EXT_swapchain_colorspace
286        // Provides wide color gamut
287        extensions.push(ext::swapchain_colorspace::NAME);
288
289        // VK_KHR_get_physical_device_properties2
290        // Even though the extension was promoted to Vulkan 1.1, we still require the extension
291        // so that we don't have to conditionally use the functions provided by the 1.1 instance
292        extensions.push(khr::get_physical_device_properties2::NAME);
293
294        // Only keep available extensions.
295        extensions.retain(|&ext| {
296            if instance_extensions
297                .iter()
298                .any(|inst_ext| inst_ext.extension_name_as_c_str() == Ok(ext))
299            {
300                true
301            } else {
302                log::debug!("Unable to find extension: {}", ext.to_string_lossy());
303                false
304            }
305        });
306        Ok(extensions)
307    }
308
309    /// # Safety
310    ///
311    /// - `raw_instance` must be created from `entry`
312    /// - `raw_instance` must be created respecting `instance_api_version`, `extensions` and `flags`
313    /// - `extensions` must be a superset of `desired_extensions()` and must be created from the
314    ///   same entry, `instance_api_version`` and flags.
315    /// - `android_sdk_version` is ignored and can be `0` for all platforms besides Android
316    /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `raw_instance`. If
317    ///   `drop_callback` is [`Some`], `raw_instance` must be valid until the callback is called.
318    ///
319    /// If `debug_utils_user_data` is `Some`, then the validation layer is
320    /// available, so create a [`vk::DebugUtilsMessengerEXT`].
321    #[allow(clippy::too_many_arguments)]
322    pub unsafe fn from_raw(
323        entry: ash::Entry,
324        raw_instance: ash::Instance,
325        instance_api_version: u32,
326        android_sdk_version: u32,
327        debug_utils_create_info: Option<super::DebugUtilsCreateInfo>,
328        extensions: Vec<&'static CStr>,
329        flags: wgt::InstanceFlags,
330        memory_budget_thresholds: wgt::MemoryBudgetThresholds,
331        has_nv_optimus: bool,
332        drop_callback: Option<crate::DropCallback>,
333    ) -> Result<Self, crate::InstanceError> {
334        log::debug!("Instance version: 0x{instance_api_version:x}");
335
336        let debug_utils = if let Some(debug_utils_create_info) = debug_utils_create_info {
337            if extensions.contains(&ext::debug_utils::NAME) {
338                log::debug!("Enabling debug utils");
339
340                let extension = ext::debug_utils::Instance::new(&entry, &raw_instance);
341                let vk_info = debug_utils_create_info.to_vk_create_info();
342                let messenger =
343                    unsafe { extension.create_debug_utils_messenger(&vk_info, None) }.unwrap();
344
345                Some(super::DebugUtils {
346                    extension,
347                    messenger,
348                    callback_data: debug_utils_create_info.callback_data,
349                })
350            } else {
351                log::debug!("Debug utils not enabled: extension not listed");
352                None
353            }
354        } else {
355            log::debug!(
356                "Debug utils not enabled: \
357                        debug_utils_user_data not passed to Instance::from_raw"
358            );
359            None
360        };
361
362        let get_physical_device_properties =
363            if extensions.contains(&khr::get_physical_device_properties2::NAME) {
364                log::debug!("Enabling device properties2");
365                Some(khr::get_physical_device_properties2::Instance::new(
366                    &entry,
367                    &raw_instance,
368                ))
369            } else {
370                None
371            };
372
373        let drop_guard = crate::DropGuard::from_option(drop_callback);
374
375        Ok(Self {
376            shared: Arc::new(super::InstanceShared {
377                raw: raw_instance,
378                extensions,
379                drop_guard,
380                flags,
381                memory_budget_thresholds,
382                debug_utils,
383                get_physical_device_properties,
384                entry,
385                has_nv_optimus,
386                instance_api_version,
387                android_sdk_version,
388            }),
389        })
390    }
391
392    fn create_surface_from_xlib(
393        &self,
394        dpy: *mut vk::Display,
395        window: vk::Window,
396    ) -> Result<super::Surface, crate::InstanceError> {
397        if !self.shared.extensions.contains(&khr::xlib_surface::NAME) {
398            return Err(crate::InstanceError::new(String::from(
399                "Vulkan driver does not support VK_KHR_xlib_surface",
400            )));
401        }
402
403        let surface = {
404            let xlib_loader =
405                khr::xlib_surface::Instance::new(&self.shared.entry, &self.shared.raw);
406            let info = vk::XlibSurfaceCreateInfoKHR::default()
407                .flags(vk::XlibSurfaceCreateFlagsKHR::empty())
408                .window(window)
409                .dpy(dpy);
410
411            unsafe { xlib_loader.create_xlib_surface(&info, None) }
412                .expect("XlibSurface::create_xlib_surface() failed")
413        };
414
415        Ok(self.create_surface_from_vk_surface_khr(surface))
416    }
417
418    fn create_surface_from_xcb(
419        &self,
420        connection: *mut vk::xcb_connection_t,
421        window: vk::xcb_window_t,
422    ) -> Result<super::Surface, crate::InstanceError> {
423        if !self.shared.extensions.contains(&khr::xcb_surface::NAME) {
424            return Err(crate::InstanceError::new(String::from(
425                "Vulkan driver does not support VK_KHR_xcb_surface",
426            )));
427        }
428
429        let surface = {
430            let xcb_loader = khr::xcb_surface::Instance::new(&self.shared.entry, &self.shared.raw);
431            let info = vk::XcbSurfaceCreateInfoKHR::default()
432                .flags(vk::XcbSurfaceCreateFlagsKHR::empty())
433                .window(window)
434                .connection(connection);
435
436            unsafe { xcb_loader.create_xcb_surface(&info, None) }
437                .expect("XcbSurface::create_xcb_surface() failed")
438        };
439
440        Ok(self.create_surface_from_vk_surface_khr(surface))
441    }
442
443    fn create_surface_from_wayland(
444        &self,
445        display: *mut vk::wl_display,
446        surface: *mut vk::wl_surface,
447    ) -> Result<super::Surface, crate::InstanceError> {
448        if !self.shared.extensions.contains(&khr::wayland_surface::NAME) {
449            return Err(crate::InstanceError::new(String::from(
450                "Vulkan driver does not support VK_KHR_wayland_surface",
451            )));
452        }
453
454        let surface = {
455            let w_loader =
456                khr::wayland_surface::Instance::new(&self.shared.entry, &self.shared.raw);
457            let info = vk::WaylandSurfaceCreateInfoKHR::default()
458                .flags(vk::WaylandSurfaceCreateFlagsKHR::empty())
459                .display(display)
460                .surface(surface);
461
462            unsafe { w_loader.create_wayland_surface(&info, None) }.expect("WaylandSurface failed")
463        };
464
465        Ok(self.create_surface_from_vk_surface_khr(surface))
466    }
467
468    fn create_surface_android(
469        &self,
470        window: *mut vk::ANativeWindow,
471    ) -> Result<super::Surface, crate::InstanceError> {
472        if !self.shared.extensions.contains(&khr::android_surface::NAME) {
473            return Err(crate::InstanceError::new(String::from(
474                "Vulkan driver does not support VK_KHR_android_surface",
475            )));
476        }
477
478        let surface = {
479            let a_loader =
480                khr::android_surface::Instance::new(&self.shared.entry, &self.shared.raw);
481            let info = vk::AndroidSurfaceCreateInfoKHR::default()
482                .flags(vk::AndroidSurfaceCreateFlagsKHR::empty())
483                .window(window);
484
485            unsafe { a_loader.create_android_surface(&info, None) }.expect("AndroidSurface failed")
486        };
487
488        Ok(self.create_surface_from_vk_surface_khr(surface))
489    }
490
491    fn create_surface_from_hwnd(
492        &self,
493        hinstance: vk::HINSTANCE,
494        hwnd: vk::HWND,
495    ) -> Result<super::Surface, crate::InstanceError> {
496        if !self.shared.extensions.contains(&khr::win32_surface::NAME) {
497            return Err(crate::InstanceError::new(String::from(
498                "Vulkan driver does not support VK_KHR_win32_surface",
499            )));
500        }
501
502        let surface = {
503            let info = vk::Win32SurfaceCreateInfoKHR::default()
504                .flags(vk::Win32SurfaceCreateFlagsKHR::empty())
505                .hinstance(hinstance)
506                .hwnd(hwnd);
507            let win32_loader =
508                khr::win32_surface::Instance::new(&self.shared.entry, &self.shared.raw);
509            unsafe {
510                win32_loader
511                    .create_win32_surface(&info, None)
512                    .expect("Unable to create Win32 surface")
513            }
514        };
515
516        Ok(self.create_surface_from_vk_surface_khr(surface))
517    }
518
519    #[cfg(metal)]
520    fn create_surface_from_view(
521        &self,
522        view: core::ptr::NonNull<c_void>,
523    ) -> Result<super::Surface, crate::InstanceError> {
524        if !self.shared.extensions.contains(&ext::metal_surface::NAME) {
525            return Err(crate::InstanceError::new(String::from(
526                "Vulkan driver does not support VK_EXT_metal_surface",
527            )));
528        }
529
530        let layer = unsafe { crate::metal::Surface::get_metal_layer(view.cast()) };
531        // NOTE: The layer is retained by Vulkan's `vkCreateMetalSurfaceEXT`,
532        // so no need to retain it beyond the scope of this function.
533        let layer_ptr = (*layer).cast();
534
535        let surface = {
536            let metal_loader =
537                ext::metal_surface::Instance::new(&self.shared.entry, &self.shared.raw);
538            let vk_info = vk::MetalSurfaceCreateInfoEXT::default()
539                .flags(vk::MetalSurfaceCreateFlagsEXT::empty())
540                .layer(layer_ptr);
541
542            unsafe { metal_loader.create_metal_surface(&vk_info, None).unwrap() }
543        };
544
545        Ok(self.create_surface_from_vk_surface_khr(surface))
546    }
547
548    pub(super) fn create_surface_from_vk_surface_khr(
549        &self,
550        surface: vk::SurfaceKHR,
551    ) -> super::Surface {
552        let native_surface =
553            crate::vulkan::swapchain::NativeSurface::from_vk_surface_khr(self, surface);
554
555        super::Surface {
556            inner: ManuallyDrop::new(Box::new(native_surface)),
557            swapchain: RwLock::new(None),
558        }
559    }
560
561    /// `Instance::init` but with a callback.
562    /// If you want to add extensions, add the to the `Vec<'static CStr>` not the create info, otherwise
563    /// it will be overwritten
564    ///
565    /// # Safety:
566    /// Same as `init` but additionally
567    /// - Callback must not remove features.
568    /// - Callback must not change anything to what the instance does not support.
569    pub unsafe fn init_with_callback(
570        desc: &crate::InstanceDescriptor,
571        callback: Option<Box<super::CreateInstanceCallback>>,
572    ) -> Result<Self, crate::InstanceError> {
573        profiling::scope!("Init Vulkan Backend");
574
575        let entry = unsafe {
576            profiling::scope!("Load vk library");
577            ash::Entry::load()
578        }
579        .map_err(|err| {
580            crate::InstanceError::with_source(String::from("missing Vulkan entry points"), err)
581        })?;
582        let version = {
583            profiling::scope!("vkEnumerateInstanceVersion");
584            unsafe { entry.try_enumerate_instance_version() }
585        };
586        let instance_api_version = match version {
587            // Vulkan 1.1+
588            Ok(Some(version)) => version,
589            Ok(None) => vk::API_VERSION_1_0,
590            Err(err) => {
591                return Err(crate::InstanceError::with_source(
592                    String::from("try_enumerate_instance_version() failed"),
593                    err,
594                ));
595            }
596        };
597
598        let app_name = CString::new(desc.name).unwrap();
599        let app_info = vk::ApplicationInfo::default()
600            .application_name(app_name.as_c_str())
601            .application_version(1)
602            .engine_name(c"wgpu-hal")
603            .engine_version(2)
604            .api_version(
605                // Vulkan 1.0 doesn't like anything but 1.0 passed in here...
606                if instance_api_version < vk::API_VERSION_1_1 {
607                    vk::API_VERSION_1_0
608                } else {
609                    // This is the max Vulkan API version supported by `wgpu-hal`.
610                    //
611                    // If we want to increment this, there are some things that must be done first:
612                    //  - Audit the behavioral differences between the previous and new API versions.
613                    //  - Audit all extensions used by this backend:
614                    //    - If any were promoted in the new API version and the behavior has changed, we must handle the new behavior in addition to the old behavior.
615                    //    - If any were obsoleted in the new API version, we must implement a fallback for the new API version
616                    //    - If any are non-KHR-vendored, we must ensure the new behavior is still correct (since backwards-compatibility is not guaranteed).
617                    vk::API_VERSION_1_3
618                },
619            );
620
621        let mut extensions = Self::desired_extensions(&entry, instance_api_version, desc.flags)?;
622        let mut create_info = vk::InstanceCreateInfo::default();
623
624        if let Some(callback) = callback {
625            callback(super::CreateInstanceCallbackArgs {
626                extensions: &mut extensions,
627                create_info: &mut create_info,
628                entry: &entry,
629                _phantom: PhantomData,
630            });
631        }
632
633        let instance_layers = {
634            profiling::scope!("vkEnumerateInstanceLayerProperties");
635            unsafe { entry.enumerate_instance_layer_properties() }
636        };
637        let instance_layers = instance_layers.map_err(|e| {
638            log::debug!("enumerate_instance_layer_properties: {e:?}");
639            crate::InstanceError::with_source(
640                String::from("enumerate_instance_layer_properties() failed"),
641                e,
642            )
643        })?;
644
645        fn find_layer<'layers>(
646            instance_layers: &'layers [vk::LayerProperties],
647            name: &CStr,
648        ) -> Option<&'layers vk::LayerProperties> {
649            instance_layers
650                .iter()
651                .find(|inst_layer| inst_layer.layer_name_as_c_str() == Ok(name))
652        }
653
654        let validation_layer_name = c"VK_LAYER_KHRONOS_validation";
655        let validation_layer_properties = find_layer(&instance_layers, validation_layer_name);
656
657        // Determine if VK_EXT_validation_features is available, so we can enable
658        // GPU assisted validation and synchronization validation.
659        let validation_features_are_enabled = if validation_layer_properties.is_some() {
660            // Get the all the instance extension properties.
661            let exts =
662                Self::enumerate_instance_extension_properties(&entry, Some(validation_layer_name))?;
663            // Convert all the names of the extensions into an iterator of CStrs.
664            let mut ext_names = exts
665                .iter()
666                .filter_map(|ext| ext.extension_name_as_c_str().ok());
667            // Find the validation features extension.
668            ext_names.any(|ext_name| ext_name == ext::validation_features::NAME)
669        } else {
670            false
671        };
672
673        let should_enable_gpu_based_validation = desc
674            .flags
675            .intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION)
676            && validation_features_are_enabled;
677
678        let has_nv_optimus = find_layer(&instance_layers, c"VK_LAYER_NV_optimus").is_some();
679
680        let has_obs_layer = find_layer(&instance_layers, c"VK_LAYER_OBS_HOOK").is_some();
681
682        let mut layers: Vec<&'static CStr> = Vec::new();
683
684        let has_debug_extension = extensions.contains(&ext::debug_utils::NAME);
685        let mut debug_user_data = has_debug_extension.then(|| {
686            // Put the callback data on the heap, to ensure it will never be
687            // moved.
688            Box::new(super::DebugUtilsMessengerUserData {
689                validation_layer_properties: None,
690                has_obs_layer,
691            })
692        });
693
694        // Request validation layer if asked.
695        if desc.flags.intersects(wgt::InstanceFlags::VALIDATION)
696            || should_enable_gpu_based_validation
697        {
698            if let Some(layer_properties) = validation_layer_properties {
699                layers.push(validation_layer_name);
700
701                if let Some(debug_user_data) = debug_user_data.as_mut() {
702                    debug_user_data.validation_layer_properties =
703                        Some(super::ValidationLayerProperties {
704                            layer_description: layer_properties
705                                .description_as_c_str()
706                                .unwrap()
707                                .to_owned(),
708                            layer_spec_version: layer_properties.spec_version,
709                        });
710                }
711            } else {
712                log::debug!(
713                    "InstanceFlags::VALIDATION requested, but unable to find layer: {}",
714                    validation_layer_name.to_string_lossy()
715                );
716            }
717        }
718        let mut debug_utils = if let Some(callback_data) = debug_user_data {
719            // having ERROR unconditionally because Vk doesn't like empty flags
720            let mut severity = vk::DebugUtilsMessageSeverityFlagsEXT::ERROR;
721            if log::max_level() >= log::LevelFilter::Debug {
722                severity |= vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE;
723            }
724            if log::max_level() >= log::LevelFilter::Info {
725                severity |= vk::DebugUtilsMessageSeverityFlagsEXT::INFO;
726            }
727            if log::max_level() >= log::LevelFilter::Warn {
728                severity |= vk::DebugUtilsMessageSeverityFlagsEXT::WARNING;
729            }
730
731            let message_type = vk::DebugUtilsMessageTypeFlagsEXT::GENERAL
732                | vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION
733                | vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE;
734
735            let create_info = super::DebugUtilsCreateInfo {
736                severity,
737                message_type,
738                callback_data,
739            };
740
741            Some(create_info)
742        } else {
743            None
744        };
745
746        #[cfg(target_os = "android")]
747        let android_sdk_version = {
748            let properties = android_system_properties::AndroidSystemProperties::new();
749            // See: https://developer.android.com/reference/android/os/Build.VERSION_CODES
750            if let Some(val) = properties.get("ro.build.version.sdk") {
751                match val.parse::<u32>() {
752                    Ok(sdk_ver) => sdk_ver,
753                    Err(err) => {
754                        log::error!(
755                            concat!(
756                                "Couldn't parse Android's ",
757                                "ro.build.version.sdk system property ({}): {}",
758                            ),
759                            val,
760                            err,
761                        );
762                        0
763                    }
764                }
765            } else {
766                log::error!("Couldn't read Android's ro.build.version.sdk system property");
767                0
768            }
769        };
770        #[cfg(not(target_os = "android"))]
771        let android_sdk_version = 0;
772
773        let mut flags = vk::InstanceCreateFlags::empty();
774
775        // Avoid VUID-VkInstanceCreateInfo-flags-06559: Only ask the instance to
776        // enumerate incomplete Vulkan implementations (which we need on Mac) if
777        // we managed to find the extension that provides the flag.
778        if extensions.contains(&khr::portability_enumeration::NAME) {
779            flags |= vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR;
780        }
781        let vk_instance = {
782            let str_pointers = layers
783                .iter()
784                .chain(extensions.iter())
785                .map(|&s: &&'static _| {
786                    // Safe because `layers` and `extensions` entries have static lifetime.
787                    s.as_ptr()
788                })
789                .collect::<Vec<_>>();
790
791            create_info = create_info
792                .flags(flags)
793                .application_info(&app_info)
794                .enabled_layer_names(&str_pointers[..layers.len()])
795                .enabled_extension_names(&str_pointers[layers.len()..]);
796
797            let mut debug_utils_create_info = debug_utils
798                .as_mut()
799                .map(|create_info| create_info.to_vk_create_info());
800            if let Some(debug_utils_create_info) = debug_utils_create_info.as_mut() {
801                create_info = create_info.push_next(debug_utils_create_info);
802            }
803
804            // Enable explicit validation features if available
805            let mut validation_features;
806            let mut validation_feature_list: ArrayVec<_, 3>;
807            if validation_features_are_enabled {
808                validation_feature_list = ArrayVec::new();
809
810                // Always enable synchronization validation
811                validation_feature_list
812                    .push(vk::ValidationFeatureEnableEXT::SYNCHRONIZATION_VALIDATION);
813
814                // Only enable GPU assisted validation if requested.
815                if should_enable_gpu_based_validation {
816                    validation_feature_list.push(vk::ValidationFeatureEnableEXT::GPU_ASSISTED);
817                    validation_feature_list
818                        .push(vk::ValidationFeatureEnableEXT::GPU_ASSISTED_RESERVE_BINDING_SLOT);
819                }
820
821                validation_features = vk::ValidationFeaturesEXT::default()
822                    .enabled_validation_features(&validation_feature_list);
823                create_info = create_info.push_next(&mut validation_features);
824            }
825
826            unsafe {
827                profiling::scope!("vkCreateInstance");
828                entry.create_instance(&create_info, None)
829            }
830            .map_err(|e| {
831                crate::InstanceError::with_source(
832                    String::from("Entry::create_instance() failed"),
833                    e,
834                )
835            })?
836        };
837
838        unsafe {
839            Self::from_raw(
840                entry,
841                vk_instance,
842                instance_api_version,
843                android_sdk_version,
844                debug_utils,
845                extensions,
846                desc.flags,
847                desc.memory_budget_thresholds,
848                has_nv_optimus,
849                None,
850            )
851        }
852    }
853}
854
855impl Drop for super::InstanceShared {
856    fn drop(&mut self) {
857        unsafe {
858            // Keep du alive since destroy_instance may also log
859            let _du = self.debug_utils.take().inspect(|du| {
860                du.extension
861                    .destroy_debug_utils_messenger(du.messenger, None);
862            });
863            if self.drop_guard.is_none() {
864                self.raw.destroy_instance(None);
865            }
866        }
867    }
868}
869
870impl crate::Instance for super::Instance {
871    type A = super::Api;
872
873    unsafe fn init(desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> {
874        unsafe { Self::init_with_callback(desc, None) }
875    }
876
877    unsafe fn create_surface(
878        &self,
879        display_handle: raw_window_handle::RawDisplayHandle,
880        window_handle: raw_window_handle::RawWindowHandle,
881    ) -> Result<super::Surface, crate::InstanceError> {
882        use raw_window_handle::{RawDisplayHandle as Rdh, RawWindowHandle as Rwh};
883
884        // TODO: Replace with ash-window, which also lazy-loads the extension based on handle type
885
886        match (window_handle, display_handle) {
887            (Rwh::Wayland(handle), Rdh::Wayland(display)) => {
888                self.create_surface_from_wayland(display.display.as_ptr(), handle.surface.as_ptr())
889            }
890            (Rwh::Xlib(handle), Rdh::Xlib(display)) => {
891                let display = display.display.expect("Display pointer is not set.");
892                self.create_surface_from_xlib(display.as_ptr(), handle.window)
893            }
894            (Rwh::Xcb(handle), Rdh::Xcb(display)) => {
895                let connection = display.connection.expect("Pointer to X-Server is not set.");
896                self.create_surface_from_xcb(connection.as_ptr(), handle.window.get())
897            }
898            (Rwh::AndroidNdk(handle), _) => {
899                self.create_surface_android(handle.a_native_window.as_ptr())
900            }
901            (Rwh::Win32(handle), _) => {
902                let hinstance = handle.hinstance.ok_or_else(|| {
903                    crate::InstanceError::new(String::from(
904                        "Vulkan requires raw-window-handle's Win32::hinstance to be set",
905                    ))
906                })?;
907                self.create_surface_from_hwnd(hinstance.get(), handle.hwnd.get())
908            }
909            #[cfg(all(target_os = "macos", feature = "metal"))]
910            (Rwh::AppKit(handle), _)
911                if self.shared.extensions.contains(&ext::metal_surface::NAME) =>
912            {
913                self.create_surface_from_view(handle.ns_view)
914            }
915            #[cfg(all(any(target_os = "ios", target_os = "visionos"), feature = "metal"))]
916            (Rwh::UiKit(handle), _)
917                if self.shared.extensions.contains(&ext::metal_surface::NAME) =>
918            {
919                self.create_surface_from_view(handle.ui_view)
920            }
921            (_, _) => Err(crate::InstanceError::new(format!(
922                "window handle {window_handle:?} is not a Vulkan-compatible handle"
923            ))),
924        }
925    }
926
927    unsafe fn enumerate_adapters(
928        &self,
929        _surface_hint: Option<&super::Surface>,
930    ) -> Vec<crate::ExposedAdapter<super::Api>> {
931        use crate::auxil::db;
932
933        let raw_devices = match unsafe { self.shared.raw.enumerate_physical_devices() } {
934            Ok(devices) => devices,
935            Err(err) => {
936                log::error!("enumerate_adapters: {err}");
937                Vec::new()
938            }
939        };
940
941        let mut exposed_adapters = raw_devices
942            .into_iter()
943            .flat_map(|device| self.expose_adapter(device))
944            .collect::<Vec<_>>();
945
946        // Detect if it's an Intel + NVidia configuration with Optimus
947        let has_nvidia_dgpu = exposed_adapters.iter().any(|exposed| {
948            exposed.info.device_type == wgt::DeviceType::DiscreteGpu
949                && exposed.info.vendor == db::nvidia::VENDOR
950        });
951        if cfg!(target_os = "linux") && has_nvidia_dgpu && self.shared.has_nv_optimus {
952            for exposed in exposed_adapters.iter_mut() {
953                if exposed.info.device_type == wgt::DeviceType::IntegratedGpu
954                    && exposed.info.vendor == db::intel::VENDOR
955                {
956                    // Check if mesa driver and version less than 21.2
957                    if let Some(version) = exposed.info.driver_info.split_once("Mesa ").map(|s| {
958                        let mut components = s.1.split('.');
959                        let major = components.next().and_then(|s| u8::from_str(s).ok());
960                        let minor = components.next().and_then(|s| u8::from_str(s).ok());
961                        if let (Some(major), Some(minor)) = (major, minor) {
962                            (major, minor)
963                        } else {
964                            (0, 0)
965                        }
966                    }) {
967                        if version < (21, 2) {
968                            // See https://gitlab.freedesktop.org/mesa/mesa/-/issues/4688
969                            log::debug!(
970                                concat!(
971                                    "Disabling presentation on '{}' (id {:?}) ",
972                                    "due to NV Optimus and Intel Mesa < v21.2"
973                                ),
974                                exposed.info.name,
975                                exposed.adapter.raw
976                            );
977                            exposed.adapter.private_caps.can_present = false;
978                        }
979                    }
980                }
981            }
982        }
983
984        exposed_adapters
985    }
986}
987
988impl Drop for super::Surface {
989    fn drop(&mut self) {
990        unsafe { ManuallyDrop::take(&mut self.inner).delete_surface() };
991    }
992}
993
994impl crate::Surface for super::Surface {
995    type A = super::Api;
996
997    unsafe fn configure(
998        &self,
999        device: &super::Device,
1000        config: &crate::SurfaceConfiguration,
1001    ) -> Result<(), crate::SurfaceError> {
1002        // SAFETY: `configure`'s contract guarantees there are no resources derived from the swapchain in use.
1003        let mut swap_chain = self.swapchain.write();
1004
1005        let mut old = swap_chain.take();
1006        if let Some(ref mut old) = old {
1007            unsafe { old.release_resources(device) };
1008        }
1009
1010        let swapchain = unsafe { self.inner.create_swapchain(device, config, old)? };
1011        *swap_chain = Some(swapchain);
1012
1013        Ok(())
1014    }
1015
1016    unsafe fn unconfigure(&self, device: &super::Device) {
1017        if let Some(mut sc) = self.swapchain.write().take() {
1018            // SAFETY: `unconfigure`'s contract guarantees there are no resources derived from the swapchain in use.
1019            unsafe { sc.release_resources(device) };
1020            unsafe { sc.delete_swapchain() };
1021        }
1022    }
1023
1024    unsafe fn acquire_texture(
1025        &self,
1026        timeout: Option<core::time::Duration>,
1027        fence: &super::Fence,
1028    ) -> Result<Option<crate::AcquiredSurfaceTexture<super::Api>>, crate::SurfaceError> {
1029        let mut swapchain = self.swapchain.write();
1030        let swapchain = swapchain.as_mut().unwrap();
1031
1032        unsafe { swapchain.acquire(timeout, fence) }
1033    }
1034
1035    unsafe fn discard_texture(&self, texture: super::SurfaceTexture) {
1036        unsafe {
1037            self.swapchain
1038                .write()
1039                .as_mut()
1040                .unwrap()
1041                .discard_texture(texture)
1042                .unwrap()
1043        };
1044    }
1045}