-
Notifications
You must be signed in to change notification settings - Fork 230
Introduce ash-swapchain helper crate #506
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Ralith
wants to merge
2
commits into
ash-rs:master
Choose a base branch
from
Ralith:swapchain
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,5 +3,6 @@ members = [ | |
| "examples", | ||
| "ash", | ||
| "ash-window", | ||
| "ash-swapchain", | ||
| "generator", | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| [package] | ||
| name = "ash-swapchain" | ||
| version = "0.1.0" | ||
| edition = "2021" | ||
|
|
||
| [dependencies] | ||
| ash = { path = "../ash", version = "0.34" } | ||
|
|
||
| [dev-dependencies] | ||
| winit = "0.26" | ||
| ash-window = { path = "../ash-window", version = "0.8" } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| ash-swapchain | ||
| = | ||
|
|
||
| Synchronization for swapchain resize and presentation | ||
| - | ||
|
|
||
| [](https://crates.io/crates/ash-swapchain) | ||
| [](https://docs.rs/ash-swapchain) | ||
| [](https://github.com/MaikKlein/ash/actions?workflow=CI) | ||
| [](LICENSE-MIT) | ||
| [](LICENSE-APACHE) | ||
|
|
||
| ## Usage | ||
|
|
||
| A `Swapchain` manages (re)creating a `vk::SwapchainKHR` associated with a particular | ||
| `vk::SurfaceKHR`, and tracks the availability of resources associated with a particular *frame in | ||
| flight*. `Swapchain::acquire` yields an `AcquiredFrame` which specifies which swapchain image to | ||
| render to, which frame's resources are available for reuse, how to synchronize submitted work with | ||
| frame and swapchain image availability, and whether previously exposed swapchain images have been | ||
| invalidated. | ||
|
|
||
| ## License | ||
|
|
||
| Licensed under either of | ||
|
|
||
| * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) | ||
| * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) | ||
|
|
||
| at your option. | ||
|
|
||
| ## Contribution | ||
|
|
||
| Unless you explicitly state otherwise, any Contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,343 @@ | ||
| use std::time::Instant; | ||
|
|
||
| use ash::{extensions::khr, vk}; | ||
| use ash_swapchain::Swapchain; | ||
| use winit::{ | ||
| event::{Event, WindowEvent}, | ||
| event_loop::{ControlFlow, EventLoop}, | ||
| window::{Window, WindowBuilder}, | ||
| }; | ||
|
|
||
| fn main() { | ||
| let event_loop = EventLoop::new(); | ||
| let window = WindowBuilder::new().build(&event_loop).unwrap(); | ||
|
|
||
| let mut app = App::new(&window); | ||
|
|
||
| event_loop.run(move |event, _, control_flow| { | ||
| *control_flow = ControlFlow::Poll; | ||
| match event { | ||
| Event::WindowEvent { | ||
| event: WindowEvent::CloseRequested, | ||
| .. | ||
| } => *control_flow = ControlFlow::Exit, | ||
| Event::WindowEvent { | ||
| event: WindowEvent::Resized(size), | ||
| .. | ||
| } => { | ||
| app.resize(vk::Extent2D { | ||
| width: size.width, | ||
| height: size.height, | ||
| }); | ||
| } | ||
| Event::MainEventsCleared => { | ||
| app.draw(); | ||
| } | ||
| _ => (), | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| pub struct App { | ||
| _entry: ash::Entry, | ||
| instance: ash::Instance, | ||
| surface: vk::SurfaceKHR, | ||
| epoch: Instant, | ||
|
|
||
| functions: Functions, | ||
| swapchain: Swapchain, | ||
| queue: vk::Queue, | ||
|
|
||
| command_pool: vk::CommandPool, | ||
| frames: Vec<Frame>, | ||
| } | ||
|
|
||
| impl App { | ||
| pub fn new(window: &Window) -> Self { | ||
| unsafe { | ||
| let entry = ash::Entry::new(); | ||
| let exts = ash_window::enumerate_required_extensions(&window).unwrap(); | ||
| let ext_ptrs = exts | ||
| .iter() | ||
| .map(|x| x.as_ptr() as *const _) | ||
| .collect::<Vec<_>>(); | ||
| let instance = entry | ||
| .create_instance( | ||
| &vk::InstanceCreateInfo::builder() | ||
| .application_info(&vk::ApplicationInfo { | ||
| api_version: vk::make_api_version(0, 1, 0, 0), | ||
| ..Default::default() | ||
| }) | ||
| .enabled_extension_names(&ext_ptrs), | ||
| None, | ||
| ) | ||
| .unwrap(); | ||
| let surface_fn = khr::Surface::new(&entry, &instance); | ||
| let surface = ash_window::create_surface(&entry, &instance, &window, None).unwrap(); | ||
|
|
||
| let (physical_device, queue_family_index) = instance | ||
| .enumerate_physical_devices() | ||
| .unwrap() | ||
| .into_iter() | ||
| .find_map(|dev| { | ||
| let (family, _) = instance | ||
| .get_physical_device_queue_family_properties(dev) | ||
| .into_iter() | ||
| .enumerate() | ||
| .find(|(_index, info)| { | ||
| info.queue_flags.contains(vk::QueueFlags::GRAPHICS) | ||
| })?; | ||
| let family = family as u32; | ||
| let supported = surface_fn | ||
| .get_physical_device_surface_support(dev, family, surface) | ||
| .unwrap(); | ||
| if !supported { | ||
| return None; | ||
| } | ||
| Some((dev, family)) | ||
| }) | ||
| .unwrap(); | ||
|
|
||
| let device = instance | ||
| .create_device( | ||
| physical_device, | ||
| &vk::DeviceCreateInfo::builder() | ||
| .enabled_extension_names(&[khr::Swapchain::name().as_ptr() as _]) | ||
| .queue_create_infos(&[vk::DeviceQueueCreateInfo::builder() | ||
| .queue_family_index(queue_family_index) | ||
| .queue_priorities(&[1.0]) | ||
| .build()]), | ||
| None, | ||
| ) | ||
| .unwrap(); | ||
| let swapchain_fn = khr::Swapchain::new(&instance, &device); | ||
| let queue = device.get_device_queue(queue_family_index, queue_family_index); | ||
|
|
||
| let size = window.inner_size(); | ||
| let mut options = ash_swapchain::Options::default(); | ||
| options.usage(vk::ImageUsageFlags::TRANSFER_DST); // Typically this would be left as the default, COLOR_ATTACHMENT | ||
| let swapchain = Swapchain::new( | ||
| &ash_swapchain::Functions { | ||
| device: &device, | ||
| swapchain: &swapchain_fn, | ||
| surface: &surface_fn, | ||
| }, | ||
| options, | ||
| surface, | ||
| physical_device, | ||
| vk::Extent2D { | ||
| width: size.width, | ||
| height: size.height, | ||
| }, | ||
| ); | ||
|
|
||
| let command_pool = device | ||
| .create_command_pool( | ||
| &vk::CommandPoolCreateInfo::builder() | ||
| .flags( | ||
| vk::CommandPoolCreateFlags::TRANSIENT | ||
| | vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER, | ||
| ) | ||
| .queue_family_index(queue_family_index), | ||
| None, | ||
| ) | ||
| .unwrap(); | ||
| let cmds = device | ||
| .allocate_command_buffers( | ||
| &vk::CommandBufferAllocateInfo::builder() | ||
| .command_pool(command_pool) | ||
| .level(vk::CommandBufferLevel::PRIMARY) | ||
| .command_buffer_count(swapchain.frames_in_flight() as u32), | ||
| ) | ||
| .unwrap(); | ||
| let frames = cmds | ||
| .into_iter() | ||
| .map(|cmd| Frame { | ||
| cmd, | ||
| complete: device | ||
| .create_semaphore(&vk::SemaphoreCreateInfo::default(), None) | ||
| .unwrap(), | ||
| }) | ||
| .collect(); | ||
|
|
||
| Self { | ||
| _entry: entry, | ||
| instance, | ||
| surface, | ||
| epoch: Instant::now(), | ||
|
|
||
| functions: Functions { | ||
| device, | ||
| swapchain: swapchain_fn, | ||
| surface: surface_fn, | ||
| }, | ||
| swapchain, | ||
| queue, | ||
|
|
||
| command_pool, | ||
| frames, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn resize(&mut self, size: vk::Extent2D) { | ||
| self.swapchain.update(size); | ||
| } | ||
|
|
||
| fn draw(&mut self) { | ||
| let device = &self.functions.device; | ||
| unsafe { | ||
| let acq = self | ||
| .swapchain | ||
| .acquire(&self.functions.ash_swapchain(), !0) | ||
| .unwrap(); | ||
| let cmd = self.frames[acq.frame_index].cmd; | ||
| let swapchain_image = self.swapchain.images()[acq.image_index]; | ||
| device | ||
| .begin_command_buffer( | ||
| cmd, | ||
| &vk::CommandBufferBeginInfo::builder() | ||
| .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT), | ||
| ) | ||
| .unwrap(); | ||
|
|
||
| // | ||
| // Record commands to render to swapchain_image | ||
| // | ||
|
|
||
| // Typically this barrier would be implemented with a subpass dependency from EXTERNAL, | ||
| // with both pipeline stages set to COLOR_ATTACHMENT_OUTPUT so that it doesn't block | ||
| // work that doesn't write to the swapchain image. The source stage must overlap with | ||
| // the wait_dst_stage_mask passed to `queue_submit` below to ensure that the image | ||
| // transition doesn't happen until after the acquire semaphore is signaled. | ||
| device.cmd_pipeline_barrier( | ||
| cmd, | ||
| vk::PipelineStageFlags::TRANSFER, | ||
| vk::PipelineStageFlags::TRANSFER, | ||
| vk::DependencyFlags::default(), | ||
| &[], | ||
| &[], | ||
| &[vk::ImageMemoryBarrier::builder() | ||
| .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE) | ||
| .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) | ||
| .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) | ||
| .old_layout(vk::ImageLayout::UNDEFINED) | ||
| .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL) | ||
| .image(swapchain_image) | ||
| .subresource_range(vk::ImageSubresourceRange { | ||
| aspect_mask: vk::ImageAspectFlags::COLOR, | ||
| base_mip_level: 0, | ||
| level_count: 1, | ||
| base_array_layer: 0, | ||
| layer_count: 1, | ||
| }) | ||
| .build()], | ||
| ); | ||
| let t = (self.epoch.elapsed().as_secs_f32().sin() + 1.0) * 0.5; | ||
| device.cmd_clear_color_image( | ||
| cmd, | ||
| swapchain_image, | ||
| vk::ImageLayout::TRANSFER_DST_OPTIMAL, | ||
| &vk::ClearColorValue { | ||
| float32: [0.0, t, 0.0, 1.0], | ||
| }, | ||
| &[vk::ImageSubresourceRange { | ||
| aspect_mask: vk::ImageAspectFlags::COLOR, | ||
| base_mip_level: 0, | ||
| level_count: 1, | ||
| base_array_layer: 0, | ||
| layer_count: 1, | ||
| }], | ||
| ); | ||
| // Typically this barrier would be implemented with the implicit subpass dependency to | ||
| // EXTERNAL | ||
| device.cmd_pipeline_barrier( | ||
| cmd, | ||
| vk::PipelineStageFlags::TRANSFER, | ||
| vk::PipelineStageFlags::BOTTOM_OF_PIPE, | ||
| vk::DependencyFlags::default(), | ||
| &[], | ||
| &[], | ||
| &[vk::ImageMemoryBarrier::builder() | ||
| .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) | ||
| .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) | ||
| .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) | ||
| .old_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL) | ||
| .new_layout(vk::ImageLayout::PRESENT_SRC_KHR) | ||
| .image(swapchain_image) | ||
| .subresource_range(vk::ImageSubresourceRange { | ||
| aspect_mask: vk::ImageAspectFlags::COLOR, | ||
| base_mip_level: 0, | ||
| level_count: 1, | ||
| base_array_layer: 0, | ||
| layer_count: 1, | ||
| }) | ||
| .build()], | ||
| ); | ||
|
|
||
| // | ||
| // Submit commands and queue present | ||
| // | ||
|
|
||
| device.end_command_buffer(cmd).unwrap(); | ||
| device | ||
| .queue_submit( | ||
| self.queue, | ||
| &[vk::SubmitInfo::builder() | ||
| .wait_semaphores(&[acq.ready]) | ||
| .wait_dst_stage_mask(&[vk::PipelineStageFlags::TRANSFER]) | ||
| .signal_semaphores(&[self.frames[acq.frame_index].complete]) | ||
| .command_buffers(&[cmd]) | ||
| .build()], | ||
| acq.complete, | ||
| ) | ||
| .unwrap(); | ||
| self.swapchain | ||
| .queue_present( | ||
| &self.functions.ash_swapchain(), | ||
| self.queue, | ||
| self.frames[acq.frame_index].complete, | ||
| acq.image_index, | ||
| ) | ||
| .unwrap(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Drop for App { | ||
| fn drop(&mut self) { | ||
| unsafe { | ||
| let device = &self.functions.device; | ||
| let _ = device.device_wait_idle(); | ||
| for frame in &self.frames { | ||
| device.destroy_semaphore(frame.complete, None); | ||
| } | ||
| device.destroy_command_pool(self.command_pool, None); | ||
| self.swapchain.destroy(&self.functions.ash_swapchain()); | ||
| self.functions.surface.destroy_surface(self.surface, None); | ||
| device.destroy_device(None); | ||
| self.instance.destroy_instance(None); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| struct Functions { | ||
| device: ash::Device, | ||
| surface: khr::Surface, | ||
| swapchain: khr::Swapchain, | ||
| } | ||
|
|
||
| impl Functions { | ||
| fn ash_swapchain(&self) -> ash_swapchain::Functions<'_> { | ||
| ash_swapchain::Functions { | ||
| device: &self.device, | ||
| swapchain: &self.swapchain, | ||
| surface: &self.surface, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| struct Frame { | ||
| cmd: vk::CommandBuffer, | ||
| complete: vk::Semaphore, | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When needing a slice of a single element that is created by a builder, I typically use
std::slice::as_ref()which allows the builder toDerefwithout calling.build().Edit: Same for a few other single-element slice constructs in this PR.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That seems like extraneous ceremony to me, since this
buildcall is lexically within the statement that consumes it and therefore sound regardless.