1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use {
    crate::graphics::GraphicsError,
    anyhow::Context,
    ash::{extensions, vk},
    ccthw_ash_instance::{PhysicalDevice, VulkanHandle, VulkanInstance},
};

/// The surface targeted by this application and the Ash extension loader which
/// provides access to KHR surface functions.
pub(super) struct WindowSurface {
    surface: vk::SurfaceKHR,
    surface_loader: extensions::khr::Surface,
}

// Public API
// ----------

impl WindowSurface {
    /// Load Vulkan extension functions for interacting with a presentable
    /// surface.
    ///
    /// # Params
    ///
    /// * `instance` - the Vulkan entrypoint for this application
    /// * `surface` - the surface which will be used for presentation. Typically
    ///   provided by the windowing system.
    ///
    /// # Safety
    ///
    /// The application must destroy the surface before the instance is
    /// destroyed.
    pub unsafe fn new(
        instance: &VulkanInstance,
        surface: vk::SurfaceKHR,
    ) -> Self {
        let surface_loader =
            extensions::khr::Surface::new(instance.entry(), instance.ash());
        Self {
            surface,
            surface_loader,
        }
    }

    /// Check that a physical device can present swapchain images to the window
    /// surface.
    ///
    /// # Params
    ///
    /// * `physical_device` - the physical device to check for support
    /// * `queue_family_index` - the queue family which will be used for
    ///   presentation. It is possible that the device supports presentation on
    ///   only a subset of all available queue families.
    ///
    /// # Safety
    ///
    /// Unsafe because the queue family index is assumed to be valid and the
    /// physical_device is assumed to still exist.
    pub unsafe fn get_physical_device_surface_support(
        &self,
        physical_device: &PhysicalDevice,
        queue_family_index: usize,
    ) -> Result<bool, GraphicsError> {
        let is_supported = self
            .surface_loader
            .get_physical_device_surface_support(
                *physical_device.raw(),
                queue_family_index as u32,
                self.surface,
            )
            .context("Error checking for physical device surface support!")?;
        Ok(is_supported)
    }

    /// Get the supported surface formats for the given physical device.
    ///
    /// # Params
    ///
    /// * `physical_device` - the physical device used to present images to the
    ///   surface
    ///
    /// # Safety
    ///
    /// Unsafe because:
    ///   - the caller must check that the physical device can present to the
    ///     window surface before calling this method.
    pub unsafe fn get_physical_device_surface_formats(
        &self,
        physical_device: &PhysicalDevice,
    ) -> Result<Vec<vk::SurfaceFormatKHR>, GraphicsError> {
        let formats = self
            .surface_loader
            .get_physical_device_surface_formats(
                *physical_device.raw(),
                self.surface,
            )
            .context("Error while getting device surface formats!")?;
        Ok(formats)
    }

    /// Get the supported surface presentation modes for the given physical
    /// device.
    ///
    /// # Params
    ///
    /// * `physical_device` - the physical device used to present images to the
    ///   suface
    ///
    /// # Safety
    ///
    /// Unsafe because:
    ///   - the caller must check that the physical device can present to the
    ///     window surface before calling this method.
    pub unsafe fn get_physical_device_surface_present_modes(
        &self,
        physical_device: &PhysicalDevice,
    ) -> Result<Vec<vk::PresentModeKHR>, GraphicsError> {
        let modes = self
            .surface_loader
            .get_physical_device_surface_present_modes(
                *physical_device.raw(),
                self.surface,
            )
            .context("Error while getting device surface present modes!")?;
        Ok(modes)
    }

    /// Get the surface capabilities for a given physical device.
    ///
    /// # Params
    ///
    /// * `physical_device` - the physical device used to present images to the
    ///   suface
    ///
    /// # Safety
    ///
    /// Unsafe because:
    ///   - the caller must check that the physical device can present to the
    ///     window surface before calling this method.
    pub unsafe fn get_surface_capabilities(
        &self,
        physical_device: &PhysicalDevice,
    ) -> Result<vk::SurfaceCapabilitiesKHR, GraphicsError> {
        let capabilities = self
            .surface_loader
            .get_physical_device_surface_capabilities(
                *physical_device.raw(),
                self.surface,
            )
            .context("Error getting device surface capabilities!")?;
        Ok(capabilities)
    }
}

impl Drop for WindowSurface {
    /// Destroy the surface.
    ///
    /// # Safety
    ///
    /// Unsafe because:
    ///   - It is undefined behavior to use this type after calling destroy.
    ///   - The application must synchronize GPU resources to ensure no pending
    ///     GPU operations still depend on the surface when it's destroyed.
    ///   - The application must destroy the surface before destroying the
    ///     Vulkan instance.
    fn drop(&mut self) {
        unsafe {
            self.surface_loader.destroy_surface(self.surface, None);
        }
    }
}

impl std::fmt::Debug for WindowSurface {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WindowSurface")
            .field("surface", &self.surface)
            .finish()
    }
}

impl VulkanHandle for WindowSurface {
    type Handle = vk::SurfaceKHR;

    unsafe fn raw(&self) -> &Self::Handle {
        &self.surface
    }
}

// Private API
// -----------