wgpu_hal/vulkan/swapchain/
native.rs

1//! Vulkan Surface and Swapchain implementation using native Vulkan surfaces.
2
3use alloc::{boxed::Box, sync::Arc, vec::Vec};
4use core::any::Any;
5
6use ash::{khr, vk};
7use wgpu_sync::{Mutex, MutexGuard};
8
9use crate::vulkan::{
10    conv, map_host_device_oom_and_lost_err,
11    semaphore_list::SemaphoreType,
12    swapchain::{
13        Surface, SurfaceTextureMetadata, Swapchain, SwapchainSubmissionSemaphoreGuard, WindowHandle,
14    },
15    DeviceShared, InstanceShared, PnextChain,
16};
17
18pub(crate) struct NativeSurface {
19    raw: vk::SurfaceKHR,
20    functor: khr::surface::Instance,
21    instance: Arc<InstanceShared>,
22    /// Built from the window's `HWND` (Windows only) to answer the display-HDR
23    /// query; `None` for non-Win32 surfaces.
24    #[cfg(windows)]
25    hdr_source: Option<crate::auxil::dxgi::hdr::DxgiHdrSource>,
26    /// A caller-provided `pNext` chain to attach to the [`vk::SwapchainCreateInfoKHR`]
27    /// of the next swapchain created for this surface.
28    ///
29    /// Set only through
30    /// [`Surface::set_next_swapchain_create_chain()`](crate::vulkan::Surface::set_next_swapchain_create_chain).
31    next_swapchain_create_chain: Mutex<Option<PnextChain>>,
32}
33
34impl NativeSurface {
35    pub fn from_vk_surface_khr(
36        instance: &crate::vulkan::Instance,
37        raw: vk::SurfaceKHR,
38        hwnd: Option<WindowHandle>,
39    ) -> Self {
40        #[cfg(not(windows))]
41        let _ = hwnd;
42        let functor = khr::surface::Instance::new(&instance.shared.entry, &instance.shared.raw);
43        Self {
44            raw,
45            functor,
46            instance: Arc::clone(&instance.shared),
47            #[cfg(windows)]
48            hdr_source: hwnd.map(|wh| crate::auxil::dxgi::hdr::DxgiHdrSource::new(wh.0)),
49            next_swapchain_create_chain: Mutex::new(None),
50        }
51    }
52
53    pub fn as_raw(&self) -> vk::SurfaceKHR {
54        self.raw
55    }
56
57    /// # Safety
58    ///
59    /// See [`Surface::set_next_swapchain_create_chain()`](crate::vulkan::Surface::set_next_swapchain_create_chain).
60    pub unsafe fn set_next_swapchain_create_chain(&self, chain: *mut core::ffi::c_void) {
61        *self.next_swapchain_create_chain.lock() = Some(PnextChain::new(chain));
62    }
63}
64
65impl Drop for NativeSurface {
66    fn drop(&mut self) {
67        unsafe {
68            self.functor.destroy_surface(self.raw, None);
69        }
70    }
71}
72
73impl Surface for NativeSurface {
74    fn surface_capabilities(
75        &self,
76        adapter: &crate::vulkan::Adapter,
77    ) -> Option<crate::SurfaceCapabilities> {
78        if !adapter.private_caps.can_present {
79            return None;
80        }
81        let queue_family_index = 0; //TODO
82        {
83            profiling::scope!("vkGetPhysicalDeviceSurfaceSupportKHR");
84            match unsafe {
85                self.functor.get_physical_device_surface_support(
86                    adapter.raw,
87                    queue_family_index,
88                    self.raw,
89                )
90            } {
91                Ok(true) => (),
92                Ok(false) => return None,
93                Err(e) => {
94                    log::error!("get_physical_device_surface_support: {e}");
95                    return None;
96                }
97            }
98        }
99
100        let caps = {
101            profiling::scope!("vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
102            match unsafe {
103                self.functor
104                    .get_physical_device_surface_capabilities(adapter.raw, self.raw)
105            } {
106                Ok(caps) => caps,
107                Err(e) => {
108                    log::error!("get_physical_device_surface_capabilities: {e}");
109                    return None;
110                }
111            }
112        };
113
114        // If image count is 0, the support number of images is unlimited.
115        let max_image_count = if caps.max_image_count == 0 {
116            !0
117        } else {
118            caps.max_image_count
119        };
120
121        // `0xFFFFFFFF` indicates that the extent depends on the created swapchain.
122        let current_extent = if caps.current_extent.width != !0 && caps.current_extent.height != !0
123        {
124            Some(wgt::Extent3d {
125                width: caps.current_extent.width,
126                height: caps.current_extent.height,
127                depth_or_array_layers: 1,
128            })
129        } else {
130            None
131        };
132
133        let raw_present_modes = {
134            profiling::scope!("vkGetPhysicalDeviceSurfacePresentModesKHR");
135            match unsafe {
136                self.functor
137                    .get_physical_device_surface_present_modes(adapter.raw, self.raw)
138            } {
139                Ok(present_modes) => present_modes,
140                Err(e) => {
141                    log::error!("get_physical_device_surface_present_modes: {e}");
142                    // Per definition of `SurfaceCapabilities`, there must be at least one present mode.
143                    return None;
144                }
145            }
146        };
147
148        let raw_surface_formats = {
149            profiling::scope!("vkGetPhysicalDeviceSurfaceFormatsKHR");
150            match unsafe {
151                self.functor
152                    .get_physical_device_surface_formats(adapter.raw, self.raw)
153            } {
154                Ok(formats) => formats,
155                Err(e) => {
156                    log::error!("get_physical_device_surface_formats: {e}");
157                    // Per definition of `SurfaceCapabilities`, there must be at least one present format.
158                    return None;
159                }
160            }
161        };
162
163        // Group the driver's (format, color space) pairs into one entry per
164        // format, preserving the driver's format order.
165        let mut formats: Vec<wgt::SurfaceFormatCapabilities> = Vec::new();
166        for (format, color_space) in raw_surface_formats
167            .into_iter()
168            .filter_map(conv::map_vk_surface_formats)
169        {
170            let color_spaces = color_space.to_color_spaces().unwrap();
171            match formats.iter_mut().find(|fc| fc.format == format) {
172                Some(fc) => fc.color_spaces |= color_spaces,
173                None => formats.push(wgt::SurfaceFormatCapabilities {
174                    format,
175                    color_spaces,
176                }),
177            }
178        }
179        Some(crate::SurfaceCapabilities {
180            formats,
181            // TODO: Right now we're always truncating the swap chain
182            // (presumably - we're actually setting the min image count which isn't necessarily the swap chain size)
183            // Instead, we should use extensions when available to wait in present.
184            // See https://github.com/gfx-rs/wgpu/issues/2869
185            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`.
186            current_extent,
187            usage: conv::map_vk_image_usage(caps.supported_usage_flags),
188            present_modes: raw_present_modes
189                .into_iter()
190                .flat_map(conv::map_vk_present_mode)
191                .collect(),
192            composite_alpha_modes: conv::map_vk_composite_alpha(caps.supported_composite_alpha),
193        })
194    }
195
196    unsafe fn create_swapchain(
197        &self,
198        device: &crate::vulkan::Device,
199        config: &crate::SurfaceConfiguration,
200        provided_old_swapchain: Option<Box<dyn Swapchain>>,
201    ) -> Result<Box<dyn Swapchain>, crate::SurfaceError> {
202        profiling::scope!("Device::create_swapchain");
203        let functor = khr::swapchain::Device::new(&self.instance.raw, &device.shared.raw);
204
205        let old_swapchain = provided_old_swapchain
206            .as_ref()
207            .map(|osc| osc.as_any().downcast_ref::<NativeSwapchain>().unwrap().raw)
208            .unwrap_or(vk::SwapchainKHR::null());
209
210        let color_space = conv::map_surface_color_space(config.color_space);
211
212        let original_format = device.shared.private_caps.map_texture_format(config.format);
213        let mut raw_flags = vk::SwapchainCreateFlagsKHR::empty();
214        let mut raw_view_formats: Vec<vk::Format> = vec![];
215        if !config.view_formats.is_empty() {
216            raw_flags |= vk::SwapchainCreateFlagsKHR::MUTABLE_FORMAT;
217            raw_view_formats = config
218                .view_formats
219                .iter()
220                .map(|f| device.shared.private_caps.map_texture_format(*f))
221                .collect();
222            raw_view_formats.push(original_format);
223        }
224
225        let mut info = vk::SwapchainCreateInfoKHR::default()
226            .flags(raw_flags)
227            .surface(self.raw)
228            .min_image_count(config.maximum_frame_latency + 1) // TODO: https://github.com/gfx-rs/wgpu/issues/2869
229            .image_format(original_format)
230            .image_color_space(color_space)
231            .image_extent(vk::Extent2D {
232                width: config.extent.width,
233                height: config.extent.height,
234            })
235            .image_array_layers(config.extent.depth_or_array_layers)
236            .image_usage(conv::map_texture_usage(config.usage))
237            .image_sharing_mode(vk::SharingMode::EXCLUSIVE)
238            .pre_transform(vk::SurfaceTransformFlagsKHR::IDENTITY)
239            .composite_alpha(conv::map_composite_alpha_mode(config.composite_alpha_mode))
240            .present_mode(conv::map_present_mode(config.present_mode))
241            .clipped(true)
242            .old_swapchain(old_swapchain);
243
244        let mut format_list_info = vk::ImageFormatListCreateInfo::default();
245        if !raw_view_formats.is_empty() {
246            format_list_info = format_list_info.view_formats(&raw_view_formats);
247            info = info.push_next(&mut format_list_info);
248        }
249
250        let create_chain = self.next_swapchain_create_chain.lock().take();
251        if let Some(chain) = create_chain {
252            // SAFETY: The contract on `Surface::set_next_swapchain_create_chain()` keeps
253            // the chain valid and unaliased until this swapchain creation returns.
254            info.p_next = unsafe { chain.splice_into(info.p_next) };
255        }
256
257        let result = {
258            profiling::scope!("vkCreateSwapchainKHR");
259            unsafe { functor.create_swapchain(&info, None) }
260        };
261
262        let raw = match result {
263            Ok(swapchain) => swapchain,
264            Err(error) => {
265                return Err(match error {
266                    vk::Result::ERROR_SURFACE_LOST_KHR
267                    | vk::Result::ERROR_INITIALIZATION_FAILED => crate::SurfaceError::Lost,
268                    vk::Result::ERROR_NATIVE_WINDOW_IN_USE_KHR => {
269                        crate::SurfaceError::Other("Native window is in use")
270                    }
271                    // We don't use VK_EXT_image_compression_control
272                    // VK_ERROR_COMPRESSION_EXHAUSTED_EXT
273                    other => map_host_device_oom_and_lost_err(other).into(),
274                });
275            }
276        };
277
278        let images = unsafe { functor.get_swapchain_images(raw) }
279            .map_err(crate::vulkan::map_host_device_oom_err)?;
280
281        // This fence is only used to throttle acquisition on Windows. It is very important to
282        // avoid bad frame pacing when the Vulkan driver is using a DXGI swapchain. See
283        // https://github.com/gfx-rs/wgpu/issues/8310 and
284        // https://github.com/gfx-rs/wgpu/issues/8354 for more details.
285        let fence = if cfg!(target_os = "windows") {
286            let raw = unsafe {
287                device
288                    .shared
289                    .raw
290                    .create_fence(&vk::FenceCreateInfo::default(), None)
291                    .map_err(crate::vulkan::map_host_device_oom_err)?
292            };
293            Some(raw)
294        } else {
295            None
296        };
297
298        // NOTE: It's important that we define the same number of acquire/present semaphores
299        // as we will need to index into them with the image index.
300        let acquire_semaphores = (0..images.len())
301            .map(|i| {
302                SwapchainAcquireSemaphore::new(&device.shared, i)
303                    .map(Mutex::new)
304                    .map(Arc::new)
305            })
306            .collect::<Result<Vec<_>, _>>()?;
307
308        let present_semaphores = (0..images.len())
309            .map(|i| Arc::new(Mutex::new(SwapchainPresentSemaphores::new(i))))
310            .collect::<Vec<_>>();
311
312        Ok(Box::new(NativeSwapchain {
313            raw,
314            functor,
315            device: Arc::clone(&device.shared),
316            images,
317            fence,
318            config: config.clone(),
319            acquire_semaphores,
320            next_acquire_index: 0,
321            present_semaphores,
322            next_present_time: None,
323            next_present_chain: None,
324        }))
325    }
326
327    #[cfg(windows)]
328    fn display_hdr_info(&self) -> Option<wgt::DisplayHdrInfo> {
329        self.hdr_source.as_ref()?.display_hdr_info()
330    }
331
332    fn as_any(&self) -> &dyn Any {
333        self
334    }
335}
336
337pub(crate) struct NativeSwapchain {
338    raw: vk::SwapchainKHR,
339    functor: khr::swapchain::Device,
340    device: Arc<DeviceShared>,
341    images: Vec<vk::Image>,
342    /// Fence used to wait on the acquired image.
343    fence: Option<vk::Fence>,
344    config: crate::SurfaceConfiguration,
345
346    /// Semaphores used between image acquisition and the first submission
347    /// that uses that image. This is indexed using [`next_acquire_index`].
348    ///
349    /// Because we need to provide this to [`vkAcquireNextImageKHR`], we haven't
350    /// received the swapchain image index for the frame yet, so we cannot use
351    /// that to index it.
352    ///
353    /// Before we pass this to [`vkAcquireNextImageKHR`], we ensure that we wait on
354    /// the submission indicated by [`previously_used_submission_index`]. This ensures
355    /// the semaphore is no longer in use before we use it.
356    ///
357    /// [`next_acquire_index`]: NativeSwapchain::next_acquire_index
358    /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR
359    /// [`previously_used_submission_index`]: SwapchainAcquireSemaphore::previously_used_submission_index
360    acquire_semaphores: Vec<Arc<Mutex<SwapchainAcquireSemaphore>>>,
361    /// The index of the next acquire semaphore to use.
362    ///
363    /// This is incremented each time we acquire a new image, and wraps around
364    /// to 0 when it reaches the end of [`acquire_semaphores`].
365    ///
366    /// [`acquire_semaphores`]: NativeSwapchain::acquire_semaphores
367    next_acquire_index: usize,
368
369    /// Semaphore sets used between all submissions that write to an image and
370    /// the presentation of that image.
371    ///
372    /// This is indexed by the swapchain image index returned by
373    /// [`vkAcquireNextImageKHR`].
374    ///
375    /// We know it is safe to use these semaphores because use them
376    /// _after_ the acquire semaphore. Because the acquire semaphore
377    /// has been signaled, the previous presentation using that image
378    /// is known-finished, so this semaphore is no longer in use.
379    ///
380    /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR
381    present_semaphores: Vec<Arc<Mutex<SwapchainPresentSemaphores>>>,
382
383    /// The present timing information which will be set in the next call to [`present()`](crate::Queue::present()).
384    ///
385    /// # Safety
386    ///
387    /// This must only be set if [`wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING`] is enabled, and
388    /// so the VK_GOOGLE_display_timing extension is present.
389    next_present_time: Option<vk::PresentTimeGOOGLE>,
390
391    /// A caller-provided `pNext` chain to attach to the [`vk::PresentInfoKHR`] of the next
392    /// call to [`present()`](crate::Queue::present()).
393    ///
394    /// Set only through
395    /// [`Surface::set_next_present_chain()`](crate::vulkan::Surface::set_next_present_chain).
396    next_present_chain: Option<PnextChain>,
397}
398
399impl Drop for NativeSwapchain {
400    fn drop(&mut self) {
401        unsafe {
402            self.functor.destroy_swapchain(self.raw, None);
403        }
404    }
405}
406
407impl Swapchain for NativeSwapchain {
408    unsafe fn release_resources(&mut self, device: &crate::vulkan::Device) {
409        profiling::scope!("Swapchain::release_resources");
410        {
411            profiling::scope!("vkDeviceWaitIdle");
412            // We need to also wait until all presentation work is done. Because there is no way to portably wait until
413            // the presentation work is done, we are forced to wait until the device is idle.
414            let _ = unsafe {
415                device
416                    .shared
417                    .raw
418                    .device_wait_idle()
419                    .map_err(map_host_device_oom_and_lost_err)
420            };
421        };
422
423        if let Some(fence) = self.fence {
424            unsafe { device.shared.raw.destroy_fence(fence, None) }
425        }
426
427        // We cannot take this by value, as the function returns `self`.
428        for semaphore in self.acquire_semaphores.drain(..) {
429            let arc_removed = Arc::into_inner(semaphore).expect(
430                "Trying to destroy a SwapchainAcquireSemaphore that is still in use by a SurfaceTexture",
431            );
432            let mutex_removed = arc_removed.into_inner();
433
434            unsafe { mutex_removed.destroy(&device.shared.raw) };
435        }
436
437        for semaphore in self.present_semaphores.drain(..) {
438            let arc_removed = Arc::into_inner(semaphore).expect(
439                "Trying to destroy a SwapchainPresentSemaphores that is still in use by a SurfaceTexture",
440            );
441            let mutex_removed = arc_removed.into_inner();
442
443            unsafe { mutex_removed.destroy(&device.shared.raw) };
444        }
445    }
446
447    unsafe fn acquire(
448        &mut self,
449        timeout: Option<core::time::Duration>,
450        fence: &crate::vulkan::Fence,
451    ) -> Result<crate::AcquiredSurfaceTexture<crate::api::Vulkan>, crate::SurfaceError> {
452        let mut timeout_ns = match timeout {
453            Some(duration) => duration.as_nanos() as u64,
454            None => u64::MAX,
455        };
456
457        // AcquireNextImageKHR on Android (prior to Android 11) doesn't support timeouts
458        // and will also log verbose warnings if tying to use a timeout.
459        //
460        // Android 10 implementation for reference:
461        // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-10.0.0_r13/vulkan/libvulkan/swapchain.cpp#1426
462        // Android 11 implementation for reference:
463        // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-11.0.0_r45/vulkan/libvulkan/swapchain.cpp#1438
464        //
465        // Android 11 corresponds to an SDK_INT/ro.build.version.sdk of 30
466        if cfg!(target_os = "android") && self.device.instance.android_sdk_version < 30 {
467            timeout_ns = u64::MAX;
468        }
469
470        let acquire_semaphore_arc = self.get_acquire_semaphore();
471        // Nothing should be using this, so we don't block, but panic if we fail to lock.
472        let acquire_semaphore_guard = acquire_semaphore_arc
473            .try_lock()
474            .expect("Failed to lock a SwapchainSemaphores.");
475
476        // Wait for all commands writing to the previously acquired image to
477        // complete.
478        //
479        // Almost all the steps in the usual acquire-draw-present flow are
480        // asynchronous: they get something started on the presentation engine
481        // or the GPU, but on the CPU, control returns immediately. Without some
482        // sort of intervention, the CPU could crank out frames much faster than
483        // the presentation engine can display them.
484        //
485        // This is the intervention: if any submissions drew on this image, and
486        // thus waited for `locked_swapchain_semaphores.acquire`, wait for all
487        // of them to finish, thus ensuring that it's okay to pass `acquire` to
488        // `vkAcquireNextImageKHR` again.
489        let completed = self.device.wait_for_fence(
490            fence,
491            acquire_semaphore_guard.previously_used_submission_index,
492            timeout_ns,
493        )?;
494        if !completed {
495            return Err(crate::SurfaceError::Timeout);
496        }
497
498        let acquire_fence = self.fence.unwrap_or_else(vk::Fence::null);
499
500        // will block if no image is available
501        let (index, suboptimal) = match unsafe {
502            profiling::scope!("vkAcquireNextImageKHR");
503            self.functor.acquire_next_image(
504                self.raw,
505                timeout_ns,
506                acquire_semaphore_guard.acquire,
507                acquire_fence,
508            )
509        } {
510            // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android.
511            // See the comment in `Queue::present`.
512            #[cfg(target_os = "android")]
513            Ok((index, _)) => (index, false),
514            #[cfg(not(target_os = "android"))]
515            Ok(pair) => pair,
516            Err(error) => {
517                return match error {
518                    vk::Result::TIMEOUT => Err(crate::SurfaceError::Timeout),
519                    vk::Result::NOT_READY | vk::Result::ERROR_OUT_OF_DATE_KHR => {
520                        Err(crate::SurfaceError::Outdated)
521                    }
522                    vk::Result::ERROR_SURFACE_LOST_KHR => Err(crate::SurfaceError::Lost),
523                    // We don't use VK_EXT_full_screen_exclusive
524                    // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT
525                    other => Err(map_host_device_oom_and_lost_err(other).into()),
526                };
527            }
528        };
529
530        if let Some(fence) = self.fence {
531            unsafe {
532                // The `wait_all` argument must be `true` to avoid crash on some Android devices. See https://github.com/gfx-rs/wgpu/pull/8769
533                self.device
534                    .raw
535                    .wait_for_fences(&[fence], true, timeout_ns)
536                    .map_err(map_host_device_oom_and_lost_err)?;
537
538                self.device
539                    .raw
540                    .reset_fences(&[fence])
541                    .map_err(map_host_device_oom_and_lost_err)?;
542            }
543        }
544
545        drop(acquire_semaphore_guard);
546        // We only advance the surface semaphores if we successfully acquired an image, otherwise
547        // we should try to re-acquire using the same semaphores.
548        self.advance_acquire_semaphore();
549
550        let present_semaphore_arc = self.get_present_semaphores(index);
551
552        // special case for Intel Vulkan returning bizarre values (ugh)
553        if self.device.vendor_id == crate::auxil::db::intel::VENDOR && index > 0x100 {
554            return Err(crate::SurfaceError::Outdated);
555        }
556
557        let identity = self.device.texture_identity_factory.next();
558
559        let texture = crate::vulkan::SurfaceTexture {
560            index,
561            texture: crate::vulkan::Texture {
562                raw: self.images[index as usize],
563                drop_guard: None,
564                memory: crate::vulkan::TextureMemory::External,
565                format: self.config.format,
566                copy_size: crate::CopyExtent {
567                    width: self.config.extent.width,
568                    height: self.config.extent.height,
569                    depth: 1,
570                },
571                identity,
572            },
573            metadata: Box::new(NativeSurfaceTextureMetadata {
574                acquire_semaphores: acquire_semaphore_arc,
575                present_semaphores: present_semaphore_arc,
576            }),
577        };
578        Ok(crate::AcquiredSurfaceTexture {
579            texture,
580            suboptimal,
581        })
582    }
583
584    unsafe fn discard_texture(
585        &mut self,
586        _texture: crate::vulkan::SurfaceTexture,
587    ) -> Result<(), crate::SurfaceError> {
588        // TODO: Current implementation no-ops
589        Ok(())
590    }
591
592    unsafe fn present(
593        &mut self,
594        queue: &crate::vulkan::Queue,
595        texture: crate::vulkan::SurfaceTexture,
596    ) -> Result<(), crate::SurfaceError> {
597        let metadata = texture
598            .metadata
599            .as_any()
600            .downcast_ref::<NativeSurfaceTextureMetadata>()
601            .unwrap();
602        let mut acquire_semaphore = metadata.acquire_semaphores.lock();
603        let mut present_semaphores = metadata.present_semaphores.lock();
604
605        let wait_semaphores = present_semaphores.get_present_wait_semaphores();
606
607        // Reset the acquire and present semaphores internal state
608        // to be ready for the next frame.
609        //
610        // We do this before the actual call to present to ensure that
611        // even if this method errors and early outs, we have reset
612        // the state for next frame.
613        acquire_semaphore.end_semaphore_usage();
614        present_semaphores.end_semaphore_usage();
615
616        drop(acquire_semaphore);
617
618        let swapchains = [self.raw];
619        let image_indices = [texture.index];
620        let vk_info = vk::PresentInfoKHR::default()
621            .swapchains(&swapchains)
622            .image_indices(&image_indices)
623            .wait_semaphores(&wait_semaphores);
624
625        let mut display_timing;
626        let present_times;
627        let mut vk_info = if let Some(present_time) = self.next_present_time.take() {
628            debug_assert!(
629                self.device
630                    .features
631                    .contains(wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING),
632                "`next_present_time` should only be set if `VULKAN_GOOGLE_DISPLAY_TIMING` is enabled"
633            );
634            present_times = [present_time];
635            display_timing = vk::PresentTimesInfoGOOGLE::default().times(&present_times);
636            // SAFETY: We know that VK_GOOGLE_display_timing is present because of the safety contract on `next_present_time`.
637            vk_info.push_next(&mut display_timing)
638        } else {
639            vk_info
640        };
641
642        if let Some(chain) = self.next_present_chain.take() {
643            // SAFETY: The contract on `Surface::set_next_present_chain()` keeps the chain
644            // valid and unaliased until this present completes.
645            vk_info.p_next = unsafe { chain.splice_into(vk_info.p_next) };
646        }
647
648        let suboptimal = {
649            profiling::scope!("vkQueuePresentKHR");
650            unsafe { self.functor.queue_present(queue.raw, &vk_info) }.map_err(|error| {
651                match error {
652                    vk::Result::ERROR_OUT_OF_DATE_KHR => crate::SurfaceError::Outdated,
653                    vk::Result::ERROR_SURFACE_LOST_KHR => crate::SurfaceError::Lost,
654                    // We don't use VK_EXT_full_screen_exclusive
655                    // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT
656                    _ => map_host_device_oom_and_lost_err(error).into(),
657                }
658            })?
659        };
660        if suboptimal {
661            // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android.
662            // On Android 10+, libvulkan's `vkQueuePresentKHR` implementation returns `VK_SUBOPTIMAL_KHR` if not doing pre-rotation
663            // (i.e `VkSwapchainCreateInfoKHR::preTransform` not being equal to the current device orientation).
664            // This is always the case when the device orientation is anything other than the identity one, as we unconditionally use `VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR`.
665            #[cfg(not(target_os = "android"))]
666            log::debug!("Suboptimal present of frame {}", texture.index);
667        }
668        Ok(())
669    }
670
671    fn as_any(&self) -> &dyn Any {
672        self
673    }
674
675    fn as_any_mut(&mut self) -> &mut dyn Any {
676        self
677    }
678}
679
680impl NativeSwapchain {
681    pub(crate) fn as_raw(&self) -> vk::SwapchainKHR {
682        self.raw
683    }
684
685    pub fn set_next_present_time(&mut self, present_timing: vk::PresentTimeGOOGLE) {
686        let features = wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING;
687        if self.device.features.contains(features) {
688            self.next_present_time = Some(present_timing);
689        } else {
690            // Ideally we'd use something like `device.required_features` here, but that's in `wgpu-core`, which we are a dependency of
691            panic!(
692                concat!(
693                    "Tried to set display timing properties ",
694                    "without the corresponding feature ({:?}) enabled."
695                ),
696                features
697            );
698        }
699    }
700
701    /// # Safety
702    ///
703    /// See [`Surface::set_next_present_chain()`](crate::vulkan::Surface::set_next_present_chain).
704    pub unsafe fn set_next_present_chain(&mut self, chain: *mut core::ffi::c_void) {
705        self.next_present_chain = Some(PnextChain::new(chain));
706    }
707
708    /// Mark the current frame finished, advancing to the next acquire semaphore.
709    fn advance_acquire_semaphore(&mut self) {
710        let semaphore_count = self.acquire_semaphores.len();
711        self.next_acquire_index = (self.next_acquire_index + 1) % semaphore_count;
712    }
713
714    /// Get the next acquire semaphore that should be used with this swapchain.
715    fn get_acquire_semaphore(&self) -> Arc<Mutex<SwapchainAcquireSemaphore>> {
716        self.acquire_semaphores[self.next_acquire_index].clone()
717    }
718
719    /// Get the set of present semaphores that should be used with the given image index.
720    fn get_present_semaphores(&self, index: u32) -> Arc<Mutex<SwapchainPresentSemaphores>> {
721        self.present_semaphores[index as usize].clone()
722    }
723}
724
725/// Semaphore used to acquire a swapchain image.
726#[derive(Debug)]
727struct SwapchainAcquireSemaphore {
728    /// A semaphore that is signaled when this image is safe for us to modify.
729    ///
730    /// When [`vkAcquireNextImageKHR`] returns the index of the next swapchain
731    /// image that we should use, that image may actually still be in use by the
732    /// presentation engine, and is not yet safe to modify. However, that
733    /// function does accept a semaphore that it will signal when the image is
734    /// indeed safe to begin messing with.
735    ///
736    /// This semaphore is:
737    ///
738    /// - waited for by the first queue submission to operate on this image
739    ///   since it was acquired, and
740    ///
741    /// - signaled by [`vkAcquireNextImageKHR`] when the acquired image is ready
742    ///   for us to use.
743    ///
744    /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR
745    acquire: vk::Semaphore,
746
747    /// True if the next command submission operating on this image should wait
748    /// for [`acquire`].
749    ///
750    /// We must wait for `acquire` before drawing to this swapchain image, but
751    /// because `wgpu-hal` queue submissions are always strongly ordered, only
752    /// the first submission that works with a swapchain image actually needs to
753    /// wait. We set this flag when this image is acquired, and clear it the
754    /// first time it's passed to [`Queue::submit`] as a surface texture.
755    ///
756    /// Additionally, semaphores can only be waited on once, so we need to ensure
757    /// that we only actually pass this semaphore to the first submission that
758    /// uses that image.
759    ///
760    /// [`acquire`]: SwapchainAcquireSemaphore::acquire
761    /// [`Queue::submit`]: crate::Queue::submit
762    should_wait_for_acquire: bool,
763
764    /// The fence value of the last command submission that wrote to this image.
765    ///
766    /// The next time we try to acquire this image, we'll block until
767    /// this submission finishes, proving that [`acquire`] is ready to
768    /// pass to `vkAcquireNextImageKHR` again.
769    ///
770    /// [`acquire`]: SwapchainAcquireSemaphore::acquire
771    previously_used_submission_index: crate::FenceValue,
772}
773
774impl SwapchainAcquireSemaphore {
775    fn new(device: &DeviceShared, index: usize) -> Result<Self, crate::DeviceError> {
776        Ok(Self {
777            acquire: device
778                .new_binary_semaphore(&format!("SwapchainImageSemaphore: Index {index} acquire"))?,
779            should_wait_for_acquire: true,
780            previously_used_submission_index: 0,
781        })
782    }
783
784    /// Sets the fence value which the next acquire will wait for. This prevents
785    /// the semaphore from being used while the previous submission is still in flight.
786    fn set_used_fence_value(&mut self, value: crate::FenceValue) {
787        self.previously_used_submission_index = value;
788    }
789
790    /// Return the semaphore that commands drawing to this image should wait for, if any.
791    ///
792    /// This only returns `Some` once per acquisition; see
793    /// [`SwapchainAcquireSemaphore::should_wait_for_acquire`] for details.
794    fn get_acquire_wait_semaphore(&mut self) -> Option<vk::Semaphore> {
795        if self.should_wait_for_acquire {
796            self.should_wait_for_acquire = false;
797            Some(self.acquire)
798        } else {
799            None
800        }
801    }
802
803    /// Indicates the cpu-side usage of this semaphore has finished for the frame,
804    /// so reset internal state to be ready for the next frame.
805    fn end_semaphore_usage(&mut self) {
806        // Reset the acquire semaphore, so that the next time we acquire this
807        // image, we can wait for it again.
808        self.should_wait_for_acquire = true;
809    }
810
811    unsafe fn destroy(&self, device: &ash::Device) {
812        unsafe {
813            device.destroy_semaphore(self.acquire, None);
814        }
815    }
816}
817
818#[derive(Debug)]
819struct SwapchainPresentSemaphores {
820    /// A pool of semaphores for ordering presentation after drawing.
821    ///
822    /// The first [`present_index`] semaphores in this vector are:
823    ///
824    /// - all waited on by the call to [`vkQueuePresentKHR`] that presents this
825    ///   image, and
826    ///
827    /// - each signaled by some [`vkQueueSubmit`] queue submission that draws to
828    ///   this image, when the submission finishes execution.
829    ///
830    /// This vector accumulates one semaphore per submission that writes to this
831    /// image. This is awkward, but hard to avoid: [`vkQueuePresentKHR`]
832    /// requires a semaphore to order it with respect to drawing commands, and
833    /// we can't attach new completion semaphores to a command submission after
834    /// it's been submitted. This means that, at submission time, we must create
835    /// the semaphore we might need if the caller's next action is to enqueue a
836    /// presentation of this image.
837    ///
838    /// An alternative strategy would be for presentation to enqueue an empty
839    /// submit, ordered relative to other submits in the usual way, and
840    /// signaling a single presentation semaphore. But we suspect that submits
841    /// are usually expensive enough, and semaphores usually cheap enough, that
842    /// performance-sensitive users will avoid making many submits, so that the
843    /// cost of accumulated semaphores will usually be less than the cost of an
844    /// additional submit.
845    ///
846    /// Only the first [`present_index`] semaphores in the vector are actually
847    /// going to be signalled by submitted commands, and need to be waited for
848    /// by the next present call. Any semaphores beyond that index were created
849    /// for prior presents and are simply being retained for recycling.
850    ///
851    /// [`present_index`]: SwapchainPresentSemaphores::present_index
852    /// [`vkQueuePresentKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueuePresentKHR
853    /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit
854    present: Vec<vk::Semaphore>,
855
856    /// The number of semaphores in [`present`] to be signalled for this submission.
857    ///
858    /// [`present`]: SwapchainPresentSemaphores::present
859    present_index: usize,
860
861    /// Which image this semaphore set is used for.
862    frame_index: usize,
863}
864
865impl SwapchainPresentSemaphores {
866    pub fn new(frame_index: usize) -> Self {
867        Self {
868            present: Vec::new(),
869            present_index: 0,
870            frame_index,
871        }
872    }
873
874    /// Return the semaphore that the next submission that writes to this image should
875    /// signal when it's done.
876    ///
877    /// See [`SwapchainPresentSemaphores::present`] for details.
878    fn get_submit_signal_semaphore(
879        &mut self,
880        device: &DeviceShared,
881    ) -> Result<vk::Semaphore, crate::DeviceError> {
882        // Try to recycle a semaphore we created for a previous presentation.
883        let sem = match self.present.get(self.present_index) {
884            Some(sem) => *sem,
885            None => {
886                let sem = device.new_binary_semaphore(&format!(
887                    "SwapchainImageSemaphore: Image {} present semaphore {}",
888                    self.frame_index, self.present_index
889                ))?;
890                self.present.push(sem);
891                sem
892            }
893        };
894
895        self.present_index += 1;
896
897        Ok(sem)
898    }
899
900    /// Indicates the cpu-side usage of this semaphore has finished for the frame,
901    /// so reset internal state to be ready for the next frame.
902    fn end_semaphore_usage(&mut self) {
903        // Reset the index to 0, so that the next time we get a semaphore, we
904        // start from the beginning of the list.
905        self.present_index = 0;
906    }
907
908    /// Return the semaphores that a presentation of this image should wait on.
909    ///
910    /// Return a slice of semaphores that the call to [`vkQueueSubmit`] that
911    /// ends this image's acquisition should wait for. See
912    /// [`SwapchainPresentSemaphores::present`] for details.
913    ///
914    /// Reset `self` to be ready for the next acquisition cycle.
915    ///
916    /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit
917    fn get_present_wait_semaphores(&mut self) -> Vec<vk::Semaphore> {
918        self.present[0..self.present_index].to_vec()
919    }
920
921    unsafe fn destroy(&self, device: &ash::Device) {
922        unsafe {
923            for sem in &self.present {
924                device.destroy_semaphore(*sem, None);
925            }
926        }
927    }
928}
929
930#[derive(Debug)]
931struct NativeSurfaceTextureMetadata {
932    acquire_semaphores: Arc<Mutex<SwapchainAcquireSemaphore>>,
933    present_semaphores: Arc<Mutex<SwapchainPresentSemaphores>>,
934}
935
936impl SurfaceTextureMetadata for NativeSurfaceTextureMetadata {
937    fn get_semaphore_guard(&self) -> Box<dyn SwapchainSubmissionSemaphoreGuard + '_> {
938        Box::new(NativeSwapchainSubmissionSemaphoreGuard {
939            acquire_semaphore_guard: self
940                .acquire_semaphores
941                .try_lock()
942                .expect("Failed to lock surface acquire semaphore"),
943            present_semaphores_guard: self
944                .present_semaphores
945                .try_lock()
946                .expect("Failed to lock surface present semaphores"),
947        })
948    }
949
950    fn as_any(&self) -> &dyn Any {
951        self
952    }
953}
954
955struct NativeSwapchainSubmissionSemaphoreGuard<'a> {
956    acquire_semaphore_guard: MutexGuard<'a, SwapchainAcquireSemaphore>,
957    present_semaphores_guard: MutexGuard<'a, SwapchainPresentSemaphores>,
958}
959
960impl<'a> SwapchainSubmissionSemaphoreGuard for NativeSwapchainSubmissionSemaphoreGuard<'a> {
961    fn set_used_fence_value(&mut self, value: u64) {
962        self.acquire_semaphore_guard.set_used_fence_value(value);
963    }
964
965    fn get_acquire_wait_semaphore(&mut self) -> Option<SemaphoreType> {
966        self.acquire_semaphore_guard
967            .get_acquire_wait_semaphore()
968            .map(SemaphoreType::Binary)
969    }
970
971    fn get_submit_signal_semaphore(
972        &mut self,
973        device: &DeviceShared,
974    ) -> Result<SemaphoreType, crate::DeviceError> {
975        self.present_semaphores_guard
976            .get_submit_signal_semaphore(device)
977            .map(SemaphoreType::Binary)
978    }
979}