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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Native window presentation types.
use {
super::{
DriverError, Surface,
device::Device,
image::{Image, ImageInfo},
},
ash::vk,
derive_builder::{Builder, UninitializedFieldError},
log::{debug, info, trace, warn},
std::{mem::replace, ops::Deref, slice, sync::Arc, thread::panicking},
};
// TODO: This needs to track completed command buffers and not constantly create semaphores
/// Provides the ability to present rendering results to a [`Surface`].
#[derive(Debug)]
pub struct Swapchain {
device: Arc<Device>,
images: Box<[SwapchainImage]>,
info: SwapchainInfo,
old_swapchain: vk::SwapchainKHR,
suboptimal: bool,
surface: Surface,
swapchain: vk::SwapchainKHR,
}
impl Swapchain {
/// Prepares a [`vk::SwapchainKHR`] object which is lazily created after calling
/// [`acquire_next_image`][Self::acquire_next_image].
#[profiling::function]
pub fn new(
device: &Arc<Device>,
surface: Surface,
info: impl Into<SwapchainInfo>,
) -> Result<Self, DriverError> {
let device = Arc::clone(device);
let info = info.into();
Ok(Swapchain {
device,
images: Default::default(),
info,
old_swapchain: vk::SwapchainKHR::null(),
suboptimal: true,
surface,
swapchain: vk::SwapchainKHR::null(),
})
}
/// Gets the next available swapchain image which should be rendered to and then presented using
/// [`present_image`][Self::present_image].
#[profiling::function]
pub fn acquire_next_image(
&mut self,
acquired: vk::Semaphore,
) -> Result<SwapchainImage, SwapchainError> {
for _ in 0..2 {
if self.suboptimal {
self.recreate_swapchain().map_err(|err| {
if matches!(err, DriverError::Unsupported) {
SwapchainError::Suboptimal
} else {
SwapchainError::SurfaceLost
}
})?;
}
let swapchain_ext = Device::expect_swapchain_ext(&self.device);
let image_idx = unsafe {
swapchain_ext.acquire_next_image(
self.swapchain,
u64::MAX,
acquired,
vk::Fence::null(),
)
}
.map(|(idx, suboptimal)| {
if suboptimal {
debug!("acquired image is suboptimal");
}
self.suboptimal = suboptimal;
idx
});
match image_idx {
Ok(image_idx) => {
let image_idx = image_idx as usize;
assert!(image_idx < self.images.len());
let image = unsafe { self.images.get_unchecked(image_idx) };
let image = SwapchainImage::clone_swapchain(image);
return Ok(replace(
unsafe { self.images.get_unchecked_mut(image_idx) },
image,
));
}
Err(err)
if err == vk::Result::ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT
|| err == vk::Result::ERROR_OUT_OF_DATE_KHR
|| err == vk::Result::NOT_READY
|| err == vk::Result::TIMEOUT =>
{
warn!("unable to acquire image: {err}");
self.suboptimal = true;
// Try again to see if we can acquire an image this frame
// (Makes redraw during resize look slightly better)
continue;
}
Err(err) if err == vk::Result::ERROR_DEVICE_LOST => {
warn!("unable to acquire image: {err}");
self.suboptimal = true;
return Err(SwapchainError::DeviceLost);
}
Err(err) if err == vk::Result::ERROR_SURFACE_LOST_KHR => {
warn!("unable to acquire image: {err}");
self.suboptimal = true;
return Err(SwapchainError::SurfaceLost);
}
Err(err) => {
// Probably:
// VK_ERROR_OUT_OF_HOST_MEMORY
// VK_ERROR_OUT_OF_DEVICE_MEMORY
// TODO: Maybe handle timeout in here
warn!("unable to acquire image: {err}");
return Err(SwapchainError::SurfaceLost);
}
}
}
Err(SwapchainError::Suboptimal)
}
fn clamp_desired_image_count(
desired_image_count: u32,
surface_capabilities: vk::SurfaceCapabilitiesKHR,
) -> u32 {
let mut desired_image_count = desired_image_count.max(surface_capabilities.min_image_count);
if surface_capabilities.max_image_count != 0 {
desired_image_count = desired_image_count.min(surface_capabilities.max_image_count);
}
desired_image_count.min(u8::MAX as u32)
}
#[profiling::function]
fn destroy_swapchain(device: &Device, swapchain: &mut vk::SwapchainKHR) {
if *swapchain != vk::SwapchainKHR::null() {
// wait for device to be finished with swapchain before destroying it.
// This avoid crashes when resizing windows
#[cfg(target_os = "macos")]
if let Err(err) = unsafe { device.device_wait_idle() } {
warn!("device_wait_idle() failed: {err}");
}
let swapchain_ext = Device::expect_swapchain_ext(device);
unsafe {
swapchain_ext.destroy_swapchain(*swapchain, None);
}
*swapchain = vk::SwapchainKHR::null();
}
}
/// Gets information about this swapchain.
pub fn info(&self) -> SwapchainInfo {
self.info.clone()
}
/// Presents an image which has been previously acquired using
/// [`acquire_next_image`][Self::acquire_next_image].
#[profiling::function]
pub fn present_image(
&mut self,
image: SwapchainImage,
wait_semaphores: &[vk::Semaphore],
queue_family_index: u32,
queue_index: u32,
) {
let queue_family_index = queue_family_index as usize;
let queue_index = queue_index as usize;
debug_assert!(
queue_family_index < self.device.physical_device.queue_families.len(),
"Queue family index must be within the range of the available queues created by the device."
);
debug_assert!(
queue_index
< self.device.physical_device.queue_families[queue_family_index].queue_count
as usize,
"Queue index must be within the range of the available queues created by the device."
);
let present_info = vk::PresentInfoKHR::default()
.wait_semaphores(wait_semaphores)
.swapchains(slice::from_ref(&self.swapchain))
.image_indices(slice::from_ref(&image.image_idx));
let swapchain_ext = Device::expect_swapchain_ext(&self.device);
unsafe {
match swapchain_ext.queue_present(
self.device.queues[queue_family_index][queue_index],
&present_info,
) {
Ok(_) => {
Self::destroy_swapchain(&self.device, &mut self.old_swapchain);
}
Err(err)
if err == vk::Result::ERROR_DEVICE_LOST
|| err == vk::Result::ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT
|| err == vk::Result::ERROR_OUT_OF_DATE_KHR
|| err == vk::Result::ERROR_SURFACE_LOST_KHR
|| err == vk::Result::SUBOPTIMAL_KHR =>
{
// Handled in the next frame
self.suboptimal = true;
}
Err(err) => {
// Probably:
// VK_ERROR_OUT_OF_HOST_MEMORY
// VK_ERROR_OUT_OF_DEVICE_MEMORY
warn!("{err}");
}
}
}
let image_idx = image.image_idx as usize;
self.images[image_idx] = image;
}
#[profiling::function]
fn recreate_swapchain(&mut self) -> Result<(), DriverError> {
Self::destroy_swapchain(&self.device, &mut self.old_swapchain);
let surface_caps = Surface::capabilities(&self.surface)?;
let present_modes = Surface::present_modes(&self.surface)?;
let desired_image_count =
Self::clamp_desired_image_count(self.info.desired_image_count, surface_caps);
let image_usage = self.supported_surface_usage(surface_caps.supported_usage_flags)?;
let (surface_width, surface_height) = match surface_caps.current_extent.width {
std::u32::MAX => (
// TODO: Maybe handle this case with aspect-correct clamping?
self.info.width.clamp(
surface_caps.min_image_extent.width,
surface_caps.max_image_extent.width,
),
self.info.height.clamp(
surface_caps.min_image_extent.height,
surface_caps.max_image_extent.height,
),
),
_ => (
surface_caps.current_extent.width,
surface_caps.current_extent.height,
),
};
if surface_width * surface_height == 0 {
return Err(DriverError::Unsupported);
}
let present_mode = self
.info
.present_modes
.iter()
.copied()
.find(|mode| present_modes.contains(mode))
.unwrap_or(vk::PresentModeKHR::FIFO);
let pre_transform = if surface_caps
.supported_transforms
.contains(vk::SurfaceTransformFlagsKHR::IDENTITY)
{
vk::SurfaceTransformFlagsKHR::IDENTITY
} else {
surface_caps.current_transform
};
let swapchain_ext = Device::expect_swapchain_ext(&self.device);
let swapchain_create_info = vk::SwapchainCreateInfoKHR::default()
.surface(*self.surface)
.min_image_count(desired_image_count)
.image_color_space(self.info.surface.color_space)
.image_format(self.info.surface.format)
.image_extent(vk::Extent2D {
width: surface_width,
height: surface_height,
})
.image_usage(image_usage)
.image_sharing_mode(vk::SharingMode::EXCLUSIVE)
.pre_transform(pre_transform)
.composite_alpha(vk::CompositeAlphaFlagsKHR::OPAQUE)
.present_mode(present_mode)
.clipped(true)
.old_swapchain(self.swapchain)
.image_array_layers(1);
let swapchain = unsafe { swapchain_ext.create_swapchain(&swapchain_create_info, None) }
.map_err(|err| {
warn!("{err}");
DriverError::Unsupported
})?;
let images =
unsafe { swapchain_ext.get_swapchain_images(swapchain) }.map_err(|err| match err {
vk::Result::INCOMPLETE => DriverError::InvalidData,
vk::Result::ERROR_OUT_OF_DEVICE_MEMORY | vk::Result::ERROR_OUT_OF_HOST_MEMORY => {
DriverError::OutOfMemory
}
_ => DriverError::Unsupported,
})?;
let images = images
.into_iter()
.enumerate()
.map(|(image_idx, image)| {
let mut image = Image::from_raw(
&self.device,
image,
ImageInfo::image_2d(
surface_width,
surface_height,
self.info.surface.format,
image_usage,
),
);
let image_idx = image_idx as u32;
image.name = Some(format!("swapchain{image_idx}"));
Ok(SwapchainImage {
exec_idx: 0,
image,
image_idx,
})
})
.collect::<Result<Box<_>, _>>()?;
self.info.height = surface_height;
self.info.width = surface_width;
self.images = images;
self.old_swapchain = self.swapchain;
self.swapchain = swapchain;
self.suboptimal = false;
info!(
"swapchain {}x{} {present_mode:?}x{} {:?} {image_usage:#?}",
self.info.width,
self.info.height,
self.images.len(),
self.info.surface.format,
);
Ok(())
}
/// Sets information about this swapchain.
///
/// Previously acquired swapchain images should be discarded after calling this function.
pub fn set_info(&mut self, info: impl Into<SwapchainInfo>) {
let info: SwapchainInfo = info.into();
if self.info != info {
// attempt to reducing flickering when resizing windows on mac
#[cfg(target_os = "macos")]
if let Err(err) = unsafe { self.device.device_wait_idle() } {
warn!("device_wait_idle() failed: {err}");
}
self.info = info;
trace!("info: {:?}", self.info);
self.suboptimal = true;
}
}
fn supported_surface_usage(
&mut self,
surface_capabilities: vk::ImageUsageFlags,
) -> Result<vk::ImageUsageFlags, DriverError> {
let mut res = vk::ImageUsageFlags::empty();
for bit in 0..u32::BITS {
let usage = vk::ImageUsageFlags::from_raw((1 << bit) & surface_capabilities.as_raw());
if usage.is_empty() {
continue;
}
if Device::image_format_properties(
&self.device,
self.info.surface.format,
vk::ImageType::TYPE_2D,
vk::ImageTiling::OPTIMAL,
usage,
vk::ImageCreateFlags::empty(),
)
.inspect_err(|err| {
warn!(
"unable to get image format properties: {:?} {:?} {err}",
self.info.surface.format, usage
)
})?
.is_none()
{
continue;
}
res |= usage;
}
// On mesa the device will return this usage flag as supported even when the extension
// that is needed for an image to have this flag isn't enabled
res &= !vk::ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT;
Ok(res)
}
}
impl Drop for Swapchain {
#[profiling::function]
fn drop(&mut self) {
if panicking() {
return;
}
Self::destroy_swapchain(&self.device, &mut self.old_swapchain);
Self::destroy_swapchain(&self.device, &mut self.swapchain);
}
}
/// Describes the condition of a swapchain.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SwapchainError {
/// This frame is lost but more may be acquired later.
DeviceLost,
/// This frame is not lost but there may be a delay while the next frame is recreated.
Suboptimal,
/// The surface was lost and must be recreated, which includes any operating system window.
SurfaceLost,
}
/// An opaque type representing a swapchain image.
#[derive(Debug)]
pub struct SwapchainImage {
pub(crate) exec_idx: usize,
image: Image,
image_idx: u32,
}
impl SwapchainImage {
pub(crate) fn clone_swapchain(this: &Self) -> Self {
let Self {
exec_idx,
image,
image_idx,
} = this;
Self {
exec_idx: *exec_idx,
image: Image::clone_swapchain(image),
image_idx: *image_idx,
}
}
}
impl Deref for SwapchainImage {
type Target = Image;
fn deref(&self) -> &Self::Target {
&self.image
}
}
/// Information used to create a [`Swapchain`] instance.
#[derive(Builder, Clone, Debug, Eq, Hash, PartialEq)]
#[builder(
build_fn(private, name = "fallible_build", error = "SwapchainInfoBuilderError"),
derive(Clone, Debug),
pattern = "owned"
)]
#[non_exhaustive]
pub struct SwapchainInfo {
/// The desired, but not guaranteed, number of images that will be in the created swapchain.
///
/// More images introduces more display lag, but smoother animation.
#[builder(default = "3")]
pub desired_image_count: u32,
/// The initial height of the surface.
pub height: u32,
/// The format and color space of the surface.
pub surface: vk::SurfaceFormatKHR,
/// `vk::PresentModeKHR` Determines timing and queueing with which frames are actually displayed to the user.
/// `present_modes` is a set of these modes ordered by preference. If the first mode is not available it will fall
/// back to the next, etc...
///
/// `vk::PresentModeKHR::FIFO` - Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
/// long. Every vertical blanking period, the presentation engine will pop a frame off the queue to display. If
/// there is no frame to display, it will present the same frame again until the next vblank.
///
/// When a present command is executed on the GPU, the presented image is added on the queue.
///
/// * **Tearing:** No tearing will be observed.
/// * **Also known as**: "Vsync On"
///
/// `vk::PresentModeKHR::FIFO_RELAXED` - Presentation frames are kept in a First-In-First-Out queue approximately 3
/// frames long. Every vertical blanking period, the presentation engine will pop a frame off the queue to display.
/// If there is no frame to display, it will present the same frame until there is a frame in the queue. The moment
/// there is a frame in the queue, it will immediately pop the frame off the queue.
///
/// When a present command is executed on the GPU, the presented image is added on the queue.
///
/// * **Tearing**:
/// Tearing will be observed if frames last more than one vblank as the front buffer.
/// * **Also known as**: "Adaptive Vsync"
///
/// `vk::PresentModeKHR::IMMEDIATE` - Presentation frames are not queued at all. The moment a present command is
/// executed on the GPU, the presented image is swapped onto the front buffer immediately.
///
/// * **Tearing**: Tearing can be observed.
/// * **Also known as**: "Vsync Off"
///
/// `vk::PresentModeKHR::MAILBOX` - Presentation frames are kept in a single-frame queue. Every vertical blanking
/// period, the presentation engine will pop a frame from the queue. If there is no frame to display, it will
/// present the same frame again until the next vblank.
///
/// When a present command is executed on the GPU, the frame will be put into the queue.
/// If there was already a frame in the queue, the new frame will _replace_ the old frame
/// on the queue.
///
/// * **Tearing**: No tearing will be observed.
/// * **Also known as**: "Fast Vsync"
#[builder(default = vec![vk::PresentModeKHR::FIFO_RELAXED, vk::PresentModeKHR::FIFO])]
pub present_modes: Vec<vk::PresentModeKHR>,
/// The initial width of the surface.
pub width: u32,
}
impl SwapchainInfo {
/// Specifies a default swapchain with the given `width`, `height` and `format` values.
#[inline(always)]
pub fn new(width: u32, height: u32, surface: vk::SurfaceFormatKHR) -> SwapchainInfo {
Self {
width,
height,
surface,
desired_image_count: 3,
present_modes: vec![vk::PresentModeKHR::FIFO_RELAXED, vk::PresentModeKHR::FIFO],
}
}
/// Converts a `SwapchainInfo` into a `SwapchainInfoBuilder`.
#[inline(always)]
pub fn to_builder(self) -> SwapchainInfoBuilder {
SwapchainInfoBuilder {
desired_image_count: Some(self.desired_image_count),
height: Some(self.height),
surface: Some(self.surface),
present_modes: Some(self.present_modes),
width: Some(self.width),
}
}
}
impl From<SwapchainInfoBuilder> for SwapchainInfo {
fn from(info: SwapchainInfoBuilder) -> Self {
info.build()
}
}
impl SwapchainInfoBuilder {
/// Builds a new `SwapchainInfo`.
///
/// # Panics
///
/// If any of the following values have not been set this function will panic:
///
/// * `width`
/// * `height`
/// * `surface`
#[inline(always)]
pub fn build(self) -> SwapchainInfo {
match self.fallible_build() {
Err(SwapchainInfoBuilderError(err)) => panic!("{err}"),
Ok(info) => info,
}
}
}
#[derive(Debug)]
struct SwapchainInfoBuilderError(UninitializedFieldError);
impl From<UninitializedFieldError> for SwapchainInfoBuilderError {
fn from(err: UninitializedFieldError) -> Self {
Self(err)
}
}
#[cfg(test)]
mod tests {
use super::*;
type Info = SwapchainInfo;
type Builder = SwapchainInfoBuilder;
#[test]
pub fn swapchain_info() {
let info = Info::new(20, 24, vk::SurfaceFormatKHR::default());
let builder = info.clone().to_builder().build();
assert_eq!(info, builder);
}
#[test]
pub fn swapchain_info_builder() {
let info = Info::new(23, 64, vk::SurfaceFormatKHR::default());
let builder = Builder::default()
.width(23)
.height(64)
.surface(vk::SurfaceFormatKHR::default())
.build();
assert_eq!(info, builder);
}
#[test]
#[should_panic(expected = "Field not initialized: height")]
pub fn swapchain_info_builder_uninit_height() {
Builder::default().build();
}
#[test]
#[should_panic(expected = "Field not initialized: surface")]
pub fn swapchain_info_builder_uninit_surface() {
Builder::default().height(42).build();
}
#[test]
#[should_panic(expected = "Field not initialized: width")]
pub fn swapchain_info_builder_uninit_width() {
Builder::default()
.height(42)
.surface(vk::SurfaceFormatKHR::default())
.build();
}
}