Files
a0_basic_app
a1_vehicle
a2_async_sim
ab_glyph
ab_glyph_rasterizer
adler
adler32
agents
aho_corasick
anyhow
approx
aquamarine
ash
atty
bitflags
bytemuck
byteorder
cache_padded
cfg_if
chrono
color_quant
crc32fast
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
deflate
draw2d
either
flexi_logger
generic_array
gif
glfw
glfw_sys
glob
image
indoc
itertools
jpeg_decoder
lazy_static
libc
libloading
log
matrixmultiply
memchr
memoffset
miniz_oxide
nalgebra
base
geometry
linalg
third_party
num_complex
num_cpus
num_integer
num_iter
num_rational
num_traits
owned_ttf_parser
paste
png
proc_macro2
proc_macro_error
proc_macro_error_attr
quote
raw_window_handle
rawpointer
rayon
rayon_core
regex
regex_syntax
scoped_threadpool
scopeguard
semver
semver_parser
serde
serde_derive
simba
smawk
spin_sleep
syn
terminal_size
textwrap
thiserror
thiserror_impl
tiff
time
triple_buffer
ttf_parser
typenum
unicode_width
unicode_xid
unindent
vk_sys
weezl
yansi
  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
mod descriptor;
mod sync;

use self::{descriptor::FrameDescriptor, sync::FrameSync};

use crate::graphics::vulkan::{
    buffer::CpuBuffer, command_pool::ReusableCommandPool, Device,
};

use anyhow::{Context, Result};
use ash::{version::DeviceV1_0, vk};
use std::sync::Arc;

/// All per-frame resources and synchronization for this application.
pub struct Frame {
    pub sync: FrameSync,
    pub descriptor: FrameDescriptor,
    pub vertex_buffer: CpuBuffer,
    pub command_pool: ReusableCommandPool,
    pub framebuffer: vk::Framebuffer,

    command_buffers: Vec<vk::CommandBuffer>,

    device: Arc<Device>,
}

impl Frame {
    /// Create a collection of frames with resource debug names based on the
    /// frame index.
    pub fn create_n_frames(
        device: &Arc<Device>,
        framebuffers: &[vk::Framebuffer],
    ) -> Result<Vec<Option<Self>>> {
        let mut result = vec![];
        for (i, framebuffer) in framebuffers.iter().enumerate() {
            result.push(Some(Self::new(
                device.clone(),
                *framebuffer,
                format!("Frame {}", i),
            )?));
        }
        Ok(result)
    }

    /// Create a new frame.
    ///
    /// Frames do not own framebuffers, it is the responsibility of the
    /// application to ensure no Frame instances are used after the swapchain
    /// has been dropped.
    pub fn new<Name>(
        device: Arc<Device>,
        framebuffer: vk::Framebuffer,
        name: Name,
    ) -> Result<Self>
    where
        Name: Into<String> + Clone,
    {
        Ok(Self {
            sync: FrameSync::new(&device, name.clone())?,
            descriptor: FrameDescriptor::new(device.clone(), name.clone())?,
            vertex_buffer: CpuBuffer::new(
                device.clone(),
                vk::BufferUsageFlags::VERTEX_BUFFER,
            )?,
            command_pool: ReusableCommandPool::new(
                device.clone(),
                name.clone(),
            )?,
            framebuffer,
            command_buffers: vec![],
            device,
        })
    }

    /// Begin the frame's rendering operations.
    ///
    /// Blocks until the previous render with this frame has finished.
    /// Resets the command pool used by this frame.
    pub fn begin_frame(&mut self) -> Result<()> {
        unsafe {
            self.wait_for_graphics_to_complete()?;
            self.command_pool.reset()?;
        }
        self.command_buffers.clear();
        Ok(())
    }

    /// Submit command buffers to be added to the graphics queue when the frame
    /// is finished by the frame context.
    pub fn submit_graphics_commands(
        &mut self,
        command_buffers: &[vk::CommandBuffer],
    ) {
        self.command_buffers.extend_from_slice(command_buffers);
    }

    /// Finish the frame by submitting all command buffers to the graphics
    /// queue and a semaphore which signals when rendering to the framebuffer
    /// is complete.
    pub fn finish_frame(
        &mut self,
        image_available: vk::Semaphore,
    ) -> Result<vk::Semaphore> {
        let wait_semaphores = [image_available];
        let wait_stages = [vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT];
        let render_finished_signal_semaphores =
            [self.sync.render_finished_semaphore];
        let submit_info = [vk::SubmitInfo {
            p_wait_semaphores: wait_semaphores.as_ptr(),
            p_wait_dst_stage_mask: wait_stages.as_ptr(),
            wait_semaphore_count: wait_semaphores.len() as u32,
            p_command_buffers: self.command_buffers.as_ptr(),
            command_buffer_count: self.command_buffers.len() as u32,
            p_signal_semaphores: render_finished_signal_semaphores.as_ptr(),
            signal_semaphore_count: render_finished_signal_semaphores.len()
                as u32,
            ..Default::default()
        }];
        unsafe {
            self.device
                .logical_device
                .queue_submit(
                    self.device.graphics_queue.raw(),
                    &submit_info,
                    self.sync.graphics_finished_fence,
                )
                .with_context(|| "unable to submit graphics commands!")?;
        }
        Ok(self.sync.render_finished_semaphore)
    }

    /// Called at the beginning of each frame.
    ///
    /// Block until this frame's prior graphics submission has completed, then
    /// reset the fences. Unsafe because this function must be considered in
    /// the context of a full frame and how rendering commansd are submitted.
    unsafe fn wait_for_graphics_to_complete(&mut self) -> Result<()> {
        self.device
            .logical_device
            .wait_for_fences(
                &[self.sync.graphics_finished_fence],
                true,
                u64::MAX,
            )
            .with_context(|| {
                "error while waiting for the graphics fence to complete!"
            })?;
        self.device
            .logical_device
            .reset_fences(&[self.sync.graphics_finished_fence])
            .with_context(|| "unable to reset the graphics fence!")?;
        Ok(())
    }
}

impl Drop for Frame {
    fn drop(&mut self) {
        unsafe {
            self.wait_for_graphics_to_complete()
                .expect("error while waiting for resources to clear");
            self.sync.destroy(&self.device);
        }
    }
}