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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
mod settings;

use {
    crate::{
        graphics::vulkan::{raii, VulkanContext},
        trace,
    },
    anyhow::{anyhow, Context, Result},
    ash::vk,
    std::sync::Arc,
};

#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum AcquireImageStatus {
    ImageAcquired(u32),
    SwapchainNeedsRebuild,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum PresentImageStatus {
    Queued,
    SwapchainNeedsRebuild,
}

/// The Vulkan swapchain and associated resources.
pub struct Swapchain {
    swapchain: Arc<raii::Swapchain>,
    extent: vk::Extent2D,
    format: vk::SurfaceFormatKHR,
    images: Vec<vk::Image>,
    image_views: Vec<raii::ImageView>,
    cxt: Arc<VulkanContext>,
}

impl Swapchain {
    /// Creates a new Vulkan swapchain.
    pub fn new(
        cxt: Arc<VulkanContext>,
        framebuffer_size: (u32, u32),
        previous_swapchain: Option<vk::SwapchainKHR>,
    ) -> Result<Self> {
        let (swapchain, extent, format) = settings::create_swapchain(
            &cxt,
            framebuffer_size,
            previous_swapchain,
        )
        .with_context(trace!("Unable to initialize swapchain!"))?;

        let images =
            unsafe { swapchain.ext.get_swapchain_images(swapchain.raw)? };
        let mut image_views = vec![];
        for image in &images {
            let create_info = vk::ImageViewCreateInfo {
                image: *image,
                view_type: vk::ImageViewType::TYPE_2D,
                format: format.format,
                components: vk::ComponentMapping::default(),
                subresource_range: vk::ImageSubresourceRange {
                    aspect_mask: vk::ImageAspectFlags::COLOR,
                    base_mip_level: 0,
                    level_count: 1,
                    base_array_layer: 0,
                    layer_count: 1,
                },
                ..Default::default()
            };
            image_views
                .push(raii::ImageView::new(cxt.device.clone(), &create_info)?);
        }

        Ok(Self {
            swapchain,
            extent,
            format,
            images,
            image_views,
            cxt,
        })
    }

    /// Returns the non-owning Vulkan swapchain handle.
    pub fn raw(&self) -> vk::SwapchainKHR {
        self.swapchain.raw
    }

    /// Returns the Swapchain's current extent.
    pub fn extent(&self) -> vk::Extent2D {
        self.extent
    }

    /// Returns a scissor rect for the full swapchain extent.
    pub fn scissor(&self) -> vk::Rect2D {
        vk::Rect2D {
            offset: vk::Offset2D { x: 0, y: 0 },
            extent: self.extent,
        }
    }

    pub fn viewport(&self) -> vk::Viewport {
        vk::Viewport {
            x: 0.0,
            y: 0.0,
            width: self.extent.width as f32,
            height: self.extent.height as f32,
            min_depth: 0.0,
            max_depth: 1.0,
        }
    }

    /// Returns the Swapchain's image format.
    pub fn format(&self) -> vk::Format {
        self.format.format
    }

    /// Returns the Swapchain's image handles.
    pub fn images(&self) -> &[vk::Image] {
        &self.images
    }

    /// Returns the Swapchain's image views.
    ///
    /// Views are paired 1-1 with images of the same index.
    pub fn image_views(&self) -> &[raii::ImageView] {
        &self.image_views
    }

    /// Acquires the index for the next swapchain image.
    ///
    /// * `image_ready_semaphore` - A Vulkan semaphore to signal when the
    ///   swapchain image is ready. This can be `vk::Semaphore::null()` if not
    ///   required.
    pub fn acquire_image(
        &self,
        image_ready_semaphore: vk::Semaphore,
    ) -> Result<AcquireImageStatus> {
        let result = unsafe {
            self.swapchain.ext.acquire_next_image(
                self.swapchain.raw,
                u64::MAX,
                image_ready_semaphore,
                vk::Fence::null(),
            )
        };
        match result {
            Ok((index, false)) => Ok(AcquireImageStatus::ImageAcquired(index)),
            Ok((_, true)) => {
                // true indicates that the swapchain is suboptimal
                Ok(AcquireImageStatus::SwapchainNeedsRebuild)
            }
            Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => {
                Ok(AcquireImageStatus::SwapchainNeedsRebuild)
            }
            Err(err) => Err(anyhow!(err))
                .with_context(trace!("Unable to acquire swapchain image!")),
        }
    }

    /// Presents the swapchain image.
    ///
    /// * `wait_semaphore` - Image presentation waits for the semaphore to be
    ///   signalled.
    /// * `image_index` - The index of the swapchain image being presented. This
    ///   must come from a prior call to [Self::acquire_image].
    pub fn present_image(
        &self,
        wait_semaphore: vk::Semaphore,
        image_index: u32,
    ) -> Result<PresentImageStatus> {
        let present_info = vk::PresentInfoKHR {
            wait_semaphore_count: 1,
            p_wait_semaphores: &wait_semaphore,
            swapchain_count: 1,
            p_swapchains: &self.swapchain.raw,
            p_image_indices: &image_index,
            ..Default::default()
        };
        let result = unsafe {
            self.swapchain
                .ext
                .queue_present(self.cxt.graphics_queue, &present_info)
        };
        match result {
            Ok(false) => Ok(PresentImageStatus::Queued),
            Ok(true) => Ok(PresentImageStatus::SwapchainNeedsRebuild),
            Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => {
                Ok(PresentImageStatus::SwapchainNeedsRebuild)
            }
            Err(err) => Err(err)
                .with_context(trace!("Unable to present swapchain image!")),
        }
    }
}

impl std::fmt::Debug for Swapchain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Swapchain")
            .field("swapchain", &self.swapchain)
            .field("extent", &self.extent)
            .field("format", &self.format)
            .field("images", &self.images)
            .field("image_views", &self.image_views)
            .finish()
    }
}