-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathswapchain.rs
More file actions
348 lines (317 loc) · 13.3 KB
/
swapchain.rs
File metadata and controls
348 lines (317 loc) · 13.3 KB
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use crate::ash_renderer::device::MyDevice;
use anyhow::Context;
use ash::vk;
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use std::sync::Arc;
/// A binary semaphore for swapchain operations
struct SwapchainSync {
acquire_semaphore: vk::Semaphore,
render_semaphore: vk::Semaphore,
render_fence: vk::Fence,
}
impl SwapchainSync {
unsafe fn new(device: &MyDevice) -> anyhow::Result<Self> {
unsafe {
let signaled_fence =
vk::FenceCreateInfo::default().flags(vk::FenceCreateFlags::SIGNALED);
Ok(Self {
acquire_semaphore: device
.create_semaphore(&vk::SemaphoreCreateInfo::default(), None)?,
render_semaphore: device
.create_semaphore(&vk::SemaphoreCreateInfo::default(), None)?,
render_fence: device.create_fence(&signaled_fence, None)?,
})
}
}
unsafe fn destroy(&self, device: &MyDevice) {
unsafe {
device.destroy_semaphore(self.acquire_semaphore, None);
device.destroy_semaphore(self.render_semaphore, None);
device.destroy_fence(self.render_fence, None);
}
}
}
/// Takes care of all things swapchain related
///
/// Intentionally kept simple and does not offer support for multiple frames in flight
pub struct MySwapchainManager {
pub device: Arc<MyDevice>,
pub window: winit::window::Window,
pub surface: vk::SurfaceKHR,
pub surface_format: vk::SurfaceFormatKHR,
pub surface_capabilities: vk::SurfaceCapabilitiesKHR,
pub present_mode: vk::PresentModeKHR,
pub image_count: u32,
pub pre_transform: vk::SurfaceTransformFlagsKHR,
// state below
active: Option<ActiveSwapchain>,
should_recreate: bool,
sync: SwapchainSync,
}
struct ActiveSwapchain {
extent: vk::Extent2D,
swapchain: vk::SwapchainKHR,
images: Vec<(vk::Image, vk::ImageView)>,
}
impl MySwapchainManager {
pub fn new(device: Arc<MyDevice>, window: winit::window::Window) -> anyhow::Result<Self> {
unsafe {
let surface_ext = &device.surface_ext;
let surface = ash_window::create_surface(
&device.entry,
&device.instance,
window.display_handle().unwrap().into(),
window.window_handle().unwrap().into(),
None,
)
.context("create_surface")?;
let surface_format = {
let acceptable_formats = {
[
vk::Format::R8G8B8_SRGB,
vk::Format::B8G8R8_SRGB,
vk::Format::R8G8B8A8_SRGB,
vk::Format::B8G8R8A8_SRGB,
vk::Format::A8B8G8R8_SRGB_PACK32,
]
};
*surface_ext
.get_physical_device_surface_formats(device.physical_device, surface)?
.iter()
.find(|sfmt| acceptable_formats.contains(&sfmt.format))
.context("Unable to find suitable surface format.")?
};
let surface_capabilities = surface_ext
.get_physical_device_surface_capabilities(device.physical_device, surface)?;
let pre_transform = surface_capabilities.current_transform;
let present_mode = surface_ext
.get_physical_device_surface_present_modes(device.physical_device, surface)?
.iter()
.cloned()
// Mailbox is preferred
.find(|&mode| mode == vk::PresentModeKHR::MAILBOX)
// FIFO is guaranteed to be available
.unwrap_or(vk::PresentModeKHR::FIFO);
let image_count = {
let mut image_count = match present_mode {
// tripple buffering in mailbox mode:: one presenting, one ready and one drawing
vk::PresentModeKHR::MAILBOX => 3,
// double buffering in fifo mode: one presenting, one drawing
vk::PresentModeKHR::FIFO => 2,
_ => unreachable!(),
};
if surface_capabilities.max_image_count != 0 {
image_count = image_count.min(surface_capabilities.max_image_count);
}
image_count.max(surface_capabilities.min_image_count)
};
let sync = SwapchainSync::new(&device)?;
Ok(Self {
device,
window,
surface,
surface_format,
surface_capabilities,
present_mode,
image_count,
pre_transform,
active: None,
should_recreate: true,
sync,
})
}
}
#[inline]
pub fn should_recreate(&mut self) {
self.should_recreate = true;
}
/// After this function is called, `Self.active` is initialized
unsafe fn recreate_swapchain(&mut self) -> anyhow::Result<()> {
unsafe {
let device = &self.device;
let swapchain_ext = &device.swapchain_ext;
let surface_ext = &self.device.surface_ext;
let format = self.surface_format.format;
let extent = {
let window_size = self.window.inner_size();
let capabilities = surface_ext.get_physical_device_surface_capabilities(
self.device.physical_device,
self.surface,
)?;
let min = capabilities.min_image_extent;
let max = capabilities.max_image_extent;
vk::Extent2D {
width: u32::clamp(window_size.width, min.width, max.width),
height: u32::clamp(window_size.height, min.height, max.height),
}
};
let old = self.active.take();
if let Some(old) = old.as_ref() {
old.destroy_image_views(device);
}
let swapchain = swapchain_ext
.create_swapchain(
&vk::SwapchainCreateInfoKHR::default()
.surface(self.surface)
.min_image_count(self.image_count)
.image_color_space(self.surface_format.color_space)
.image_format(format)
.image_extent(extent)
.image_usage(vk::ImageUsageFlags::COLOR_ATTACHMENT)
.image_sharing_mode(vk::SharingMode::EXCLUSIVE)
.pre_transform(self.pre_transform)
.composite_alpha(vk::CompositeAlphaFlagsKHR::OPAQUE)
.present_mode(self.present_mode)
.clipped(true)
.image_array_layers(1)
.old_swapchain(
old.as_ref()
.map_or(vk::SwapchainKHR::null(), |old| old.swapchain),
),
None,
)
.context("create_swapchain")?;
if let Some(old) = old.as_ref() {
old.destroy_swapchain(device);
}
let images = device.swapchain_ext.get_swapchain_images(swapchain)?;
let images = images
.into_iter()
.map(|image| {
let image_view = device.create_image_view(
&vk::ImageViewCreateInfo::default()
.image(image)
.view_type(vk::ImageViewType::TYPE_2D)
.format(format)
.components(vk::ComponentMapping::default()) // identity
.subresource_range(vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
}),
None,
)?;
Ok::<_, anyhow::Error>((image, image_view))
})
.collect::<Result<Vec<_>, _>>()?;
self.active = Some(ActiveSwapchain {
swapchain,
images,
extent,
});
Ok(())
}
}
}
impl ActiveSwapchain {
/// We must destroy the image views we own, but not the images, those are owned by the swapchain.
unsafe fn destroy_image_views(&self, device: &MyDevice) {
unsafe {
for (_, image_view) in &self.images {
device.destroy_image_view(*image_view, None);
}
}
}
/// Destroying the swapchain destroys* the images, so image views must be destroyed beforehand.
unsafe fn destroy_swapchain(&self, device: &MyDevice) {
unsafe { device.swapchain_ext.destroy_swapchain(self.swapchain, None) }
}
}
impl Drop for MySwapchainManager {
fn drop(&mut self) {
unsafe {
self.device.device_wait_idle().ok();
self.sync.destroy(&self.device);
if let Some(active) = self.active.as_ref() {
active.destroy_image_views(&self.device);
active.destroy_swapchain(&self.device);
}
self.device.surface_ext.destroy_surface(self.surface, None);
}
}
}
/// Metadata on drawing a single frame on some image
pub struct DrawFrame {
/// the size of the image
pub extent: vk::Extent2D,
/// the [`vk::Image`] to draw to
pub image: vk::Image,
/// the [`vk::Image`] to draw to, created from `image`
pub image_view: vk::ImageView,
/// the `acquire_image` semaphore that must be waited for before draw commands are executed
pub acquire_semaphore: vk::Semaphore,
/// the `draw_finished` semaphore that must be signaled when drawing to the image has finished
pub draw_finished_semaphore: vk::Semaphore,
/// the `draw_finished` fence that must be signaled when drawing to the image has finished
pub draw_finished_fence: vk::Fence,
}
impl MySwapchainManager {
pub fn render(
&mut self,
f: impl FnOnce(DrawFrame) -> anyhow::Result<()>,
) -> anyhow::Result<()> {
unsafe {
self.device
.wait_for_fences(&[self.sync.render_fence], true, !0)?;
self.device.reset_fences(&[self.sync.render_fence])?;
const RECREATE_ATTEMPTS: u32 = 10;
for _ in 0..RECREATE_ATTEMPTS {
if self.should_recreate {
self.should_recreate = false;
// *In theory*, recreating the swapchain allows you to present any acquired images from the old
// swapchain. Which (iirc) requires you to wait for all images to be presented before destroying
// the old swapchain. But we just use the [`ash::Device::device_wait_idle`] "hack" to wait for all
// previous images to finish before immediately destroying the swapchain.
self.device.device_wait_idle()?;
self.recreate_swapchain()?;
}
let active = self.active.as_ref().unwrap();
let swapchain_ext = &self.device.swapchain_ext;
match swapchain_ext.acquire_next_image(
active.swapchain,
!0,
self.sync.acquire_semaphore,
vk::Fence::null(),
) {
Ok((id, suboptimal)) => {
if suboptimal {
self.should_recreate = true;
}
let (image, image_view) = active.images[id as usize];
f(DrawFrame {
extent: active.extent,
image,
image_view,
acquire_semaphore: self.sync.acquire_semaphore,
draw_finished_semaphore: self.sync.render_semaphore,
draw_finished_fence: self.sync.render_fence,
})?;
let suboptimal = swapchain_ext.queue_present(
self.device.main_queue,
&vk::PresentInfoKHR::default()
.swapchains(&[active.swapchain])
.image_indices(&[id])
.wait_semaphores(&[self.sync.render_semaphore]),
)?;
if suboptimal {
self.should_recreate = true;
}
return Ok(());
}
Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => {
// retry
self.should_recreate = true;
}
Err(e) => {
return Err(e.into());
}
}
}
panic!(
"looped {RECREATE_ATTEMPTS} times trying to acquire swapchain image and failed repeatedly!"
);
}
}
}