First try to convert to lifetimes

This commit is contained in:
hodasemi 2024-03-28 18:28:52 +01:00
parent 4d476c4263
commit 39c4fa2342
33 changed files with 489 additions and 826 deletions

View file

@ -37,9 +37,9 @@ pub struct AccelerationStructureBuilder {
} }
impl AccelerationStructureBuilder { impl AccelerationStructureBuilder {
pub fn add_instance( pub fn add_instance<'a>(
mut self, mut self,
blas: &Arc<AccelerationStructure>, blas: &AccelerationStructure<'a>,
transform: Option<Matrix4<f32>>, transform: Option<Matrix4<f32>>,
instance_flags: impl Into<VkGeometryInstanceFlagBitsKHR>, instance_flags: impl Into<VkGeometryInstanceFlagBitsKHR>,
) -> Self { ) -> Self {
@ -70,10 +70,10 @@ impl AccelerationStructureBuilder {
self self
} }
pub fn add_vertices<T: ReprC + Send + Sync + 'static>( pub fn add_vertices<'a, T: ReprC + Send + Sync + 'static>(
mut self, mut self,
vertex_buffer: &Arc<Buffer<T>>, vertex_buffer: &Arc<Buffer<'a, T>>,
transform: Option<Arc<Buffer<Transform>>>, transform: Option<Arc<Buffer<'a, Transform>>>,
flags: impl Into<VkGeometryFlagBitsKHR>, flags: impl Into<VkGeometryFlagBitsKHR>,
) -> Self { ) -> Self {
match &mut self.data { match &mut self.data {
@ -122,11 +122,11 @@ impl AccelerationStructureBuilder {
self self
} }
pub fn build( pub fn build<'a>(
self, self,
device: Arc<Device>, device: &Device,
recorder: &mut CommandBufferRecorder<'_>, recorder: &mut CommandBufferRecorder<'_>,
) -> Result<Arc<AccelerationStructure>> { ) -> Result<AccelerationStructure<'a>> {
let build_flags = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR let build_flags = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR
| VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR;
@ -140,7 +140,7 @@ impl AccelerationStructureBuilder {
| VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT,
) )
.set_memory_usage(MemoryUsage::CpuToGpu) .set_memory_usage(MemoryUsage::CpuToGpu)
.build(device.clone())?; .build(device)?;
let device_address: VkDeviceOrHostAddressConstKHR = let device_address: VkDeviceOrHostAddressConstKHR =
instances_buffer.device_address().into(); instances_buffer.device_address().into();
@ -239,8 +239,8 @@ impl AccelerationStructureBuilder {
} }
}; };
let acceleration_structure = Arc::new(AccelerationStructure { let acceleration_structure = AccelerationStructure {
device: device.clone(), device,
acceleration_structure, acceleration_structure,
@ -258,7 +258,7 @@ impl AccelerationStructureBuilder {
generation_data, generation_data,
build_flags, build_flags,
}); };
acceleration_structure.generate( acceleration_structure.generate(
recorder, recorder,
@ -270,21 +270,21 @@ impl AccelerationStructureBuilder {
} }
} }
pub struct AccelerationStructure { pub struct AccelerationStructure<'a> {
device: Arc<Device>, device: &'a Device,
acceleration_structure: VkAccelerationStructureKHR, acceleration_structure: VkAccelerationStructureKHR,
result_buffer: Arc<Buffer<RawBuffer>>, result_buffer: Buffer<'a, RawBuffer>,
scratch_buffer: Mutex<Arc<Buffer<RawBuffer>>>, scratch_buffer: Mutex<Buffer<'a, RawBuffer>>,
update_scratch_buffer_size: VkDeviceSize, update_scratch_buffer_size: VkDeviceSize,
generation_data: AccelerationStructureGenerationData, generation_data: AccelerationStructureGenerationData<'a>,
build_flags: VkBuildAccelerationStructureFlagBitsKHR, build_flags: VkBuildAccelerationStructureFlagBitsKHR,
} }
impl AccelerationStructure { impl<'a> AccelerationStructure<'a> {
pub fn bottom_level() -> AccelerationStructureBuilder { pub fn bottom_level() -> AccelerationStructureBuilder {
AccelerationStructureBuilder { AccelerationStructureBuilder {
flags: 0.into(), flags: 0.into(),
@ -303,7 +303,7 @@ impl AccelerationStructure {
} }
} }
pub fn result_buffer(&self) -> &Arc<Buffer<RawBuffer>> { pub fn result_buffer(&self) -> &Buffer<'a, RawBuffer> {
&self.result_buffer &self.result_buffer
} }
@ -390,10 +390,10 @@ impl AccelerationStructure {
#[inline] #[inline]
fn create_scratch_buffer( fn create_scratch_buffer(
device: &Arc<Device>, device: &Device,
size: VkDeviceSize, size: VkDeviceSize,
alignment: VkDeviceSize, alignment: VkDeviceSize,
) -> Result<Arc<Buffer<RawBuffer>>> { ) -> Result<Buffer<'a, RawBuffer>> {
Buffer::builder() Buffer::builder()
.set_usage( .set_usage(
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT,
@ -401,11 +401,11 @@ impl AccelerationStructure {
.set_memory_usage(MemoryUsage::GpuOnly) .set_memory_usage(MemoryUsage::GpuOnly)
.set_size(size) .set_size(size)
.force_alignment(alignment) .force_alignment(alignment)
.build(device.clone()) .build(device)
} }
} }
impl Drop for AccelerationStructure { impl<'a> Drop for AccelerationStructure<'a> {
fn drop(&mut self) { fn drop(&mut self) {
self.device self.device
.destroy_acceleration_structure(self.acceleration_structure, None); .destroy_acceleration_structure(self.acceleration_structure, None);
@ -418,11 +418,11 @@ impl_vk_handle!(
acceleration_structure acceleration_structure
); );
enum AccelerationStructureGenerationData { enum AccelerationStructureGenerationData<'a> {
TopLevel( TopLevel(
Vec<VkAccelerationStructureInstanceKHR>, Vec<VkAccelerationStructureInstanceKHR>,
VkAccelerationStructureGeometryKHR, VkAccelerationStructureGeometryKHR,
Arc<Buffer<VkAccelerationStructureInstanceKHR>>, Buffer<'a, VkAccelerationStructureInstanceKHR>,
), ),
BottomLevel( BottomLevel(
Vec<VkAccelerationStructureGeometryKHR>, Vec<VkAccelerationStructureGeometryKHR>,
@ -430,26 +430,26 @@ enum AccelerationStructureGenerationData {
), ),
} }
impl impl<'a>
From<( From<(
Vec<VkAccelerationStructureInstanceKHR>, Vec<VkAccelerationStructureInstanceKHR>,
VkAccelerationStructureGeometryKHR, VkAccelerationStructureGeometryKHR,
Arc<Buffer<VkAccelerationStructureInstanceKHR>>, Buffer<'a, VkAccelerationStructureInstanceKHR>,
)> for AccelerationStructureGenerationData )> for AccelerationStructureGenerationData<'a>
{ {
fn from( fn from(
(instances, geometry, buffer): ( (instances, geometry, buffer): (
Vec<VkAccelerationStructureInstanceKHR>, Vec<VkAccelerationStructureInstanceKHR>,
VkAccelerationStructureGeometryKHR, VkAccelerationStructureGeometryKHR,
Arc<Buffer<VkAccelerationStructureInstanceKHR>>, Buffer<'a, VkAccelerationStructureInstanceKHR>,
), ),
) -> Self { ) -> Self {
Self::TopLevel(instances, geometry, buffer) Self::TopLevel(instances, geometry, buffer)
} }
} }
impl From<(Vec<VkAccelerationStructureGeometryKHR>, Vec<u32>)> impl<'a> From<(Vec<VkAccelerationStructureGeometryKHR>, Vec<u32>)>
for AccelerationStructureGenerationData for AccelerationStructureGenerationData<'a>
{ {
fn from( fn from(
(geometries, primitive_counts): (Vec<VkAccelerationStructureGeometryKHR>, Vec<u32>), (geometries, primitive_counts): (Vec<VkAccelerationStructureGeometryKHR>, Vec<u32>),

View file

@ -4,7 +4,6 @@ use anyhow::Result;
use std; use std;
use std::mem; use std::mem;
use std::sync::Arc;
pub struct BufferBuilder<'a, T: ReprC> { pub struct BufferBuilder<'a, T: ReprC> {
flags: VkBufferCreateFlagBits, flags: VkBufferCreateFlagBits,
@ -62,7 +61,7 @@ impl<'a, T: ReprC> BufferBuilder<'a, T> {
} }
impl<'a, T: ReprC + Clone + Send + Sync + 'static> BufferBuilder<'a, T> { impl<'a, T: ReprC + Clone + Send + Sync + 'static> BufferBuilder<'a, T> {
pub fn build(self, device: Arc<Device>) -> Result<Arc<Buffer<T>>> { pub fn build(self, device: &'a Device) -> Result<Buffer<'a, T>> {
let size = match self.data { let size = match self.data {
Some(data) => data.len() as VkDeviceSize, Some(data) => data.len() as VkDeviceSize,
None => self.size, None => self.size,
@ -90,18 +89,18 @@ impl<'a, T: ReprC + Clone + Send + Sync + 'static> BufferBuilder<'a, T> {
memory_requirements.alignment = alignment; memory_requirements.alignment = alignment;
Memory::forced_requirements( Memory::forced_requirements(
&device, device,
memory_requirements, memory_requirements,
buffer, buffer,
MemoryUsage::into_vma(self.memory_usage), MemoryUsage::into_vma(self.memory_usage),
)? )?
} }
None => { None => {
Memory::buffer_memory(&device, buffer, MemoryUsage::into_vma(self.memory_usage))? Memory::buffer_memory(device, buffer, MemoryUsage::into_vma(self.memory_usage))?
} }
}; };
let buffer = Arc::new(Buffer { let buffer = Buffer {
device, device,
buffer, buffer,
memory, memory,
@ -111,7 +110,7 @@ impl<'a, T: ReprC + Clone + Send + Sync + 'static> BufferBuilder<'a, T> {
_sharing_mode: self.sharing_mode, _sharing_mode: self.sharing_mode,
size, size,
}); };
if let Some(data) = self.data { if let Some(data) = self.data {
buffer.fill(data)?; buffer.fill(data)?;
@ -122,11 +121,11 @@ impl<'a, T: ReprC + Clone + Send + Sync + 'static> BufferBuilder<'a, T> {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Buffer<T: ReprC> { pub struct Buffer<'a, T: ReprC> {
device: Arc<Device>, device: &'a Device,
buffer: VkBuffer, buffer: VkBuffer,
memory: Arc<Memory<T>>, memory: Memory<'a, T>,
_usage: VkBufferUsageFlagBits, _usage: VkBufferUsageFlagBits,
@ -134,7 +133,7 @@ pub struct Buffer<T: ReprC> {
size: VkDeviceSize, size: VkDeviceSize,
} }
impl<T: ReprC + Clone + Send + Sync + 'static> Buffer<T> { impl<'a, T: ReprC + Clone + Send + Sync + 'static> Buffer<'a, T> {
pub fn fill(&self, data: &[T]) -> Result<()> { pub fn fill(&self, data: &[T]) -> Result<()> {
let mut buffer_map = self.map(data.len() as VkDeviceSize)?; let mut buffer_map = self.map(data.len() as VkDeviceSize)?;
@ -152,19 +151,19 @@ impl<T: ReprC + Clone + Send + Sync + 'static> Buffer<T> {
} }
pub fn into_device_local( pub fn into_device_local(
self: &Arc<Buffer<T>>, &self,
buffer_recorder: &mut CommandBufferRecorder<'_>, buffer_recorder: &mut CommandBufferRecorder<'_>,
access_mask: impl Into<VkAccessFlagBits>, access_mask: impl Into<VkAccessFlagBits>,
stage: impl Into<VkPipelineStageFlagBits>, stage: impl Into<VkPipelineStageFlagBits>,
usage: impl Into<VkBufferUsageFlagBits>, usage: impl Into<VkBufferUsageFlagBits>,
) -> Result<Arc<Buffer<T>>> { ) -> Result<Buffer<'a, T>> {
let new_usage = usage.into() | VK_BUFFER_USAGE_TRANSFER_DST_BIT; let new_usage = usage.into() | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
let device_local_buffer = Buffer::builder() let device_local_buffer = Buffer::builder()
.set_memory_usage(MemoryUsage::GpuOnly) .set_memory_usage(MemoryUsage::GpuOnly)
.set_usage(new_usage) .set_usage(new_usage)
.set_size(self.size) .set_size(self.size)
.build(self.device.clone())?; .build(self.device)?;
// copy complete buffer // copy complete buffer
buffer_recorder.copy_buffer( buffer_recorder.copy_buffer(
@ -190,8 +189,8 @@ impl<T: ReprC + Clone + Send + Sync + 'static> Buffer<T> {
} }
} }
impl<T: ReprC> Buffer<T> { impl<'a, T: ReprC> Buffer<'a, T> {
pub fn builder<'a>() -> BufferBuilder<'a, T> { pub fn builder() -> BufferBuilder<'a, T> {
BufferBuilder { BufferBuilder {
flags: 0u32.into(), flags: 0u32.into(),
usage: 0u32.into(), usage: 0u32.into(),
@ -217,72 +216,28 @@ impl<T: ReprC> Buffer<T> {
} }
} }
impl<T: ReprC> VulkanDevice for Buffer<T> { impl<'a, T: ReprC> VulkanDevice for Buffer<'a, T> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl_vk_handle_t!(Buffer[ReprC], VkBuffer, buffer); impl_vk_handle_t!(Buffer[ReprC], VkBuffer, buffer);
impl<T: ReprC> VkHandle<VkDeviceMemory> for Buffer<T> { impl<'a, T: ReprC> VkHandle<VkDeviceMemory> for Buffer<'a, T> {
fn vk_handle(&self) -> VkDeviceMemory { fn vk_handle(&self) -> VkDeviceMemory {
self.memory.vk_handle() self.memory.vk_handle()
} }
} }
impl<'a, T: ReprC> VkHandle<VkDeviceMemory> for &'a Buffer<T> { impl<'a, T: ReprC> VkHandle<VkDeviceMemory> for &'a Buffer<'a, T> {
fn vk_handle(&self) -> VkDeviceMemory { fn vk_handle(&self) -> VkDeviceMemory {
self.memory.vk_handle() self.memory.vk_handle()
} }
} }
impl<T: ReprC> VkHandle<VkDeviceMemory> for Arc<Buffer<T>> { impl<'a, T: ReprC> Drop for Buffer<'a, T> {
fn vk_handle(&self) -> VkDeviceMemory {
self.memory.vk_handle()
}
}
impl<'a, T: ReprC> VkHandle<VkDeviceMemory> for &'a Arc<Buffer<T>> {
fn vk_handle(&self) -> VkDeviceMemory {
self.memory.vk_handle()
}
}
impl<T: ReprC> Drop for Buffer<T> {
fn drop(&mut self) { fn drop(&mut self) {
self.device.destroy_buffer(self.buffer); self.device.destroy_buffer(self.buffer);
} }
} }
// use crate::{ffi::*, handle_ffi_result};
impl<T: ReprC> FFIBufferTrait for Buffer<T> {
fn byte_size(&self) -> VkDeviceSize {
self.byte_size()
}
}
pub trait FFIBufferTrait {
fn byte_size(&self) -> VkDeviceSize;
}
pub struct FFIBuffer {
trait_obj: Box<dyn FFIBufferTrait>,
}
impl FFIBuffer {
fn byte_size(&self) -> VkDeviceSize {
self.trait_obj.byte_size()
}
}
#[no_mangle]
pub extern "C" fn create_buffer(_device: *const Device) -> *const FFIBuffer {
todo!()
}
#[no_mangle]
pub extern "C" fn byte_size(buffer: *const FFIBuffer) -> VkDeviceSize {
unsafe { &*buffer }.byte_size()
}

View file

@ -9,7 +9,7 @@ use anyhow::Result;
use std::any::Any; use std::any::Any;
use std::sync::{ use std::sync::{
atomic::{AtomicUsize, Ordering::SeqCst}, atomic::{AtomicUsize, Ordering::SeqCst},
Arc, Mutex, MutexGuard, Mutex, MutexGuard,
}; };
pub struct QueryEnable { pub struct QueryEnable {
@ -29,11 +29,11 @@ impl CommandBufferBuilder {
self self
} }
pub fn build( pub fn build<'a>(
self, self,
device: Arc<Device>, device: &'a Device,
queue: Arc<Mutex<Queue>>, queue: &'a Mutex<Queue<'a>>,
) -> Result<Arc<CommandBuffer>> { ) -> Result<Arc<CommandBuffer<'a>>> {
let command_pool = self let command_pool = self
.pool_builder .pool_builder
.set_queue_family_index( .set_queue_family_index(
@ -42,7 +42,7 @@ impl CommandBufferBuilder {
.map_err(|_| anyhow::Error::msg("Failed locking vulkan queue"))? .map_err(|_| anyhow::Error::msg("Failed locking vulkan queue"))?
.family_index(), .family_index(),
) )
.build(device.clone())?; .build(device)?;
let command_buffer_ci = let command_buffer_ci =
VkCommandBufferAllocateInfo::new(command_pool.vk_handle(), self.buffer_level, 1); VkCommandBufferAllocateInfo::new(command_pool.vk_handle(), self.buffer_level, 1);
@ -62,30 +62,30 @@ impl CommandBufferBuilder {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct CommandBuffer { pub struct CommandBuffer<'a> {
device: Arc<Device>, device: &'a Device,
pool: Arc<CommandPool>, pool: CommandPool<'a>,
buffer: VkCommandBuffer, buffer: VkCommandBuffer,
calls: Arc<AtomicUsize>, calls: Arc<AtomicUsize>,
stored_handles: Mutex<Vec<Arc<dyn Any + Send + Sync>>>, stored_handles: Mutex<Vec<&'a (dyn Any + Send + Sync)>>,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct CommandBufferRecorder<'a> { pub struct CommandBufferRecorder<'a> {
device: Arc<Device>, device: &'a Device,
sub_pass: u32, sub_pass: u32,
pipeline: Option<Arc<Pipeline>>, pipeline: Option<Arc<Pipeline>>,
calls: Arc<AtomicUsize>, calls: Arc<AtomicUsize>,
buffer: VkCommandBuffer, buffer: VkCommandBuffer,
handles_lock: MutexGuard<'a, Vec<Arc<dyn Any + Send + Sync>>>, handles_lock: MutexGuard<'a, Vec<&'a (dyn Any + Send + Sync)>>,
} }
impl_vk_handle!(CommandBuffer, VkCommandBuffer, buffer); impl_vk_handle!(CommandBuffer, VkCommandBuffer, buffer);
impl CommandBuffer { impl<'a> CommandBuffer<'a> {
pub fn new_primary() -> CommandBufferBuilder { pub fn new_primary() -> CommandBufferBuilder {
CommandBufferBuilder { CommandBufferBuilder {
buffer_level: VK_COMMAND_BUFFER_LEVEL_PRIMARY, buffer_level: VK_COMMAND_BUFFER_LEVEL_PRIMARY,
@ -572,14 +572,14 @@ impl<'a> CommandBufferRecorder<'a> {
pub fn set_image_layout( pub fn set_image_layout(
&mut self, &mut self,
image: &Arc<Image>, image: &Image<'a>,
new_image_layout: VkImageLayout, new_image_layout: VkImageLayout,
subresource_range: VkImageSubresourceRange, subresource_range: VkImageSubresourceRange,
) { ) {
let src_access = Image::src_layout_to_access(image.image_layout()); let src_access = Image::src_layout_to_access(image.image_layout());
let dst_access = Image::dst_layout_to_access(new_image_layout); let dst_access = Image::dst_layout_to_access(new_image_layout);
self.handles_lock.push(image.clone()); self.handles_lock.push(image);
self.pipeline_barrier( self.pipeline_barrier(
CommandBuffer::access_to_stage(src_access), CommandBuffer::access_to_stage(src_access),
@ -760,8 +760,8 @@ impl<'a> CommandBufferRecorder<'a> {
pub fn blit_image( pub fn blit_image(
&mut self, &mut self,
src_image: &Arc<Image>, src_image: &Image<'a>,
dst_image: &Arc<Image>, dst_image: &Image<'a>,
src_layout: VkImageLayout, src_layout: VkImageLayout,
dst_layout: VkImageLayout, dst_layout: VkImageLayout,
regions: &[VkImageBlit], regions: &[VkImageBlit],
@ -769,8 +769,8 @@ impl<'a> CommandBufferRecorder<'a> {
) { ) {
self.calls.fetch_add(1, SeqCst); self.calls.fetch_add(1, SeqCst);
self.handles_lock.push(src_image.clone()); self.handles_lock.push(src_image);
self.handles_lock.push(dst_image.clone()); self.handles_lock.push(dst_image);
self.device.cmd_blit_image( self.device.cmd_blit_image(
self.buffer, self.buffer,
@ -785,15 +785,15 @@ impl<'a> CommandBufferRecorder<'a> {
pub fn copy_buffer_to_image<T: ReprC + Send + Sync + 'static>( pub fn copy_buffer_to_image<T: ReprC + Send + Sync + 'static>(
&mut self, &mut self,
src_buffer: &Arc<Buffer<T>>, src_buffer: &Arc<Buffer<'a, T>>,
dst_image: &Arc<Image>, dst_image: &Image<'a>,
image_layout: VkImageLayout, image_layout: VkImageLayout,
regions: &[VkBufferImageCopy], regions: &[VkBufferImageCopy],
) { ) {
self.calls.fetch_add(1, SeqCst); self.calls.fetch_add(1, SeqCst);
self.handles_lock.push(src_buffer.clone()); self.handles_lock.push(src_buffer.clone());
self.handles_lock.push(dst_image.clone()); self.handles_lock.push(dst_image);
self.device.cmd_copy_buffer_to_image( self.device.cmd_copy_buffer_to_image(
self.buffer, self.buffer,

View file

@ -22,7 +22,7 @@ impl CommandPoolBuilder {
self self
} }
pub(crate) fn build(self, device: Arc<Device>) -> Result<Arc<CommandPool>> { pub(crate) fn build<'a>(self, device: &'a Device) -> Result<Arc<CommandPool<'a>>> {
let command_pool_ci = VkCommandPoolCreateInfo::new(self.flags, self.queue_family_index); let command_pool_ci = VkCommandPoolCreateInfo::new(self.flags, self.queue_family_index);
let command_pool = device.create_command_pool(&command_pool_ci)?; let command_pool = device.create_command_pool(&command_pool_ci)?;
@ -35,12 +35,12 @@ impl CommandPoolBuilder {
} }
#[derive(Debug)] #[derive(Debug)]
pub(crate) struct CommandPool { pub(crate) struct CommandPool<'a> {
device: Arc<Device>, device: &'a Device,
command_pool: VkCommandPool, command_pool: VkCommandPool,
} }
impl CommandPool { impl<'a> CommandPool<'a> {
pub(crate) fn builder() -> CommandPoolBuilder { pub(crate) fn builder() -> CommandPoolBuilder {
CommandPoolBuilder { CommandPoolBuilder {
flags: VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT flags: VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT
@ -50,39 +50,16 @@ impl CommandPool {
} }
} }
impl VulkanDevice for CommandPool { impl<'a> VulkanDevice for CommandPool<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl_vk_handle!(CommandPool, VkCommandPool, command_pool); impl_vk_handle!(CommandPool, VkCommandPool, command_pool);
impl Drop for CommandPool { impl<'a> Drop for CommandPool<'a> {
fn drop(&mut self) { fn drop(&mut self) {
self.device.destroy_command_pool(self.command_pool); self.device.destroy_command_pool(self.command_pool);
} }
} }
// use crate::{ffi::*, handle_ffi_result};
// #[no_mangle]
// pub extern "C" fn create_command_pool(
// flags: VkCommandPoolCreateFlagBits,
// queue_family_index: u32,
// device: *const Device,
// ) -> *const CommandPool {
// let device = unsafe { Arc::from_raw(device) };
// let pool_res = CommandPool::builder()
// .set_flags(flags)
// .set_queue_family_index(queue_family_index)
// .build(device);
// handle_ffi_result!(pool_res)
// }
// #[no_mangle]
// pub extern "C" fn destroy_command_pool(command_pool: *const CommandPool) {
// let _pool = unsafe { Arc::from_raw(command_pool) };
// }

View file

@ -2,15 +2,13 @@ use crate::prelude::*;
use anyhow::Result; use anyhow::Result;
use std::sync::Arc; pub struct DescriptorPoolBuilder<'a> {
layout: Option<&'a DescriptorSetLayout<'a>>,
pub struct DescriptorPoolBuilder {
layout: Option<Arc<DescriptorSetLayout>>,
descriptor_count: u32, descriptor_count: u32,
flags: VkDescriptorPoolCreateFlagBits, flags: VkDescriptorPoolCreateFlagBits,
} }
impl DescriptorPoolBuilder { impl<'a> DescriptorPoolBuilder<'a> {
pub fn set_flags(mut self, flags: impl Into<VkDescriptorPoolCreateFlagBits>) -> Self { pub fn set_flags(mut self, flags: impl Into<VkDescriptorPoolCreateFlagBits>) -> Self {
self.flags |= flags.into(); self.flags |= flags.into();
@ -23,13 +21,13 @@ impl DescriptorPoolBuilder {
self self
} }
pub fn set_layout(mut self, layout: Arc<DescriptorSetLayout>) -> Self { pub fn set_layout(mut self, layout: &'a DescriptorSetLayout<'a>) -> Self {
self.layout = Some(layout); self.layout = Some(layout);
self self
} }
pub fn build(self, device: Arc<Device>) -> Result<Arc<DescriptorPool>> { pub fn build(self, device: &'a Device) -> Result<DescriptorPool<'a>> {
if cfg!(debug_assertions) { if cfg!(debug_assertions) {
if self.layout.is_none() { if self.layout.is_none() {
panic!("no layout set!"); panic!("no layout set!");
@ -60,23 +58,23 @@ impl DescriptorPoolBuilder {
let descriptor_pool = device.create_descriptor_pool(&descriptor_pool_ci)?; let descriptor_pool = device.create_descriptor_pool(&descriptor_pool_ci)?;
Ok(Arc::new(DescriptorPool { Ok(DescriptorPool {
device, device,
descriptor_pool, descriptor_pool,
descriptor_set_layout: layout, descriptor_set_layout: layout,
})) })
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct DescriptorPool { pub struct DescriptorPool<'a> {
device: Arc<Device>, device: &'a Device,
descriptor_pool: VkDescriptorPool, descriptor_pool: VkDescriptorPool,
pub(crate) descriptor_set_layout: Arc<DescriptorSetLayout>, pub(crate) descriptor_set_layout: &'a DescriptorSetLayout<'a>,
} }
impl DescriptorPool { impl<'a> DescriptorPool<'a> {
pub fn builder() -> DescriptorPoolBuilder { pub fn builder() -> DescriptorPoolBuilder<'a> {
DescriptorPoolBuilder { DescriptorPoolBuilder {
layout: None, layout: None,
descriptor_count: 1, descriptor_count: 1,
@ -89,83 +87,33 @@ impl DescriptorPool {
.reset_descriptor_pool(self.descriptor_pool, VK_DESCRIPTOR_POOL_RESET_NULL_BIT) .reset_descriptor_pool(self.descriptor_pool, VK_DESCRIPTOR_POOL_RESET_NULL_BIT)
} }
pub fn prepare_set(self: &Arc<Self>) -> DescriptorSetBuilder { pub fn prepare_set(&self) -> DescriptorSetBuilder<'a> {
DescriptorSet::builder(self.device.clone(), self.clone()) DescriptorSet::builder(self.device, self)
} }
} }
impl VulkanDevice for DescriptorPool { impl<'a> VulkanDevice for DescriptorPool<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl_vk_handle!(DescriptorPool, VkDescriptorPool, descriptor_pool); impl_vk_handle!(DescriptorPool, VkDescriptorPool, descriptor_pool);
impl VkHandle<VkDescriptorSetLayout> for DescriptorPool { impl<'a> VkHandle<VkDescriptorSetLayout> for DescriptorPool<'a> {
fn vk_handle(&self) -> VkDescriptorSetLayout { fn vk_handle(&self) -> VkDescriptorSetLayout {
self.descriptor_set_layout.vk_handle() self.descriptor_set_layout.vk_handle()
} }
} }
impl<'a> VkHandle<VkDescriptorSetLayout> for &'a DescriptorPool { impl<'a> VkHandle<VkDescriptorSetLayout> for &'a DescriptorPool<'a> {
fn vk_handle(&self) -> VkDescriptorSetLayout { fn vk_handle(&self) -> VkDescriptorSetLayout {
self.descriptor_set_layout.vk_handle() self.descriptor_set_layout.vk_handle()
} }
} }
impl VkHandle<VkDescriptorSetLayout> for Arc<DescriptorPool> { impl<'a> Drop for DescriptorPool<'a> {
fn vk_handle(&self) -> VkDescriptorSetLayout {
self.descriptor_set_layout.vk_handle()
}
}
impl<'a> VkHandle<VkDescriptorSetLayout> for &'a Arc<DescriptorPool> {
fn vk_handle(&self) -> VkDescriptorSetLayout {
self.descriptor_set_layout.vk_handle()
}
}
impl Drop for DescriptorPool {
fn drop(&mut self) { fn drop(&mut self) {
self.device.destroy_descriptor_pool(self.descriptor_pool); self.device.destroy_descriptor_pool(self.descriptor_pool);
} }
} }
use crate::{ffi::*, handle_ffi_result};
#[no_mangle]
pub extern "C" fn create_descriptor_pool(
flags: VkDescriptorPoolCreateFlagBits,
descriptor_set_layout: *const DescriptorSetLayout,
device: *const Device,
) -> *const DescriptorPool {
let device = unsafe { Arc::from_raw(device) };
let layout = unsafe { Arc::from_raw(descriptor_set_layout) };
let pool_res = DescriptorPool::builder()
.set_flags(flags)
.set_layout(layout)
.build(device);
handle_ffi_result!(pool_res)
}
#[no_mangle]
pub extern "C" fn reset_descriptor_pool(descriptor_pool: *const DescriptorPool) -> bool {
let pool = unsafe { Arc::from_raw(descriptor_pool) };
match pool.reset() {
Ok(_) => true,
Err(err) => {
update_last_error(err);
false
}
}
}
#[no_mangle]
pub extern "C" fn destroy_descriptor_pool(descriptor_pool: *const DescriptorPool) {
let _pool = unsafe { Arc::from_raw(descriptor_pool) };
}

View file

@ -5,14 +5,14 @@ use anyhow::Result;
use std::any::Any; use std::any::Any;
use std::collections::HashMap; use std::collections::HashMap;
use std::slice; use std::slice;
use std::sync::{Arc, Mutex}; use std::sync::Mutex;
#[derive(Debug)] #[derive(Debug)]
pub struct DescriptorWrite { pub struct DescriptorWrite<'a> {
binding: u32, binding: u32,
descriptor_type: VkDescriptorType, descriptor_type: VkDescriptorType,
inner: InnerWrite, inner: InnerWrite,
handles: Vec<Arc<dyn Any + Send + Sync>>, handles: Vec<&'a (dyn Any + Send + Sync)>,
} }
#[derive(Debug)] #[derive(Debug)]
@ -27,10 +27,10 @@ enum InnerWrite {
), ),
} }
impl DescriptorWrite { impl<'a> DescriptorWrite<'a> {
pub fn uniform_buffers<T: ReprC + Send + Sync + 'static>( pub fn uniform_buffers<T: ReprC + Send + Sync + 'static>(
binding: u32, binding: u32,
buffers: &[&Arc<Buffer<T>>], buffers: &[&Buffer<'a, T>],
) -> Self { ) -> Self {
DescriptorWrite { DescriptorWrite {
binding, binding,
@ -47,14 +47,14 @@ impl DescriptorWrite {
), ),
handles: buffers handles: buffers
.iter() .iter()
.map(|b| (*b).clone() as Arc<dyn Any + Send + Sync>) .map(|b| (*b) as &'a (dyn Any + Send + Sync))
.collect(), .collect(),
} }
} }
pub fn storage_buffers<T: ReprC + Send + Sync + 'static>( pub fn storage_buffers<T: ReprC + Send + Sync + 'static>(
binding: u32, binding: u32,
buffers: &[&Arc<Buffer<T>>], buffers: &[&Buffer<'a, T>],
) -> Self { ) -> Self {
DescriptorWrite { DescriptorWrite {
binding, binding,
@ -71,12 +71,12 @@ impl DescriptorWrite {
), ),
handles: buffers handles: buffers
.iter() .iter()
.map(|b| (*b).clone() as Arc<dyn Any + Send + Sync>) .map(|b| (*b) as &'a (dyn Any + Send + Sync))
.collect(), .collect(),
} }
} }
pub fn combined_samplers(binding: u32, images: &[&Arc<Image>]) -> Self { pub fn combined_samplers(binding: u32, images: &[&'a Image<'a>]) -> Self {
DescriptorWrite { DescriptorWrite {
binding, binding,
descriptor_type: VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, descriptor_type: VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
@ -96,12 +96,12 @@ impl DescriptorWrite {
), ),
handles: images handles: images
.iter() .iter()
.map(|i| (*i).clone() as Arc<dyn Any + Send + Sync>) .map(|i| (*i).clone() as &'a (dyn Any + Send + Sync))
.collect(), .collect(),
} }
} }
pub fn storage_images(binding: u32, images: &[&Arc<Image>]) -> Self { pub fn storage_images(binding: u32, images: &[&'a Image<'a>]) -> Self {
DescriptorWrite { DescriptorWrite {
binding, binding,
descriptor_type: VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, descriptor_type: VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
@ -117,12 +117,12 @@ impl DescriptorWrite {
), ),
handles: images handles: images
.iter() .iter()
.map(|i| (*i).clone() as Arc<dyn Any + Send + Sync>) .map(|i| (*i).clone() as &'a (dyn Any + Send + Sync))
.collect(), .collect(),
} }
} }
pub fn input_attachments(binding: u32, images: &[&Arc<Image>]) -> Self { pub fn input_attachments(binding: u32, images: &[&'a Image<'a>]) -> Self {
DescriptorWrite { DescriptorWrite {
binding, binding,
descriptor_type: VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, descriptor_type: VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT,
@ -138,14 +138,14 @@ impl DescriptorWrite {
), ),
handles: images handles: images
.iter() .iter()
.map(|i| (*i).clone() as Arc<dyn Any + Send + Sync>) .map(|i| (*i) as &'a (dyn Any + Send + Sync))
.collect(), .collect(),
} }
} }
pub fn acceleration_structures( pub fn acceleration_structures(
binding: u32, binding: u32,
acceleration_structures: &[&Arc<AccelerationStructure>], acceleration_structures: &[&AccelerationStructure<'a>],
) -> Self { ) -> Self {
let vk_as: Vec<VkAccelerationStructureKHR> = acceleration_structures let vk_as: Vec<VkAccelerationStructureKHR> = acceleration_structures
.iter() .iter()
@ -161,7 +161,7 @@ impl DescriptorWrite {
)), )),
handles: acceleration_structures handles: acceleration_structures
.iter() .iter()
.map(|a| (*a).clone() as Arc<dyn Any + Send + Sync>) .map(|a| (*a) as &'a (dyn Any + Send + Sync))
.collect(), .collect(),
}; };
@ -198,21 +198,21 @@ impl DescriptorWrite {
} }
} }
pub struct DescriptorSetBuilder { pub struct DescriptorSetBuilder<'a> {
device: Arc<Device>, device: &'a Device,
descriptor_pool: Arc<DescriptorPool>, descriptor_pool: &'a DescriptorPool<'a>,
variable_desc_counts: Vec<u32>, variable_desc_counts: Vec<u32>,
variable_descriptor_count: VkDescriptorSetVariableDescriptorCountAllocateInfoEXT, variable_descriptor_count: VkDescriptorSetVariableDescriptorCountAllocateInfoEXT,
} }
impl DescriptorSetBuilder { impl<'a> DescriptorSetBuilder<'a> {
pub fn set_variable_descriptor_counts(mut self, descriptor_counts: &[u32]) -> Self { pub fn set_variable_descriptor_counts(mut self, descriptor_counts: &[u32]) -> Self {
self.variable_desc_counts = descriptor_counts.to_vec(); self.variable_desc_counts = descriptor_counts.to_vec();
self self
} }
pub fn allocate(mut self) -> Result<Arc<DescriptorSet>> { pub fn allocate(mut self) -> Result<DescriptorSet<'a>> {
let layout = self.descriptor_pool.vk_handle(); let layout = self.descriptor_pool.vk_handle();
let mut descriptor_set_ci = VkDescriptorSetAllocateInfo::new( let mut descriptor_set_ci = VkDescriptorSetAllocateInfo::new(
@ -228,30 +228,30 @@ impl DescriptorSetBuilder {
let descriptor_set = self.device.allocate_descriptor_sets(&descriptor_set_ci)?[0]; let descriptor_set = self.device.allocate_descriptor_sets(&descriptor_set_ci)?[0];
Ok(Arc::new(DescriptorSet { Ok(DescriptorSet {
device: self.device, device: self.device,
pool: self.descriptor_pool, pool: self.descriptor_pool,
descriptor_set, descriptor_set,
handles: Mutex::new(HashMap::new()), handles: Mutex::new(HashMap::new()),
})) })
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct DescriptorSet { pub struct DescriptorSet<'a> {
device: Arc<Device>, device: &'a Device,
pool: Arc<DescriptorPool>, pool: &'a DescriptorPool<'a>,
descriptor_set: VkDescriptorSet, descriptor_set: VkDescriptorSet,
handles: Mutex<HashMap<u32, Vec<Arc<dyn Any + Send + Sync>>>>, handles: Mutex<HashMap<u32, Vec<&'a (dyn Any + Send + Sync)>>>,
} }
impl DescriptorSet { impl<'a> DescriptorSet<'a> {
pub(crate) fn builder( pub(crate) fn builder(
device: Arc<Device>, device: &'a Device,
descriptor_pool: Arc<DescriptorPool>, descriptor_pool: &'a DescriptorPool<'a>,
) -> DescriptorSetBuilder { ) -> DescriptorSetBuilder<'a> {
DescriptorSetBuilder { DescriptorSetBuilder {
device, device,
descriptor_pool, descriptor_pool,
@ -263,7 +263,7 @@ impl DescriptorSet {
} }
// TODO: add update function for VkCopyDescriptorSet // TODO: add update function for VkCopyDescriptorSet
pub fn update(&self, writes: &[DescriptorWrite]) -> Result<()> { pub fn update(&self, writes: &[DescriptorWrite<'a>]) -> Result<()> {
debug_assert!(!writes.is_empty()); debug_assert!(!writes.is_empty());
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@ -307,39 +307,27 @@ impl DescriptorSet {
} }
} }
impl VulkanDevice for DescriptorSet { impl<'a> VulkanDevice for DescriptorSet<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl_vk_handle!(DescriptorSet, VkDescriptorSet, descriptor_set); impl_vk_handle!(DescriptorSet, VkDescriptorSet, descriptor_set);
impl VkHandle<VkDescriptorSetLayout> for DescriptorSet { impl<'a> VkHandle<VkDescriptorSetLayout> for DescriptorSet<'a> {
fn vk_handle(&self) -> VkDescriptorSetLayout { fn vk_handle(&self) -> VkDescriptorSetLayout {
self.pool.vk_handle() self.pool.vk_handle()
} }
} }
impl<'a> VkHandle<VkDescriptorSetLayout> for &'a DescriptorSet { impl<'a> VkHandle<VkDescriptorSetLayout> for &'a DescriptorSet<'a> {
fn vk_handle(&self) -> VkDescriptorSetLayout { fn vk_handle(&self) -> VkDescriptorSetLayout {
self.pool.vk_handle() self.pool.vk_handle()
} }
} }
impl VkHandle<VkDescriptorSetLayout> for Arc<DescriptorSet> { impl<'a> Drop for DescriptorSet<'a> {
fn vk_handle(&self) -> VkDescriptorSetLayout {
self.pool.vk_handle()
}
}
impl<'a> VkHandle<VkDescriptorSetLayout> for &'a Arc<DescriptorSet> {
fn vk_handle(&self) -> VkDescriptorSetLayout {
self.pool.vk_handle()
}
}
impl Drop for DescriptorSet {
fn drop(&mut self) { fn drop(&mut self) {
if let Err(error) = self if let Err(error) = self
.device .device
@ -355,8 +343,6 @@ mod test {
use crate::prelude::*; use crate::prelude::*;
use anyhow::Result; use anyhow::Result;
use std::sync::Arc;
#[test] #[test]
fn create_multiple_sets_from_one_pool() -> Result<()> { fn create_multiple_sets_from_one_pool() -> Result<()> {
const DESCRIPTOR_COUNT: u32 = 2; const DESCRIPTOR_COUNT: u32 = 2;
@ -370,14 +356,14 @@ mod test {
VK_SHADER_STAGE_FRAGMENT_BIT, VK_SHADER_STAGE_FRAGMENT_BIT,
0, 0,
) )
.build(device.clone())?; .build(&device)?;
let descriptor_pool = DescriptorPool::builder() let descriptor_pool = DescriptorPool::builder()
.set_layout(descriptor_layout.clone()) .set_layout(&descriptor_layout)
.set_descriptor_set_count(DESCRIPTOR_COUNT) .set_descriptor_set_count(DESCRIPTOR_COUNT)
.build(device.clone())?; .build(&device)?;
let descriptors: Vec<Arc<DescriptorSet>> = (0..DESCRIPTOR_COUNT) let descriptors: Vec<DescriptorSet<'_>> = (0..DESCRIPTOR_COUNT)
.map(|_| { .map(|_| {
let set = descriptor_pool.prepare_set().allocate(); let set = descriptor_pool.prepare_set().allocate();

View file

@ -48,7 +48,7 @@ impl DescriptorSetLayoutBuilder {
self self
} }
pub fn build(self, device: Arc<Device>) -> Result<Arc<DescriptorSetLayout>> { pub fn build<'a>(self, device: &'a Device) -> Result<Arc<DescriptorSetLayout<'a>>> {
let mut descriptor_set_ci = let mut descriptor_set_ci =
VkDescriptorSetLayoutCreateInfo::new(self.flags, &self.layout_bindings); VkDescriptorSetLayoutCreateInfo::new(self.flags, &self.layout_bindings);
let binding_flags_ci = let binding_flags_ci =
@ -98,15 +98,15 @@ impl DescriptorSetLayoutBuilder {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct DescriptorSetLayout { pub struct DescriptorSetLayout<'a> {
device: Arc<Device>, device: &'a Device,
descriptor_set_layout: VkDescriptorSetLayout, descriptor_set_layout: VkDescriptorSetLayout,
pool_sizes: Vec<VkDescriptorPoolSize>, pool_sizes: Vec<VkDescriptorPoolSize>,
bindings: Vec<DescriptorLayoutBinding>, bindings: Vec<DescriptorLayoutBinding>,
} }
impl DescriptorSetLayout { impl<'a> DescriptorSetLayout<'a> {
pub fn builder() -> DescriptorSetLayoutBuilder { pub fn builder() -> DescriptorSetLayoutBuilder {
DescriptorSetLayoutBuilder { DescriptorSetLayoutBuilder {
layout_bindings: Vec::new(), layout_bindings: Vec::new(),
@ -124,8 +124,8 @@ impl DescriptorSetLayout {
} }
} }
impl VulkanDevice for DescriptorSetLayout { impl<'a> VulkanDevice for DescriptorSetLayout<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
@ -136,7 +136,7 @@ impl_vk_handle!(
descriptor_set_layout descriptor_set_layout
); );
impl Drop for DescriptorSetLayout { impl<'a> Drop for DescriptorSetLayout<'a> {
fn drop(&mut self) { fn drop(&mut self) {
self.device self.device
.destroy_descriptor_set_layout(self.descriptor_set_layout); .destroy_descriptor_set_layout(self.descriptor_set_layout);

View file

@ -53,7 +53,7 @@ pub struct Device {
enabled_extensions: DeviceExtensions, enabled_extensions: DeviceExtensions,
physical_device: Arc<PhysicalDevice>, physical_device: PhysicalDevice,
device: VkDevice, device: VkDevice,
memory_allocator: Allocator, memory_allocator: Allocator,
@ -65,9 +65,9 @@ impl Device {
pub fn preinitialized( pub fn preinitialized(
device: VkDevice, device: VkDevice,
proc_addr: PFN_vkGetDeviceProcAddr, proc_addr: PFN_vkGetDeviceProcAddr,
physical_device: Arc<PhysicalDevice>, physical_device: PhysicalDevice,
extensions: &[VkString], extensions: &[VkString],
) -> Result<Arc<Device>> { ) -> Result<Device> {
let device_functions = DeviceFunctions::load(|name| { let device_functions = DeviceFunctions::load(|name| {
proc_addr(device, name.as_ptr()) as *const std::ffi::c_void proc_addr(device, name.as_ptr()) as *const std::ffi::c_void
}); });
@ -133,7 +133,7 @@ impl Device {
physical_device.instance().api_version(), physical_device.instance().api_version(),
)?; )?;
Ok(Arc::new(Device { Ok(Device {
memory_allocator, memory_allocator,
device_functions, device_functions,
@ -151,15 +151,15 @@ impl Device {
device, device,
sampler_manager: SamplerManager::new(), sampler_manager: SamplerManager::new(),
})) })
} }
pub fn new( pub fn new(
physical_device: Arc<PhysicalDevice>, physical_device: PhysicalDevice,
mut extensions: DeviceExtensions, mut extensions: DeviceExtensions,
queue_infos: &[VkDeviceQueueCreateInfo], queue_infos: &[VkDeviceQueueCreateInfo],
requested_device_features: DeviceFeatures, requested_device_features: DeviceFeatures,
) -> Result<Arc<Device>> { ) -> Result<Device> {
// buffer device address is required in the current library implementation // buffer device address is required in the current library implementation
extensions.buffer_device_address = true; extensions.buffer_device_address = true;
@ -285,7 +285,7 @@ impl Device {
physical_device.instance().api_version(), physical_device.instance().api_version(),
)?; )?;
Ok(Arc::new(Device { Ok(Device {
memory_allocator, memory_allocator,
device_functions, device_functions,
@ -303,7 +303,7 @@ impl Device {
device, device,
sampler_manager: SamplerManager::new(), sampler_manager: SamplerManager::new(),
})) })
} }
fn verify_vma_vk_functions(fns: &VmaVulkanFunctions) -> Result<()> { fn verify_vma_vk_functions(fns: &VmaVulkanFunctions) -> Result<()> {
@ -348,26 +348,22 @@ impl Device {
Ok(()) Ok(())
} }
pub fn get_queue( pub fn get_queue<'a>(&'a self, queue_family_index: u32, queue_index: u32) -> Mutex<Queue<'a>> {
self: &Arc<Self>,
queue_family_index: u32,
queue_index: u32,
) -> Arc<Mutex<Queue>> {
Queue::new( Queue::new(
self.clone(), self,
self.get_device_queue(queue_family_index, queue_index), self.get_device_queue(queue_family_index, queue_index),
queue_family_index, queue_family_index,
queue_index, queue_index,
) )
} }
pub fn physical_device(&self) -> &Arc<PhysicalDevice> { pub fn physical_device(&self) -> &PhysicalDevice {
&self.physical_device &self.physical_device
} }
pub fn wait_for_fences( pub fn wait_for_fences<'a>(
&self, &self,
fences: &[&Arc<Fence>], fences: &[&Fence<'a>],
wait_all: bool, wait_all: bool,
timeout: Duration, timeout: Duration,
) -> Result<()> { ) -> Result<()> {
@ -879,7 +875,7 @@ impl Device {
pub(crate) fn create_sampler_from_manager( pub(crate) fn create_sampler_from_manager(
&self, &self,
create_info: VkSamplerCreateInfo, create_info: VkSamplerCreateInfo,
) -> Result<Arc<Sampler>> { ) -> Result<Sampler> {
self.sampler_manager self.sampler_manager
.lock() .lock()
.unwrap() .unwrap()

View file

@ -15,7 +15,7 @@ impl FenceBuilder {
self self
} }
pub fn build(self, device: Arc<Device>) -> Result<Arc<Fence>> { pub fn build<'a>(self, device: &'a Device) -> Result<Arc<Fence<'a>>> {
let flag: VkFenceCreateFlagBits = if self.signaled { let flag: VkFenceCreateFlagBits = if self.signaled {
VK_FENCE_CREATE_SIGNALED_BIT.into() VK_FENCE_CREATE_SIGNALED_BIT.into()
} else { } else {
@ -31,12 +31,12 @@ impl FenceBuilder {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Fence { pub struct Fence<'a> {
device: Arc<Device>, device: &'a Device,
fence: VkFence, fence: VkFence,
} }
impl Fence { impl<'a> Fence<'a> {
pub fn builder() -> FenceBuilder { pub fn builder() -> FenceBuilder {
FenceBuilder { signaled: false } FenceBuilder { signaled: false }
} }
@ -50,39 +50,16 @@ impl Fence {
} }
} }
impl VulkanDevice for Fence { impl<'a> VulkanDevice for Fence<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl_vk_handle!(Fence, VkFence, fence); impl_vk_handle!(Fence, VkFence, fence);
impl Drop for Fence { impl<'a> Drop for Fence<'a> {
fn drop(&mut self) { fn drop(&mut self) {
self.device.destroy_fence(self.fence); self.device.destroy_fence(self.fence);
} }
} }
use crate::{ffi::*, handle_ffi_result};
#[no_mangle]
pub extern "C" fn create_fence(signaled: bool, device: *const Device) -> *const Fence {
let device = unsafe { Arc::from_raw(device) };
let fence_res = Fence::builder().set_signaled(signaled).build(device);
handle_ffi_result!(fence_res)
}
#[no_mangle]
pub extern "C" fn reset_fence(fence: *const Fence) -> bool {
let fence = unsafe { Arc::from_raw(fence) };
fence.reset()
}
#[no_mangle]
pub extern "C" fn destroy_fence(fence: *const Fence) {
let _fence = unsafe { Arc::from_raw(fence) };
}

View file

@ -1,70 +0,0 @@
use std::cell::RefCell;
use std::os::raw::{c_char, c_int};
#[macro_export]
macro_rules! handle_ffi_result {
($result: expr) => {
match $result {
Ok(value) => Arc::into_raw(value),
Err(error) => {
update_last_error(error);
std::ptr::null()
}
}
};
}
thread_local! {
static LAST_ERROR:RefCell<Option<Box<String>>> = RefCell::new(None);
}
pub(crate) fn update_last_error(err: anyhow::Error) {
LAST_ERROR.with(|prev| {
*prev.borrow_mut() = Some(Box::new(format!("{:?}", err)));
});
}
pub(crate) fn take_last_error() -> Option<Box<String>> {
LAST_ERROR.with(|prev| prev.borrow_mut().take())
}
#[no_mangle]
pub extern "C" fn last_error_length() -> c_int {
LAST_ERROR.with(|prev| match *prev.borrow() {
Some(ref err) => err.to_string().len() as c_int + 1,
None => 0,
})
}
#[no_mangle]
pub unsafe extern "C" fn last_error_message(buffer: *mut c_char, length: c_int) -> c_int {
if buffer.is_null() {
return -1;
}
let last_error = match take_last_error() {
Some(err) => err,
None => return 0,
};
let error_message = last_error.to_string();
let buffer = std::slice::from_raw_parts_mut(buffer as *mut u8, length as usize);
if error_message.len() >= buffer.len() {
return -1;
}
std::ptr::copy_nonoverlapping(
error_message.as_ptr(),
buffer.as_mut_ptr(),
error_message.len(),
);
// Add a trailing null so people using the string as a `char *` don't
// accidentally read into garbage.
buffer[error_message.len()] = 0;
error_message.len() as c_int
}

View file

@ -6,7 +6,7 @@ use std::sync::Arc;
pub struct FramebufferBuilder<'a> { pub struct FramebufferBuilder<'a> {
render_pass: Option<&'a Arc<RenderPass>>, render_pass: Option<&'a Arc<RenderPass>>,
attachments: Vec<&'a Arc<Image>>, attachments: Vec<&'a Image<'a>>,
width: u32, width: u32,
height: u32, height: u32,
layers: u32, layers: u32,
@ -19,7 +19,7 @@ impl<'a> FramebufferBuilder<'a> {
self self
} }
pub fn add_attachment(mut self, image: &'a Arc<Image>) -> Self { pub fn add_attachment(mut self, image: &'a Image<'a>) -> Self {
self.attachments.push(image); self.attachments.push(image);
self self
@ -43,7 +43,7 @@ impl<'a> FramebufferBuilder<'a> {
self self
} }
pub fn build(mut self, device: Arc<Device>) -> Result<Arc<Framebuffer>> { pub fn build(mut self, device: Arc<Device>) -> Result<Framebuffer<'a>> {
if self.attachments.is_empty() { if self.attachments.is_empty() {
panic!("no attachments added!"); panic!("no attachments added!");
} }
@ -80,29 +80,29 @@ impl<'a> FramebufferBuilder<'a> {
let framebuffer = device.create_framebuffer(&framebuffer_ci)?; let framebuffer = device.create_framebuffer(&framebuffer_ci)?;
Ok(Arc::new(Framebuffer { Ok(Framebuffer {
device, device,
framebuffer, framebuffer,
images, images,
width: self.width, width: self.width,
height: self.height, height: self.height,
})) })
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Framebuffer { pub struct Framebuffer<'a> {
device: Arc<Device>, device: Arc<Device>,
framebuffer: VkFramebuffer, framebuffer: VkFramebuffer,
images: Vec<Arc<Image>>, images: Vec<&'a Image<'a>>,
width: u32, width: u32,
height: u32, height: u32,
} }
impl Framebuffer { impl<'a> Framebuffer<'a> {
pub fn builder<'a>() -> FramebufferBuilder<'a> { pub fn builder() -> FramebufferBuilder<'a> {
FramebufferBuilder { FramebufferBuilder {
render_pass: None, render_pass: None,
attachments: Vec::new(), attachments: Vec::new(),
@ -120,11 +120,11 @@ impl Framebuffer {
self.height self.height
} }
pub fn attachments(&self) -> &[Arc<Image>] { pub fn attachments(&self) -> &[&'a Image<'a>] {
&self.images &self.images
} }
pub fn image(&self, index: usize) -> &Arc<Image> { pub fn image(&self, index: usize) -> &Image<'a> {
&self.images[index] &self.images[index]
} }
@ -133,15 +133,15 @@ impl Framebuffer {
} }
} }
impl VulkanDevice for Framebuffer { impl<'a> VulkanDevice for Framebuffer<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl_vk_handle!(Framebuffer, VkFramebuffer, framebuffer); impl_vk_handle!(Framebuffer, VkFramebuffer, framebuffer);
impl Drop for Framebuffer { impl<'a> Drop for Framebuffer<'a> {
fn drop(&mut self) { fn drop(&mut self) {
self.device.destroy_framebuffer(self.framebuffer); self.device.destroy_framebuffer(self.framebuffer);
} }

View file

@ -9,20 +9,20 @@ use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
enum ImageSourceType { enum ImageSourceType<'a> {
Empty, Empty,
Raw(Vec<u8>), Raw(Vec<u8>),
Array(Vec<Arc<Image>>), Array(Vec<Image<'a>>),
} }
struct ImageCreateInfo { struct ImageCreateInfo<'a> {
vk_image_create_info: VkImageCreateInfo, vk_image_create_info: VkImageCreateInfo,
source_type: ImageSourceType, source_type: ImageSourceType<'a>,
} }
impl ImageCreateInfo { impl<'a> ImageCreateInfo<'a> {
fn default(source_type: ImageSourceType) -> Self { fn default(source_type: ImageSourceType<'a>) -> Self {
ImageCreateInfo { ImageCreateInfo {
vk_image_create_info: VkImageCreateInfo::new( vk_image_create_info: VkImageCreateInfo::new(
0, 0,
@ -62,25 +62,25 @@ struct PreinitializedImage {
assume_layout: bool, assume_layout: bool,
} }
enum ImageBuilderInternalType { enum ImageBuilderInternalType<'a> {
PreinitializedImage(PreinitializedImage), PreinitializedImage(PreinitializedImage),
NewImage(ImageCreateInfo), NewImage(ImageCreateInfo<'a>),
} }
/// Implements the builder pattern for Image /// Implements the builder pattern for Image
pub struct ImageBuilder { pub struct ImageBuilder<'a> {
file_name: Option<AssetPath>, file_name: Option<AssetPath>,
builder_type: ImageBuilderInternalType, builder_type: ImageBuilderInternalType<'a>,
components: VkComponentMapping, components: VkComponentMapping,
view_type: VkImageViewType, view_type: VkImageViewType,
subresource_range: VkImageSubresourceRange, subresource_range: VkImageSubresourceRange,
sampler: Option<Arc<Sampler>>, sampler: Option<Sampler>,
} }
impl ImageBuilder { impl<'a> ImageBuilder<'a> {
/// Sets up the ImageBuilder for further use /// Sets up the ImageBuilder for further use
fn new(internal_type: ImageBuilderInternalType) -> Self { fn new(internal_type: ImageBuilderInternalType<'a>) -> Self {
ImageBuilder { ImageBuilder {
file_name: None, file_name: None,
builder_type: internal_type, builder_type: internal_type,
@ -98,7 +98,7 @@ impl ImageBuilder {
} }
} }
pub fn build(self, device: &Arc<Device>, queue: &Arc<Mutex<Queue>>) -> Result<Arc<Image>> { pub fn build(self, device: &'a Device, queue: &'a Mutex<Queue<'a>>) -> Result<Image<'a>> {
let mut image_view_ci = self.vk_image_view_create_info(); let mut image_view_ci = self.vk_image_view_create_info();
match self.builder_type { match self.builder_type {
@ -107,9 +107,9 @@ impl ImageBuilder {
let image_view = device.create_image_view(&image_view_ci)?; let image_view = device.create_image_view(&image_view_ci)?;
let image = Arc::new(Image { let image = Image {
device: device.clone(), device,
queue: queue.clone(), queue,
image: preinitialized_image.image, image: preinitialized_image.image,
image_view, image_view,
@ -130,7 +130,7 @@ impl ImageBuilder {
levels: 1, levels: 1,
sample_count: preinitialized_image.sample_count, sample_count: preinitialized_image.sample_count,
usage: preinitialized_image.usage, usage: preinitialized_image.usage,
}); };
// TODO: check necessity // TODO: check necessity
if !preinitialized_image.assume_layout { if !preinitialized_image.assume_layout {
@ -308,7 +308,7 @@ impl ImageBuilder {
self self
} }
pub fn attach_sampler(mut self, sampler: Arc<Sampler>) -> Self { pub fn attach_sampler(mut self, sampler: Sampler) -> Self {
self.sampler = Some(sampler); self.sampler = Some(sampler);
if let ImageBuilderInternalType::NewImage(ref mut info) = self.builder_type { if let ImageBuilderInternalType::NewImage(ref mut info) = self.builder_type {
@ -384,13 +384,13 @@ impl ImageBuilder {
} }
fn create_from_source( fn create_from_source(
device: &Arc<Device>, device: &Device,
queue: &Arc<Mutex<Queue>>, queue: &Mutex<Queue<'a>>,
info: &ImageCreateInfo, info: &ImageCreateInfo<'a>,
sampler: Option<Arc<Sampler>>, sampler: Option<Sampler>,
mut view_ci: VkImageViewCreateInfo, mut view_ci: VkImageViewCreateInfo,
file_name: Option<AssetPath>, file_name: Option<AssetPath>,
) -> Result<Arc<Image>> { ) -> Result<Image<'a>> {
let format = view_ci.format; let format = view_ci.format;
let (image, memory) = Self::create_texture(device, &info.vk_image_create_info)?; let (image, memory) = Self::create_texture(device, &info.vk_image_create_info)?;
@ -399,7 +399,7 @@ impl ImageBuilder {
let image_view = device.create_image_view(&view_ci)?; let image_view = device.create_image_view(&view_ci)?;
Ok(Arc::new(Image { Ok(Image {
device: device.clone(), device: device.clone(),
queue: queue.clone(), queue: queue.clone(),
@ -422,13 +422,13 @@ impl ImageBuilder {
levels: info.vk_image_create_info.mipLevels, levels: info.vk_image_create_info.mipLevels,
sample_count: info.vk_image_create_info.samples, sample_count: info.vk_image_create_info.samples,
usage: info.vk_image_create_info.usage, usage: info.vk_image_create_info.usage,
})) })
} }
fn create_texture( fn create_texture(
device: &Arc<Device>, device: &Device,
image_ci: &VkImageCreateInfo, image_ci: &VkImageCreateInfo,
) -> Result<(VkImage, Arc<Memory<RawBuffer>>)> { ) -> Result<(VkImage, Memory<'a, RawBuffer>)> {
let image = Self::create_image(device, image_ci)?; let image = Self::create_image(device, image_ci)?;
let memory = Memory::image_memory( let memory = Memory::image_memory(
device, device,
@ -439,7 +439,7 @@ impl ImageBuilder {
Ok((image, memory)) Ok((image, memory))
} }
fn create_image(device: &Arc<Device>, image_ci: &VkImageCreateInfo) -> Result<VkImage> { fn create_image(device: &Device, image_ci: &VkImageCreateInfo) -> Result<VkImage> {
debug_assert_ne!(image_ci.extent.width, 0); debug_assert_ne!(image_ci.extent.width, 0);
debug_assert_ne!(image_ci.extent.height, 0); debug_assert_ne!(image_ci.extent.height, 0);
@ -447,18 +447,18 @@ impl ImageBuilder {
} }
fn optimize_fill( fn optimize_fill(
device: &Arc<Device>, device: &Device,
queue: &Arc<Mutex<Queue>>, queue: &Mutex<Queue<'a>>,
data: &[RawBuffer], data: &[RawBuffer],
image: &Arc<Image>, image: &Image<'a>,
) -> Result<()> { ) -> Result<()> {
let staging_buffer = Buffer::builder() let staging_buffer = Buffer::builder()
.set_usage(VK_BUFFER_USAGE_TRANSFER_SRC_BIT) .set_usage(VK_BUFFER_USAGE_TRANSFER_SRC_BIT)
.set_memory_usage(MemoryUsage::CpuToGpu) .set_memory_usage(MemoryUsage::CpuToGpu)
.set_data(data) .set_data(data)
.build(device.clone())?; .build(device)?;
copy_buffer_to_image(device, queue, &staging_buffer, image)?; copy_buffer_to_image(image, device, queue, &staging_buffer)?;
Ok(()) Ok(())
} }
@ -469,12 +469,12 @@ impl ImageBuilder {
/// handles VkImage, VkSampler, VkDeviceSize and VkImageView internally /// handles VkImage, VkSampler, VkDeviceSize and VkImageView internally
/// just as you set it up to /// just as you set it up to
#[derive(Debug)] #[derive(Debug)]
pub struct Image { pub struct Image<'a> {
// device handle // device handle
device: Arc<Device>, device: &'a Device,
// queue handle // queue handle
queue: Arc<Mutex<Queue>>, queue: &'a Mutex<Queue<'a>>,
file_name: Option<AssetPath>, file_name: Option<AssetPath>,
@ -486,8 +486,8 @@ pub struct Image {
image_view: VkImageView, image_view: VkImageView,
// optional handles // optional handles
_memory: Option<Arc<Memory<RawBuffer>>>, _memory: Option<Memory<'a, RawBuffer>>,
sampler: Option<Arc<Sampler>>, sampler: Option<Sampler>,
// image information // image information
format: VkFormat, format: VkFormat,
@ -502,7 +502,7 @@ pub struct Image {
usage: VkImageUsageFlagBits, usage: VkImageUsageFlagBits,
} }
impl Image { impl<'a> Image<'a> {
/// Creates an `ImageBuilder` where you can define the image for your needs /// Creates an `ImageBuilder` where you can define the image for your needs
/// ///
/// For example, this is used to wrap swapchain images /// For example, this is used to wrap swapchain images
@ -519,7 +519,7 @@ impl Image {
layout: VkImageLayout, layout: VkImageLayout,
usage: impl Into<VkImageUsageFlagBits>, usage: impl Into<VkImageUsageFlagBits>,
assume_layout: bool, assume_layout: bool,
) -> ImageBuilder { ) -> ImageBuilder<'a> {
ImageBuilder::new(ImageBuilderInternalType::PreinitializedImage( ImageBuilder::new(ImageBuilderInternalType::PreinitializedImage(
PreinitializedImage { PreinitializedImage {
image, image,
@ -545,7 +545,7 @@ impl Image {
/// * `source` - The color information for the image /// * `source` - The color information for the image
/// * `width` - The target width of the image /// * `width` - The target width of the image
/// * `height` - The target height of the image /// * `height` - The target height of the image
pub fn from_raw(source: Vec<u8>, width: u32, height: u32) -> ImageBuilder { pub fn from_raw(source: Vec<u8>, width: u32, height: u32) -> ImageBuilder<'a> {
let mut create_info = ImageCreateInfo::default(ImageSourceType::Raw(source)); let mut create_info = ImageCreateInfo::default(ImageSourceType::Raw(source));
create_info.vk_image_create_info.extent.width = width; create_info.vk_image_create_info.extent.width = width;
create_info.vk_image_create_info.extent.height = height; create_info.vk_image_create_info.extent.height = height;
@ -563,7 +563,7 @@ impl Image {
/// # Arguments /// # Arguments
/// ///
/// * `file` - The path to the file /// * `file` - The path to the file
pub fn from_file(file: AssetPath) -> Result<ImageBuilder> { pub fn from_file(file: AssetPath) -> Result<ImageBuilder<'a>> {
let texture = match image::open(&file.full_path()) { let texture = match image::open(&file.full_path()) {
Ok(i) => i.to_rgba8(), Ok(i) => i.to_rgba8(),
Err(err) => return Err(anyhow::Error::new(err).context(file.full_path())), Err(err) => return Err(anyhow::Error::new(err).context(file.full_path())),
@ -591,7 +591,7 @@ impl Image {
/// # Arguments /// # Arguments
/// ///
/// * `slice` - Slice of bytes /// * `slice` - Slice of bytes
pub fn from_slice(data: &[u8]) -> Result<ImageBuilder> { pub fn from_slice(data: &[u8]) -> Result<ImageBuilder<'a>> {
let texture = image::load_from_memory(data)?.to_rgba8(); let texture = image::load_from_memory(data)?.to_rgba8();
let (width, height) = texture.dimensions(); let (width, height) = texture.dimensions();
@ -607,7 +607,7 @@ impl Image {
/// # Arguments /// # Arguments
/// ///
/// * `array` - Source images /// * `array` - Source images
pub fn from_array(array: Vec<Arc<Image>>) -> ImageBuilder { pub fn from_array(array: Vec<Image<'a>>) -> ImageBuilder<'a> {
debug_assert!(array.is_empty(), "images array must not be empty"); debug_assert!(array.is_empty(), "images array must not be empty");
let width = array[0].width(); let width = array[0].width();
@ -652,7 +652,7 @@ impl Image {
height: u32, height: u32,
usage: impl Into<VkImageUsageFlagBits>, usage: impl Into<VkImageUsageFlagBits>,
sample_count: VkSampleCountFlags, sample_count: VkSampleCountFlags,
) -> ImageBuilder { ) -> ImageBuilder<'a> {
let mut create_info = ImageCreateInfo::default(ImageSourceType::Empty); let mut create_info = ImageCreateInfo::default(ImageSourceType::Empty);
create_info.vk_image_create_info.samples = sample_count.into(); create_info.vk_image_create_info.samples = sample_count.into();
create_info.vk_image_create_info.extent.width = width; create_info.vk_image_create_info.extent.width = width;
@ -664,7 +664,7 @@ impl Image {
} }
pub fn check_configuration( pub fn check_configuration(
device: &Arc<Device>, device: &Device,
tiling: VkImageTiling, tiling: VkImageTiling,
format: VkFormat, format: VkFormat,
usage: impl Into<VkImageUsageFlagBits>, usage: impl Into<VkImageUsageFlagBits>,
@ -677,11 +677,11 @@ impl Image {
} }
} }
pub fn device(&self) -> &Arc<Device> { pub fn device(&self) -> &Device {
&self.device &self.device
} }
pub fn queue(&self) -> &Arc<Mutex<Queue>> { pub fn queue(&self) -> &Mutex<Queue<'a>> {
&self.queue &self.queue
} }
@ -689,7 +689,7 @@ impl Image {
self.file_name.as_ref() self.file_name.as_ref()
} }
pub fn convert_layout(self: &Arc<Self>, target_layout: VkImageLayout) -> Result<()> { pub fn convert_layout(&self, target_layout: VkImageLayout) -> Result<()> {
into_layout(self, target_layout) into_layout(self, target_layout)
} }
@ -697,7 +697,7 @@ impl Image {
self.format self.format
} }
pub fn sampler(&self) -> &Option<Arc<Sampler>> { pub fn sampler(&self) -> &Option<Sampler> {
&self.sampler &self.sampler
} }
@ -788,7 +788,7 @@ impl Image {
} }
} }
pub fn to_file(self: &Arc<Image>, path: impl AsRef<Path>) -> Result<()> { pub fn to_file(&self, path: impl AsRef<Path>) -> Result<()> {
// check if image is created with correct usage flag that allows transfering data from it // check if image is created with correct usage flag that allows transfering data from it
if (self.usage | VK_IMAGE_USAGE_TRANSFER_SRC_BIT) == 0 { if (self.usage | VK_IMAGE_USAGE_TRANSFER_SRC_BIT) == 0 {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!(
@ -815,9 +815,9 @@ impl Image {
} }
pub fn copy_image_to_buffer( pub fn copy_image_to_buffer(
self: &Arc<Image>, &self,
extra_buffer_flags: impl Into<Option<VkBufferUsageFlagBits>>, extra_buffer_flags: impl Into<Option<VkBufferUsageFlagBits>>,
) -> Result<Arc<Buffer<RawBuffer>>> { ) -> Result<Buffer<'a, RawBuffer>> {
let usage = match extra_buffer_flags.into() { let usage = match extra_buffer_flags.into() {
Some(flags) => VK_BUFFER_USAGE_TRANSFER_DST_BIT | flags, Some(flags) => VK_BUFFER_USAGE_TRANSFER_DST_BIT | flags,
None => VK_BUFFER_USAGE_TRANSFER_DST_BIT.into(), None => VK_BUFFER_USAGE_TRANSFER_DST_BIT.into(),
@ -885,13 +885,13 @@ impl Image {
Ok(buffer) Ok(buffer)
} }
pub fn copy_buffer_to_image(self: &Arc<Image>, buffer: &Arc<Buffer<RawBuffer>>) -> Result<()> { pub fn copy_buffer_to_image(&self, buffer: &Arc<Buffer<'a, RawBuffer>>) -> Result<()> {
copy_buffer_to_image(&self.device, &self.queue, &buffer, self) copy_buffer_to_image(self, &self.device, &self.queue, &buffer)
} }
} }
impl VulkanDevice for Image { impl<'a> VulkanDevice for Image<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
@ -899,7 +899,7 @@ impl VulkanDevice for Image {
impl_vk_handle!(Image, VkImage, image); impl_vk_handle!(Image, VkImage, image);
impl_vk_handle!(Image, VkImageView, image_view); impl_vk_handle!(Image, VkImageView, image_view);
impl Drop for Image { impl<'a> Drop for Image<'a> {
fn drop(&mut self) { fn drop(&mut self) {
self.device.destroy_image_view(self.image_view); self.device.destroy_image_view(self.image_view);
@ -909,10 +909,9 @@ impl Drop for Image {
} }
} }
fn into_layout(image: &Arc<Image>, layout: VkImageLayout) -> Result<()> { fn into_layout<'a>(image: &Image<'a>, layout: VkImageLayout) -> Result<()> {
// create a new command buffer // create a new command buffer
let command_buffer = let command_buffer = CommandBuffer::new_primary().build(image.device, image.queue)?;
CommandBuffer::new_primary().build(image.device.clone(), image.queue.clone())?;
{ {
// begin recording into this command buffer // begin recording into this command buffer
@ -950,11 +949,11 @@ fn into_layout(image: &Arc<Image>, layout: VkImageLayout) -> Result<()> {
Ok(()) Ok(())
} }
fn copy_buffer_to_image<T: ReprC + Send + Sync + 'static>( fn copy_buffer_to_image<'a, T: ReprC + Send + Sync + 'static>(
device: &Arc<Device>, image: &Image<'a>,
queue: &Arc<Mutex<Queue>>, device: &Device,
buffer: &Arc<Buffer<T>>, queue: &Mutex<Queue<'a>>,
image: &Arc<Image>, buffer: &Buffer<'a, T>,
) -> Result<()> ) -> Result<()>
where where
T: Copy, T: Copy,
@ -1045,11 +1044,11 @@ where
Ok(()) Ok(())
} }
fn copy_images_to_imagearray( fn copy_images_to_imagearray<'a>(
device: &Arc<Device>, device: &Device,
queue: &Arc<Mutex<Queue>>, queue: &Mutex<Queue<'a>>,
image_array: &Arc<Image>, image_array: &Image<'a>,
images: &[Arc<Image>], images: &[Image<'a>],
) -> Result<()> { ) -> Result<()> {
// create a new command buffer // create a new command buffer
let command_buffer = CommandBuffer::new_primary().build(device.clone(), queue.clone())?; let command_buffer = CommandBuffer::new_primary().build(device.clone(), queue.clone())?;
@ -1119,10 +1118,10 @@ fn copy_images_to_imagearray(
Ok(()) Ok(())
} }
fn copy_image_to_image( fn copy_image_to_image<'a>(
buffer_recorder: &mut CommandBufferRecorder<'_>, buffer_recorder: &mut CommandBufferRecorder<'_>,
src_image: &Arc<Image>, src_image: &Image<'a>,
dst_image: &Arc<Image>, dst_image: &Image<'a>,
mip_level: u32, mip_level: u32,
dst_layer: u32, dst_layer: u32,
) { ) {
@ -1181,9 +1180,9 @@ fn copy_image_to_image(
); );
} }
fn blit_mip_maps( fn blit_mip_maps<'a>(
buffer_recorder: &mut CommandBufferRecorder<'_>, buffer_recorder: &mut CommandBufferRecorder<'_>,
image: &Arc<Image>, image: &Image<'a>,
target_image_layout: VkImageLayout, target_image_layout: VkImageLayout,
) { ) {
let mut mip_width = image.width(); let mut mip_width = image.width();

View file

@ -6,7 +6,6 @@ use std::collections::HashSet;
use std::fmt; use std::fmt;
use std::mem::MaybeUninit; use std::mem::MaybeUninit;
use std::ptr; use std::ptr;
use std::sync::Arc;
use std::os::raw::c_char; use std::os::raw::c_char;
use std::os::raw::c_void; use std::os::raw::c_void;
@ -104,7 +103,7 @@ impl Instance {
proc_addr: PFN_vkGetInstanceProcAddr, proc_addr: PFN_vkGetInstanceProcAddr,
extensions: &[VkString], extensions: &[VkString],
api_version: Option<u32>, api_version: Option<u32>,
) -> Result<Arc<Instance>> { ) -> Result<Instance> {
let static_functions = StaticFunctions { let static_functions = StaticFunctions {
_lib: None, _lib: None,
vkGetInstanceProcAddr: proc_addr, vkGetInstanceProcAddr: proc_addr,
@ -122,7 +121,7 @@ impl Instance {
let instance_extensions = InstanceExtensions::from_list(extensions); let instance_extensions = InstanceExtensions::from_list(extensions);
let instance = Arc::new(Instance { let instance = Instance {
_static_functions: static_functions, _static_functions: static_functions,
_entry_functions: None, _entry_functions: None,
instance_functions, instance_functions,
@ -138,7 +137,7 @@ impl Instance {
debug_report: None, debug_report: None,
api_version: api_version.unwrap_or(VK_MAKE_VERSION(1, 0, 0)), api_version: api_version.unwrap_or(VK_MAKE_VERSION(1, 0, 0)),
}); };
Ok(instance) Ok(instance)
} }
@ -147,7 +146,7 @@ impl Instance {
app_info: VkApplicationInfo<'_>, app_info: VkApplicationInfo<'_>,
debug_info: VulkanDebugInfo, debug_info: VulkanDebugInfo,
mut extensions: InstanceExtensions, mut extensions: InstanceExtensions,
) -> Result<Arc<Instance>> { ) -> Result<Instance> {
// required in physical device // required in physical device
extensions.physical_device_properties2 = true; extensions.physical_device_properties2 = true;
@ -267,7 +266,7 @@ impl Instance {
} }
} }
Ok(Arc::new(instance)) Ok(instance)
} }
pub(crate) fn api_version(&self) -> u32 { pub(crate) fn api_version(&self) -> u32 {

View file

@ -39,8 +39,6 @@ pub mod shadermodule;
pub mod surface; pub mod surface;
pub mod swapchain; pub mod swapchain;
pub mod ffi;
mod sampler_manager; mod sampler_manager;
mod single_submit; mod single_submit;
@ -56,13 +54,11 @@ pub trait VkHandle<T> {
} }
pub trait VulkanDevice { pub trait VulkanDevice {
fn device(&self) -> &std::sync::Arc<device::Device>; fn device(&self) -> &device::Device;
} }
pub fn create_vk_handles() -> anyhow::Result<( pub fn create_vk_handles<'a>(
std::sync::Arc<prelude::Device>, ) -> anyhow::Result<(prelude::Device, std::sync::Mutex<prelude::Queue<'a>>)> {
std::sync::Arc<std::sync::Mutex<prelude::Queue>>,
)> {
use crate::prelude::*; use crate::prelude::*;
let instance = Instance::new( let instance = Instance::new(

View file

@ -1,49 +1,25 @@
macro_rules! impl_vk_handle { macro_rules! impl_vk_handle {
($struct_name:ident $(<$( $const:ident $name:ident: $type:ident, )*>)?, $target_name:ident, $value:ident) => { ($struct_name:ident $(<$( $lt:lifetime $(,)? )* $( $const:ident $name:ident: $type:ident, )*>)?, $target_name:ident, $value:ident) => {
impl$(<$( $const $name: $type, )*>)? VkHandle<$target_name> for $struct_name$(<$($name,)?>)? { impl$(<$( $const $name: $type, )*>)? VkHandle<$target_name> for $struct_name$(<$($lt, )* $($name,)?>)? {
fn vk_handle(&self) -> $target_name { fn vk_handle(&self) -> $target_name {
self.$value self.$value
} }
} }
impl<'a $($(, $const $name: $type)*)?> VkHandle<$target_name> for &'a $struct_name$(<$($name,)?>)? { impl<'x $($(, $const $name: $type)*)?> VkHandle<$target_name> for &'x $struct_name$(<$($lt, )* $($name,)?>)? {
fn vk_handle(&self) -> $target_name {
self.$value
}
}
impl$(<$( $const $name: $type, )*>)? VkHandle<$target_name> for Arc<$struct_name$(<$($name,)?>)?> {
fn vk_handle(&self) -> $target_name {
self.$value
}
}
impl<'a $($(, $const $name: $type)*)?> VkHandle<$target_name> for &'a Arc<$struct_name$(<$($name,)?>)?> {
fn vk_handle(&self) -> $target_name { fn vk_handle(&self) -> $target_name {
self.$value self.$value
} }
} }
}; };
($struct_name:ident $(<$( $name:ident: $type:ident, )*>)?, $target_name:ident, $value:ident) => { ($struct_name:ident $(<$( $lt:lifetime $(,)? )* $( $name:ident: $type:ident, )*>)?, $target_name:ident, $value:ident) => {
impl$(<$( $name: $type, )*>)? VkHandle<$target_name> for $struct_name$(<$($name,)?>)? { impl$(<$( $lt, )* $( $name: $type, )*>)? VkHandle<$target_name> for $struct_name$(<$($lt, )* $($name,)?>)? {
fn vk_handle(&self) -> $target_name { fn vk_handle(&self) -> $target_name {
self.$value self.$value
} }
} }
impl<'a $($(, $name: $type)*)?> VkHandle<$target_name> for &'a $struct_name$(<$($name,)?>)? { impl<'x $($(, $lt, )* $(, $name: $type)*)?> VkHandle<$target_name> for &'x $struct_name$(<$($lt, )* $($name,)?>)? {
fn vk_handle(&self) -> $target_name {
self.$value
}
}
impl$(<$( $name: $type, )*>)? VkHandle<$target_name> for Arc<$struct_name$(<$($name,)?>)?> {
fn vk_handle(&self) -> $target_name {
self.$value
}
}
impl<'a $($(, $name: $type)*)?> VkHandle<$target_name> for &'a Arc<$struct_name$(<$($name,)?>)?> {
fn vk_handle(&self) -> $target_name { fn vk_handle(&self) -> $target_name {
self.$value self.$value
} }
@ -64,18 +40,6 @@ macro_rules! impl_vk_handle_t {
self.$value self.$value
} }
} }
impl<T $(: $($t,)* )?> VkHandle<$target_name> for Arc<$struct_name<T>> {
fn vk_handle(&self) -> $target_name {
self.$value
}
}
impl<'a, T $(: $($t,)* )?> VkHandle<$target_name> for &'a Arc<$struct_name<T>> {
fn vk_handle(&self) -> $target_name {
self.$value
}
}
}; };
} }

View file

@ -6,7 +6,6 @@ use utilities::impl_reprc;
use vma_rs::prelude::*; use vma_rs::prelude::*;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::sync::Arc;
impl_reprc!( impl_reprc!(
#[derive(Debug, Copy)] #[derive(Debug, Copy)]
@ -45,45 +44,42 @@ impl Into<VmaMemoryUsage> for MemoryUsage {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Memory<T: ReprC> { pub struct Memory<'a, T: ReprC> {
device: Arc<Device>, device: &'a Device,
allocation: Allocation, allocation: Allocation,
data_type: PhantomData<T>, data_type: PhantomData<T>,
} }
impl<T: ReprC> Memory<T> { impl<'a, T: ReprC> Memory<'a, T> {
pub(crate) fn forced_requirements( pub(crate) fn forced_requirements(
device: &Arc<Device>, device: &'a Device,
memory_requirements: VkMemoryRequirements, memory_requirements: VkMemoryRequirements,
buffer: VkBuffer, buffer: VkBuffer,
memory_usage: VmaMemoryUsage, memory_usage: VmaMemoryUsage,
) -> Result<Arc<Memory<T>>> { ) -> Result<Memory<'a, T>> {
let mut memory = Self::create_and_bind(device, memory_requirements, memory_usage, ())?; let mut memory = Self::create_and_bind(device, memory_requirements, memory_usage, ())?;
memory.allocation.bind_buffer_memory(buffer)?;
if let Some(mut_memory) = Arc::get_mut(&mut memory) {
mut_memory.allocation.bind_buffer_memory(buffer)?;
}
Ok(memory) Ok(memory)
} }
pub(crate) fn buffer_memory( pub(crate) fn buffer_memory(
device: &Arc<Device>, device: &'a Device,
buffer: VkBuffer, buffer: VkBuffer,
memory_usage: VmaMemoryUsage, memory_usage: VmaMemoryUsage,
) -> Result<Arc<Memory<T>>> { ) -> Result<Memory<'a, T>> {
let memory_requirements = device.buffer_memory_requirements(buffer); let memory_requirements = device.buffer_memory_requirements(buffer);
Self::create_and_bind(device, memory_requirements, memory_usage, buffer) Self::create_and_bind(device, memory_requirements, memory_usage, buffer)
} }
pub(crate) fn image_memory( pub(crate) fn image_memory(
device: &Arc<Device>, device: &Device,
image: VkImage, image: VkImage,
memory_usage: VmaMemoryUsage, memory_usage: VmaMemoryUsage,
) -> Result<Arc<Memory<T>>> { ) -> Result<Memory<'a, T>> {
let memory_requirements = device.image_memory_requirements(image); let memory_requirements = device.image_memory_requirements(image);
Self::create_and_bind(device, memory_requirements, memory_usage, image) Self::create_and_bind(device, memory_requirements, memory_usage, image)
@ -94,22 +90,22 @@ impl<T: ReprC> Memory<T> {
} }
} }
trait MemoryBinder<T, K: ReprC> { trait MemoryBinder<'a, T, K: ReprC> {
fn create_and_bind( fn create_and_bind(
device: &Arc<Device>, device: &Device,
memory_requirements: VkMemoryRequirements, memory_requirements: VkMemoryRequirements,
memory_usage: VmaMemoryUsage, memory_usage: VmaMemoryUsage,
argument: T, argument: T,
) -> Result<Arc<Memory<K>>>; ) -> Result<Memory<'a, K>>;
} }
impl<K: ReprC> MemoryBinder<(), K> for Memory<K> { impl<'a, K: ReprC> MemoryBinder<'a, (), K> for Memory<'a, K> {
fn create_and_bind( fn create_and_bind(
device: &Arc<Device>, device: &Device,
memory_requirements: VkMemoryRequirements, memory_requirements: VkMemoryRequirements,
memory_usage: VmaMemoryUsage, memory_usage: VmaMemoryUsage,
_: (), _: (),
) -> Result<Arc<Memory<K>>> { ) -> Result<Memory<'a, K>> {
let allocation = device let allocation = device
.allocator() .allocator()
.allocate() .allocate()
@ -117,23 +113,23 @@ impl<K: ReprC> MemoryBinder<(), K> for Memory<K> {
.set_memory_type_bits(memory_requirements.memoryTypeBits.into()) .set_memory_type_bits(memory_requirements.memoryTypeBits.into())
.build(&memory_requirements)?; .build(&memory_requirements)?;
Ok(Arc::new(Memory { Ok(Memory {
device: device.clone(), device,
allocation, allocation,
data_type: PhantomData, data_type: PhantomData,
})) })
} }
} }
impl<K: ReprC> MemoryBinder<VkImage, K> for Memory<K> { impl<'a, K: ReprC> MemoryBinder<'a, VkImage, K> for Memory<'a, K> {
fn create_and_bind( fn create_and_bind(
device: &Arc<Device>, device: &Device,
memory_requirements: VkMemoryRequirements, memory_requirements: VkMemoryRequirements,
memory_usage: VmaMemoryUsage, memory_usage: VmaMemoryUsage,
image: VkImage, image: VkImage,
) -> Result<Arc<Memory<K>>> { ) -> Result<Memory<'a, K>> {
let allocation = device let allocation = device
.allocator() .allocator()
.allocate() .allocate()
@ -141,23 +137,23 @@ impl<K: ReprC> MemoryBinder<VkImage, K> for Memory<K> {
.set_memory_type_bits(memory_requirements.memoryTypeBits.into()) .set_memory_type_bits(memory_requirements.memoryTypeBits.into())
.build(image)?; .build(image)?;
Ok(Arc::new(Memory { Ok(Memory {
device: device.clone(), device,
allocation, allocation,
data_type: PhantomData, data_type: PhantomData,
})) })
} }
} }
impl<K: ReprC> MemoryBinder<VkBuffer, K> for Memory<K> { impl<'a, K: ReprC> MemoryBinder<'a, VkBuffer, K> for Memory<'a, K> {
fn create_and_bind( fn create_and_bind(
device: &Arc<Device>, device: &Device,
memory_requirements: VkMemoryRequirements, memory_requirements: VkMemoryRequirements,
memory_usage: VmaMemoryUsage, memory_usage: VmaMemoryUsage,
buffer: VkBuffer, buffer: VkBuffer,
) -> Result<Arc<Memory<K>>> { ) -> Result<Memory<'a, K>> {
let allocation = device let allocation = device
.allocator() .allocator()
.allocate() .allocate()
@ -165,23 +161,23 @@ impl<K: ReprC> MemoryBinder<VkBuffer, K> for Memory<K> {
.set_memory_type_bits(memory_requirements.memoryTypeBits.into()) .set_memory_type_bits(memory_requirements.memoryTypeBits.into())
.build(buffer)?; .build(buffer)?;
Ok(Arc::new(Memory { Ok(Memory {
device: device.clone(), device,
allocation, allocation,
data_type: PhantomData, data_type: PhantomData,
})) })
} }
} }
impl<T: ReprC> VulkanDevice for Memory<T> { impl<'a, T: ReprC> VulkanDevice for Memory<'a, T> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl<T: ReprC + Clone> Memory<T> { impl<'a, T: ReprC + Clone> Memory<'a, T> {
pub fn map(&self, length: VkDeviceSize) -> Result<VkMappedMemory<'_, T>> { pub fn map(&self, length: VkDeviceSize) -> Result<VkMappedMemory<'_, T>> {
self.allocation.map(length) self.allocation.map(length)
} }

View file

@ -2,11 +2,11 @@ use crate::prelude::*;
use anyhow::Result; use anyhow::Result;
use std::{ptr, sync::Arc}; use std::ptr;
#[derive(Debug)] #[derive(Debug)]
pub struct PhysicalDevice { pub struct PhysicalDevice {
instance: Arc<Instance>, instance: Instance,
physical_device: VkPhysicalDevice, physical_device: VkPhysicalDevice,
properties: VkPhysicalDeviceProperties, properties: VkPhysicalDeviceProperties,
features: VkPhysicalDeviceFeatures, features: VkPhysicalDeviceFeatures,
@ -26,7 +26,7 @@ pub struct PhysicalDevice {
} }
impl PhysicalDevice { impl PhysicalDevice {
pub fn new(instance: Arc<Instance>) -> Result<Arc<PhysicalDevice>> { pub fn new(instance: Instance) -> Result<PhysicalDevice> {
let physical_devices = instance.enumerate_physical_devices()?; let physical_devices = instance.enumerate_physical_devices()?;
let (mut physical_device, mut device_properties) = PhysicalDevice::find_phys_dev( let (mut physical_device, mut device_properties) = PhysicalDevice::find_phys_dev(
@ -57,19 +57,19 @@ impl PhysicalDevice {
} }
pub fn from_raw( pub fn from_raw(
instance: Arc<Instance>, instance: Instance,
physical_device: VkPhysicalDevice, physical_device: VkPhysicalDevice,
) -> Result<Arc<PhysicalDevice>> { ) -> Result<PhysicalDevice> {
let properties = instance.physical_device_properties(physical_device); let properties = instance.physical_device_properties(physical_device);
Self::internal_new(instance, physical_device, properties) Self::internal_new(instance, physical_device, properties)
} }
fn internal_new( fn internal_new(
instance: Arc<Instance>, instance: Instance,
physical_device: VkPhysicalDevice, physical_device: VkPhysicalDevice,
properties: VkPhysicalDeviceProperties, properties: VkPhysicalDeviceProperties,
) -> Result<Arc<PhysicalDevice>> { ) -> Result<PhysicalDevice> {
let device_features = instance.physical_device_features(physical_device); let device_features = instance.physical_device_features(physical_device);
let device_memory_properties = instance.physical_device_memory_properties(physical_device); let device_memory_properties = instance.physical_device_memory_properties(physical_device);
@ -134,7 +134,7 @@ impl PhysicalDevice {
patch patch
); );
Ok(Arc::new(PhysicalDevice { Ok(PhysicalDevice {
instance, instance,
physical_device, physical_device,
properties, properties,
@ -151,13 +151,13 @@ impl PhysicalDevice {
descriptor_indexing_features, descriptor_indexing_features,
buffer_device_address_features, buffer_device_address_features,
})) })
} }
} }
// getter // getter
impl PhysicalDevice { impl PhysicalDevice {
pub fn instance(&self) -> &Arc<Instance> { pub fn instance(&self) -> &Instance {
&self.instance &self.instance
} }
@ -305,7 +305,7 @@ impl_vk_handle!(PhysicalDevice, VkPhysicalDevice, physical_device);
// private // private
impl PhysicalDevice { impl PhysicalDevice {
fn find_phys_dev( fn find_phys_dev(
instance: &Arc<Instance>, instance: &Instance,
physical_devices: &[VkPhysicalDevice], physical_devices: &[VkPhysicalDevice],
device_type: VkPhysicalDeviceType, device_type: VkPhysicalDeviceType,
) -> (Option<VkPhysicalDevice>, Option<VkPhysicalDeviceProperties>) { ) -> (Option<VkPhysicalDevice>, Option<VkPhysicalDeviceProperties>) {
@ -321,7 +321,7 @@ impl PhysicalDevice {
} }
fn query_extensions( fn query_extensions(
instance: &Arc<Instance>, instance: &Instance,
physical_device: VkPhysicalDevice, physical_device: VkPhysicalDevice,
) -> Result<Vec<VkString>> { ) -> Result<Vec<VkString>> {
let extensions = instance.enumerate_device_extensions(physical_device)?; let extensions = instance.enumerate_device_extensions(physical_device)?;

View file

@ -84,7 +84,7 @@ impl Pipeline {
} }
impl VulkanDevice for Pipeline { impl VulkanDevice for Pipeline {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }

View file

@ -38,7 +38,7 @@ impl PipelineCache {
} }
impl VulkanDevice for PipelineCache { impl VulkanDevice for PipelineCache {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }

View file

@ -59,7 +59,7 @@ impl PipelineLayout {
} }
impl VulkanDevice for PipelineLayout { impl VulkanDevice for PipelineLayout {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }

View file

@ -245,7 +245,7 @@ impl<'a> RayTracingPipelineBuilder<'a> {
mut self, mut self,
device: Arc<Device>, device: Arc<Device>,
pipeline_layout: &Arc<PipelineLayout>, pipeline_layout: &Arc<PipelineLayout>,
) -> Result<(Arc<Pipeline>, ShaderBindingTable)> { ) -> Result<(Arc<Pipeline>, ShaderBindingTable<'a>)> {
let shader_stages: Vec<VkPipelineShaderStageCreateInfo> = self let shader_stages: Vec<VkPipelineShaderStageCreateInfo> = self
.shader_modules .shader_modules
.iter() .iter()

View file

@ -14,8 +14,8 @@ pub(crate) struct ShaderBindingTableBuilder {
hit_group_entries: Vec<ShaderBindingTableEntry>, hit_group_entries: Vec<ShaderBindingTableEntry>,
} }
pub struct ShaderBindingTable { pub struct ShaderBindingTable<'a> {
_sbt_buffer: Arc<Buffer<RawBuffer>>, _sbt_buffer: Buffer<'a, RawBuffer>,
raygen_shader_binding_table: VkStridedDeviceAddressRegionKHR, raygen_shader_binding_table: VkStridedDeviceAddressRegionKHR,
miss_shader_binding_table: VkStridedDeviceAddressRegionKHR, miss_shader_binding_table: VkStridedDeviceAddressRegionKHR,
@ -23,7 +23,7 @@ pub struct ShaderBindingTable {
callable_shader_binding_table: VkStridedDeviceAddressRegionKHR, callable_shader_binding_table: VkStridedDeviceAddressRegionKHR,
} }
impl ShaderBindingTable { impl<'a> ShaderBindingTable<'a> {
pub fn raygen_shader_binding_table(&self) -> &VkStridedDeviceAddressRegionKHR { pub fn raygen_shader_binding_table(&self) -> &VkStridedDeviceAddressRegionKHR {
&self.raygen_shader_binding_table &self.raygen_shader_binding_table
} }
@ -41,7 +41,7 @@ impl ShaderBindingTable {
} }
fn create( fn create(
sbt_buffer: Arc<Buffer<RawBuffer>>, sbt_buffer: Buffer<'a, RawBuffer>,
ray_gen_entry_size: VkDeviceSize, ray_gen_entry_size: VkDeviceSize,
ray_gen_entry_count: VkDeviceSize, ray_gen_entry_count: VkDeviceSize,
miss_offset: VkDeviceSize, miss_offset: VkDeviceSize,
@ -128,11 +128,11 @@ impl ShaderBindingTableBuilder {
self self
} }
pub(crate) fn build( pub(crate) fn build<'a>(
&mut self, &mut self,
device: &Arc<Device>, device: &Arc<Device>,
pipeline: &Arc<Pipeline>, pipeline: &Arc<Pipeline>,
) -> Result<ShaderBindingTable> { ) -> Result<ShaderBindingTable<'a>> {
let ray_tracing_properties = device.physical_device().ray_tracing_properties(); let ray_tracing_properties = device.physical_device().ray_tracing_properties();
let prog_id_size = ray_tracing_properties.shaderGroupHandleSize; let prog_id_size = ray_tracing_properties.shaderGroupHandleSize;
@ -208,7 +208,7 @@ impl ShaderBindingTableBuilder {
.collect::<Vec<RawBuffer>>() .collect::<Vec<RawBuffer>>()
.as_slice(), .as_slice(),
) )
.build(device.clone())?; .build(device)?;
Ok(ShaderBindingTable::create( Ok(ShaderBindingTable::create(
sbt_buffer, sbt_buffer,

View file

@ -52,7 +52,7 @@ impl QueryPool {
} }
impl VulkanDevice for QueryPool { impl VulkanDevice for QueryPool {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }

View file

@ -15,17 +15,17 @@ pub struct QueueRequestInfo {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Queue { pub struct Queue<'a> {
device: Arc<Device>, device: &'a Device,
queue: VkQueue, queue: VkQueue,
family_index: u32, family_index: u32,
queue_index: u32, queue_index: u32,
} }
impl Queue { impl<'a> Queue<'a> {
pub fn create_presentable_request_info( pub fn create_presentable_request_info<'b>(
physical_device: &Arc<PhysicalDevice>, physical_device: &PhysicalDevice,
surface: &Arc<Surface>, surface: &Surface<'b>,
queue_type: impl Into<VkQueueFlagBits>, queue_type: impl Into<VkQueueFlagBits>,
) -> Result<QueueRequestInfo> { ) -> Result<QueueRequestInfo> {
let index = let index =
@ -41,7 +41,7 @@ impl Queue {
} }
pub fn create_non_presentable_request_info( pub fn create_non_presentable_request_info(
physical_device: &Arc<PhysicalDevice>, physical_device: &PhysicalDevice,
queue_type: impl Into<VkQueueFlagBits>, queue_type: impl Into<VkQueueFlagBits>,
) -> Result<QueueRequestInfo> { ) -> Result<QueueRequestInfo> {
let index = Self::find_non_presentable_queue_index(physical_device, queue_type.into())?; let index = Self::find_non_presentable_queue_index(physical_device, queue_type.into())?;
@ -56,17 +56,17 @@ impl Queue {
} }
pub fn new( pub fn new(
device: Arc<Device>, device: &'a Device,
queue: VkQueue, queue: VkQueue,
family_index: u32, family_index: u32,
queue_index: u32, queue_index: u32,
) -> Arc<Mutex<Queue>> { ) -> Mutex<Queue<'a>> {
Arc::new(Mutex::new(Queue { Mutex::new(Queue {
device, device,
queue, queue,
family_index, family_index,
queue_index, queue_index,
})) })
} }
pub fn family_index(&self) -> u32 { pub fn family_index(&self) -> u32 {
@ -78,7 +78,7 @@ impl Queue {
} }
/// really expensiv call, since its locks the queue until it is idle /// really expensiv call, since its locks the queue until it is idle
pub fn submit(&self, fence: Option<&Arc<Fence>>, submits: &[SubmitInfo]) -> Result<()> { pub fn submit(&self, fence: Option<&Fence<'a>>, submits: &[SubmitInfo]) -> Result<()> {
let submit_infos: Vec<VkSubmitInfo> = submits.iter().map(|s| s.as_vk_submit()).collect(); let submit_infos: Vec<VkSubmitInfo> = submits.iter().map(|s| s.as_vk_submit()).collect();
let fence = match fence { let fence = match fence {
@ -93,7 +93,7 @@ impl Queue {
pub fn minimal_submit( pub fn minimal_submit(
&self, &self,
time_out: Duration, time_out: Duration,
command_buffers: &[Arc<CommandBuffer>], command_buffers: &[Arc<CommandBuffer<'a>>],
) -> Result<()> { ) -> Result<()> {
let mut submit = SubmitInfo::default(); let mut submit = SubmitInfo::default();
@ -101,7 +101,7 @@ impl Queue {
submit = submit.add_command_buffer(command_buffer); submit = submit.add_command_buffer(command_buffer);
} }
let fence = Fence::builder().build(self.device.clone())?; let fence = Fence::builder().build(self.device)?;
self.submit(Some(&fence), slice::from_ref(&submit))?; self.submit(Some(&fence), slice::from_ref(&submit))?;
@ -113,9 +113,9 @@ impl Queue {
pub fn present( pub fn present(
&self, &self,
swapchains: &[&Arc<Swapchain>], swapchains: &[&Swapchain<'a>],
image_indices: &[u32], image_indices: &[u32],
wait_semaphores: &[&Arc<Semaphore>], wait_semaphores: &[&Semaphore<'a>],
) -> Result<OutOfDate<()>> { ) -> Result<OutOfDate<()>> {
let wait_semaphores: Vec<VkSemaphore> = let wait_semaphores: Vec<VkSemaphore> =
wait_semaphores.iter().map(|sem| sem.vk_handle()).collect(); wait_semaphores.iter().map(|sem| sem.vk_handle()).collect();
@ -140,18 +140,18 @@ impl Queue {
} }
} }
impl VulkanDevice for Queue { impl<'a> VulkanDevice for Queue<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl_vk_handle!(Queue, VkQueue, queue); impl_vk_handle!(Queue, VkQueue, queue);
impl Queue { impl<'a> Queue<'a> {
fn find_presentable_queue_index( fn find_presentable_queue_index(
physical_device: &Arc<PhysicalDevice>, physical_device: &PhysicalDevice,
surface: &Arc<Surface>, surface: &Surface<'a>,
flags: VkQueueFlagBits, flags: VkQueueFlagBits,
) -> Result<u32> { ) -> Result<u32> {
let surface = surface.vk_handle(); let surface = surface.vk_handle();
@ -179,7 +179,7 @@ impl Queue {
} }
fn find_non_presentable_queue_index( fn find_non_presentable_queue_index(
physical_device: &Arc<PhysicalDevice>, physical_device: &PhysicalDevice,
flags: VkQueueFlagBits, flags: VkQueueFlagBits,
) -> Result<u32> { ) -> Result<u32> {
let vk_physical_device = physical_device.vk_handle(); let vk_physical_device = physical_device.vk_handle();

View file

@ -9,24 +9,24 @@ pub mod sub_pass;
use sub_pass::{AttachmentInfo, AttachmentInfoUsage, SubPass}; use sub_pass::{AttachmentInfo, AttachmentInfoUsage, SubPass};
pub struct RenderTargetBuilder<'a> { pub struct RenderTargetBuilder<'a> {
old_render_target: Option<&'a RenderTarget>, old_render_target: Option<&'a RenderTarget<'a>>,
sub_passes: Vec<SubPass>, sub_passes: Vec<SubPass<'a>>,
} }
impl<'a> RenderTargetBuilder<'a> { impl<'a> RenderTargetBuilder<'a> {
pub fn add_sub_pass(mut self, sub_pass: SubPass) -> Self { pub fn add_sub_pass(mut self, sub_pass: SubPass<'a>) -> Self {
self.sub_passes.push(sub_pass); self.sub_passes.push(sub_pass);
self self
} }
pub fn preserve_old_render_pass(mut self, render_target: &'a RenderTarget) -> Self { pub fn preserve_old_render_pass(mut self, render_target: &'a RenderTarget<'a>) -> Self {
self.old_render_target = Some(render_target); self.old_render_target = Some(render_target);
self self
} }
pub fn build(self, device: &Arc<Device>) -> Result<RenderTarget> { pub fn build(self, device: &Arc<Device>) -> Result<RenderTarget<'a>> {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
{ {
// sub passes must not be empty // sub passes must not be empty
@ -187,8 +187,8 @@ impl<'a> RenderTargetBuilder<'a> {
fn create_framebuffers( fn create_framebuffers(
render_pass: &Arc<RenderPass>, render_pass: &Arc<RenderPass>,
sub_passes: &[SubPass], sub_passes: &[SubPass<'a>],
) -> Result<Vec<Arc<Framebuffer>>> { ) -> Result<Vec<Framebuffer<'a>>> {
let extent = sub_passes[0].extent(); let extent = sub_passes[0].extent();
(0..Self::max_images(sub_passes)) (0..Self::max_images(sub_passes))
@ -211,7 +211,7 @@ impl<'a> RenderTargetBuilder<'a> {
} }
#[inline] #[inline]
fn max_images(sub_passes: &[SubPass]) -> usize { fn max_images(sub_passes: &[SubPass<'a>]) -> usize {
let mut max_images = 0; let mut max_images = 0;
for sub_pass in sub_passes.iter() { for sub_pass in sub_passes.iter() {
@ -221,7 +221,7 @@ impl<'a> RenderTargetBuilder<'a> {
max_images max_images
} }
fn verify_setups(old_sub_passes: &[SubPass], new_sub_passes: &[SubPass]) -> bool { fn verify_setups(old_sub_passes: &[SubPass<'a>], new_sub_passes: &[SubPass<'a>]) -> bool {
if old_sub_passes.len() != new_sub_passes.len() { if old_sub_passes.len() != new_sub_passes.len() {
return false; return false;
} }
@ -238,7 +238,7 @@ impl<'a> RenderTargetBuilder<'a> {
#[inline] #[inline]
fn map_attachment<'b, F>(&'b self, mut f: F) fn map_attachment<'b, F>(&'b self, mut f: F)
where where
F: FnMut(&'b AttachmentInfo) -> (), F: FnMut(&'b AttachmentInfo<'a>) -> (),
{ {
for sub_pass in self.sub_passes.iter() { for sub_pass in self.sub_passes.iter() {
for attachment in sub_pass.attachments().iter() { for attachment in sub_pass.attachments().iter() {
@ -260,21 +260,21 @@ struct SubPassAttachmentReferences {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct RenderTarget { pub struct RenderTarget<'a> {
render_pass: Arc<RenderPass>, render_pass: Arc<RenderPass>,
framebuffers: Vec<Arc<Framebuffer>>, framebuffers: Vec<Framebuffer<'a>>,
clear_values: Vec<VkClearValue>, clear_values: Vec<VkClearValue>,
extent: VkExtent2D, extent: VkExtent2D,
sub_passes: Vec<SubPass>, sub_passes: Vec<SubPass<'a>>,
current_subpass: AtomicU32, current_subpass: AtomicU32,
framebuffer_index: AtomicUsize, framebuffer_index: AtomicUsize,
} }
impl RenderTarget { impl<'a> RenderTarget<'a> {
pub fn builder<'a>() -> RenderTargetBuilder<'a> { pub fn builder() -> RenderTargetBuilder<'a> {
RenderTargetBuilder { RenderTargetBuilder {
old_render_target: None, old_render_target: None,
sub_passes: Vec::new(), sub_passes: Vec::new(),
@ -285,11 +285,11 @@ impl RenderTarget {
&self.render_pass &self.render_pass
} }
pub fn framebuffer(&self, index: usize) -> &Arc<Framebuffer> { pub fn framebuffer(&self, index: usize) -> &Framebuffer<'a> {
&self.framebuffers[index] &self.framebuffers[index]
} }
pub fn sub_pass(&self, index: usize) -> &SubPass { pub fn sub_pass(&self, index: usize) -> &SubPass<'a> {
&self.sub_passes[index] &self.sub_passes[index]
} }
@ -353,48 +353,14 @@ impl RenderTarget {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use crate::prelude::*; use crate::{create_vk_handles, prelude::*};
use anyhow::Result; use anyhow::Result;
use std::sync::{Arc, Mutex};
fn create_vk_handles() -> Result<(Arc<Device>, Arc<Mutex<Queue>>)> {
let instance = Instance::new(
VkApplicationInfo::new(
&VkString::new("Test"),
1,
&VkString::new("no name"),
1,
VK_MAKE_VERSION(1, 3, 0),
),
VulkanDebugInfo::default(),
InstanceExtensions::default(),
)?;
let physical_device = PhysicalDevice::new(instance)?;
let queue_info = Queue::create_non_presentable_request_info(
&physical_device,
VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_TRANSFER_BIT,
)?;
let device = Device::new(
physical_device,
DeviceExtensions::default(),
&[queue_info.queue_create_info],
DeviceFeatures::default(),
)?;
let queue = device.get_queue(queue_info.queue_family_index, queue_info.queue_index);
Ok((device, queue))
}
#[test] #[test]
fn test_render_target() { fn test_render_target() {
let (device, queue) = create_vk_handles().unwrap(); let (device, queue) = create_vk_handles().unwrap();
let target_images: Vec<Arc<Image>> = (0..2) let target_images: Vec<Image<'_>> = (0..2)
.map(|_| { .map(|_| {
let image = Image::empty( let image = Image::empty(
1920, 1920,
@ -409,7 +375,7 @@ mod test {
Ok(image) Ok(image)
}) })
.collect::<Result<Vec<Arc<Image>>>>() .collect::<Result<Vec<Image<'_>>>>()
.unwrap(); .unwrap();
RenderTarget::builder() RenderTarget::builder()

View file

@ -1,6 +1,6 @@
use crate::prelude::*; use crate::prelude::*;
use anyhow::Result; use anyhow::Result;
use std::sync::{Arc, Mutex}; use std::sync::Mutex;
pub enum ClearValue { pub enum ClearValue {
Color([f32; 4]), Color([f32; 4]),
@ -54,14 +54,14 @@ impl CustomTarget {
} }
} }
fn to_attachment_info( fn to_attachment_info<'a>(
&self, &self,
device: &Arc<Device>, device: &Device,
queue: &Arc<Mutex<Queue>>, queue: &Mutex<Queue<'a>>,
width: u32, width: u32,
height: u32, height: u32,
sample_count: VkSampleCountFlags, sample_count: VkSampleCountFlags,
) -> Result<AttachmentInfo> { ) -> Result<AttachmentInfo<'a>> {
let clear_operation = SubPassBuilder::clear_op(if self.use_as_input { let clear_operation = SubPassBuilder::clear_op(if self.use_as_input {
false false
} else { } else {
@ -168,25 +168,25 @@ impl CustomTarget {
} }
} }
pub enum ResolveTarget { pub enum ResolveTarget<'a> {
CustomTarget(CustomTarget), CustomTarget(CustomTarget),
PreparedTargets((Vec<Arc<Image>>, bool)), PreparedTargets((Vec<&'a Image<'a>>, bool)),
} }
impl From<CustomTarget> for ResolveTarget { impl<'a> From<CustomTarget> for ResolveTarget<'a> {
fn from(custom_target: CustomTarget) -> Self { fn from(custom_target: CustomTarget) -> Self {
Self::CustomTarget(custom_target) Self::CustomTarget(custom_target)
} }
} }
impl From<(Vec<Arc<Image>>, bool)> for ResolveTarget { impl<'a> From<(Vec<&'a Image<'a>>, bool)> for ResolveTarget<'a> {
fn from((prepared_targets, clear_on_load): (Vec<Arc<Image>>, bool)) -> Self { fn from((prepared_targets, clear_on_load): (Vec<&'a Image<'a>>, bool)) -> Self {
Self::PreparedTargets((prepared_targets, clear_on_load)) Self::PreparedTargets((prepared_targets, clear_on_load))
} }
} }
impl<'a> From<(&'a Vec<Arc<Image>>, bool)> for ResolveTarget { impl<'a> From<(&'a Vec<&'a Image<'a>>, bool)> for ResolveTarget<'a> {
fn from((prepared_targets, clear_on_load): (&'a Vec<Arc<Image>>, bool)) -> Self { fn from((prepared_targets, clear_on_load): (&'a Vec<&'a Image<'a>>, bool)) -> Self {
Self::PreparedTargets((prepared_targets.clone(), clear_on_load)) Self::PreparedTargets((prepared_targets.clone(), clear_on_load))
} }
} }
@ -202,15 +202,15 @@ pub struct SubPassBuilder<'a> {
height: u32, height: u32,
sample_count: VkSampleCountFlags, sample_count: VkSampleCountFlags,
queue: Option<Arc<Mutex<Queue>>>, queue: Option<&'a Mutex<Queue<'a>>>,
target_infos: Vec<CustomTarget>, target_infos: Vec<CustomTarget>,
input_info: Option<InputAttachmentInfo>, input_info: Option<InputAttachmentInfo>,
// (images, index, clear_color, clear_on_load) // (images, index, clear_color, clear_on_load)
prepared_targets: Option<(&'a [Arc<Image>], usize, [f32; 4], bool)>, prepared_targets: Option<(&'a [&'a Image<'a>], usize, [f32; 4], bool)>,
resolve_targets: Vec<ResolveTarget>, resolve_targets: Vec<ResolveTarget<'a>>,
output_usage: VkAccessFlagBits, output_usage: VkAccessFlagBits,
} }
@ -242,7 +242,7 @@ impl<'a> SubPassBuilder<'a> {
pub fn set_prepared_targets( pub fn set_prepared_targets(
mut self, mut self,
prepared_targets: &'a [Arc<Image>], prepared_targets: &'a [&'a Image<'a>],
target_index: usize, target_index: usize,
clear_color: impl Into<[f32; 4]>, clear_color: impl Into<[f32; 4]>,
clear_on_load: bool, clear_on_load: bool,
@ -257,19 +257,19 @@ impl<'a> SubPassBuilder<'a> {
self self
} }
pub fn add_resolve_targets(mut self, resolve_target: impl Into<ResolveTarget>) -> Self { pub fn add_resolve_targets(mut self, resolve_target: impl Into<ResolveTarget<'a>>) -> Self {
self.resolve_targets.push(resolve_target.into()); self.resolve_targets.push(resolve_target.into());
self self
} }
pub fn use_queue(mut self, queue: Arc<Mutex<Queue>>) -> Self { pub fn use_queue(mut self, queue: &'a Mutex<Queue<'a>>) -> Self {
self.queue = Some(queue); self.queue = Some(queue);
self self
} }
pub fn build(self, device: &Arc<Device>) -> Result<SubPass> { pub fn build(self, device: &Device) -> Result<SubPass<'a>> {
Ok(SubPass { Ok(SubPass {
extent: VkExtent2D { extent: VkExtent2D {
width: self.width, width: self.width,
@ -284,7 +284,7 @@ impl<'a> SubPassBuilder<'a> {
} }
#[inline] #[inline]
fn create_images(self, device: &Arc<Device>) -> Result<Vec<AttachmentInfo>> { fn create_images(self, device: &Device) -> Result<Vec<AttachmentInfo<'a>>> {
// check for correct sample count // check for correct sample count
let checked_sample_count = device.max_supported_sample_count(self.sample_count); let checked_sample_count = device.max_supported_sample_count(self.sample_count);
@ -405,16 +405,16 @@ pub enum AttachmentInfoUsage {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct AttachmentInfo { pub struct AttachmentInfo<'a> {
images: Vec<Arc<Image>>, images: Vec<&'a Image<'a>>,
pub(crate) clear_value: VkClearValue, pub(crate) clear_value: VkClearValue,
pub(crate) layout: VkImageLayout, pub(crate) layout: VkImageLayout,
pub(crate) description: VkAttachmentDescription, pub(crate) description: VkAttachmentDescription,
pub(crate) usage: AttachmentInfoUsage, pub(crate) usage: AttachmentInfoUsage,
} }
impl AttachmentInfo { impl<'a> AttachmentInfo<'a> {
pub fn image(&self, mut index: usize) -> &Arc<Image> { pub fn image(&self, mut index: usize) -> &Image<'a> {
debug_assert!(!self.images.is_empty()); debug_assert!(!self.images.is_empty());
if index >= self.images.len() { if index >= self.images.len() {
@ -433,17 +433,17 @@ impl AttachmentInfo {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct SubPass { pub struct SubPass<'a> {
extent: VkExtent2D, extent: VkExtent2D,
input_info: Option<InputAttachmentInfo>, input_info: Option<InputAttachmentInfo>,
attachments: Vec<AttachmentInfo>, attachments: Vec<AttachmentInfo<'a>>,
output_usage: VkAccessFlagBits, output_usage: VkAccessFlagBits,
} }
impl SubPass { impl<'a> SubPass<'a> {
pub fn builder<'a>(width: u32, height: u32) -> SubPassBuilder<'a> { pub fn builder(width: u32, height: u32) -> SubPassBuilder<'a> {
SubPassBuilder { SubPassBuilder {
width, width,
height, height,
@ -475,7 +475,7 @@ impl SubPass {
self.extent self.extent
} }
pub fn attachments(&self) -> &[AttachmentInfo] { pub fn attachments(&self) -> &[AttachmentInfo<'a>] {
&self.attachments &self.attachments
} }

View file

@ -34,7 +34,7 @@ impl RenderPass {
} }
impl VulkanDevice for RenderPass { impl VulkanDevice for RenderPass {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }

View file

@ -78,7 +78,7 @@ impl SamplerBuilder {
self self
} }
pub fn build(self, device: &Device) -> Result<Arc<Sampler>> { pub fn build(self, device: &Device) -> Result<Sampler> {
device.create_sampler_from_manager(self.create_info) device.create_sampler_from_manager(self.create_info)
} }
} }

View file

@ -2,48 +2,32 @@ use crate::prelude::*;
use anyhow::Result; use anyhow::Result;
use std::sync::Arc;
#[derive(Debug)] #[derive(Debug)]
pub struct Semaphore { pub struct Semaphore<'a> {
device: Arc<Device>, device: &'a Device,
semaphore: VkSemaphore, semaphore: VkSemaphore,
} }
impl Semaphore { impl<'a> Semaphore<'a> {
pub fn new(device: Arc<Device>) -> Result<Arc<Semaphore>> { pub fn new(device: &'a Device) -> Result<Semaphore<'a>> {
let semaphore_ci = VkSemaphoreCreateInfo::new(VK_SEMAPHORE_CREATE_NULL_BIT); let semaphore_ci = VkSemaphoreCreateInfo::new(VK_SEMAPHORE_CREATE_NULL_BIT);
let semaphore = device.create_semaphore(&semaphore_ci)?; let semaphore = device.create_semaphore(&semaphore_ci)?;
Ok(Arc::new(Semaphore { device, semaphore })) Ok(Semaphore { device, semaphore })
} }
} }
impl VulkanDevice for Semaphore { impl<'a> VulkanDevice for Semaphore<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl_vk_handle!(Semaphore, VkSemaphore, semaphore); impl_vk_handle!(Semaphore, VkSemaphore, semaphore);
impl Drop for Semaphore { impl<'a> Drop for Semaphore<'a> {
fn drop(&mut self) { fn drop(&mut self) {
self.device.destroy_semaphore(self.semaphore); self.device.destroy_semaphore(self.semaphore);
} }
} }
use crate::{ffi::*, handle_ffi_result};
#[no_mangle]
pub extern "C" fn create_semaphore(device: *const Device) -> *const Semaphore {
let device = unsafe { Arc::from_raw(device) };
handle_ffi_result!(Semaphore::new(device))
}
#[no_mangle]
pub extern "C" fn destroy_semaphore(semaphore: *const Semaphore) {
let _semaphore = unsafe { Arc::from_raw(semaphore) };
}

View file

@ -144,7 +144,7 @@ impl_pipeline_stage_info!(ray_generation, RayGeneration);
impl_pipeline_stage_info!(miss, Miss); impl_pipeline_stage_info!(miss, Miss);
impl<ShaderModuleType: ShaderType> VulkanDevice for ShaderModule<ShaderModuleType> { impl<ShaderModuleType: ShaderType> VulkanDevice for ShaderModule<ShaderModuleType> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }

View file

@ -1,15 +1,15 @@
use crate::prelude::*; use crate::prelude::*;
use anyhow::Result; use anyhow::Result;
use std::sync::{Arc, Mutex}; use std::sync::Mutex;
use std::time::Duration; use std::time::Duration;
pub struct SingleSubmit<'a, F, T> pub struct SingleSubmit<'a, F, T>
where where
F: FnOnce(&mut CommandBufferRecorder<'_>) -> Result<T>, F: FnOnce(&mut CommandBufferRecorder<'_>) -> Result<T>,
{ {
command_buffer: &'a Arc<CommandBuffer>, command_buffer: &'a CommandBuffer<'a>,
queue: &'a Arc<Mutex<Queue>>, queue: &'a Mutex<Queue<'a>>,
f: F, f: F,
timeout: Option<Duration>, timeout: Option<Duration>,
@ -20,8 +20,8 @@ where
F: FnOnce(&mut CommandBufferRecorder<'_>) -> Result<T>, F: FnOnce(&mut CommandBufferRecorder<'_>) -> Result<T>,
{ {
pub fn builder( pub fn builder(
command_buffer: &'a Arc<CommandBuffer>, command_buffer: &'a CommandBuffer<'a>,
queue: &'a Arc<Mutex<Queue>>, queue: &'a Mutex<Queue<'a>>,
f: F, f: F,
) -> Self { ) -> Self {
SingleSubmit { SingleSubmit {

View file

@ -7,17 +7,14 @@ use std::sync::Arc;
const UNORM_FORMATS: [VkFormat; 2] = [VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM]; const UNORM_FORMATS: [VkFormat; 2] = [VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM];
#[derive(Debug)] #[derive(Debug)]
pub struct Surface { pub struct Surface<'a> {
instance: Arc<Instance>, instance: &'a Instance,
surface: VkSurfaceKHR, surface: VkSurfaceKHR,
} }
impl Surface { impl<'a> Surface<'a> {
pub fn from_vk_surface(surface: VkSurfaceKHR, instance: &Arc<Instance>) -> Arc<Surface> { pub fn from_vk_surface(surface: VkSurfaceKHR, instance: &'a Instance) -> Self {
Arc::new(Surface { Self { instance, surface }
instance: instance.clone(),
surface,
})
} }
pub fn capabilities(&self, device: &Arc<Device>) -> Result<VkSurfaceCapabilitiesKHR> { pub fn capabilities(&self, device: &Arc<Device>) -> Result<VkSurfaceCapabilitiesKHR> {
@ -67,9 +64,19 @@ impl Surface {
} }
} }
impl_vk_handle!(Surface, VkSurfaceKHR, surface); impl<'a> VkHandle<VkSurfaceKHR> for Surface<'a> {
fn vk_handle(&self) -> VkSurfaceKHR {
self.surface
}
}
impl Drop for Surface { impl<'a> VkHandle<VkSurfaceKHR> for &'a Surface<'a> {
fn vk_handle(&self) -> VkSurfaceKHR {
self.surface
}
}
impl<'a> Drop for Surface<'a> {
fn drop(&mut self) { fn drop(&mut self) {
self.instance.destroy_surface(self.surface) self.instance.destroy_surface(self.surface)
} }

View file

@ -5,52 +5,52 @@ use anyhow::Result;
use std::cmp; use std::cmp;
use std::sync::{ use std::sync::{
atomic::{AtomicU32, Ordering::SeqCst}, atomic::{AtomicU32, Ordering::SeqCst},
Arc, Mutex, Mutex,
}; };
pub enum NextImageSynchronization<'a> { pub enum NextImageSynchronization<'a> {
Semaphore(&'a Arc<Semaphore>), Semaphore(&'a Semaphore<'a>),
Fence(&'a Arc<Fence>), Fence(&'a Fence<'a>),
} }
impl<'a> From<&'a Arc<Semaphore>> for NextImageSynchronization<'a> { impl<'a> From<&'a Semaphore<'a>> for NextImageSynchronization<'a> {
fn from(value: &'a Arc<Semaphore>) -> Self { fn from(value: &'a Semaphore<'a>) -> Self {
Self::Semaphore(value) Self::Semaphore(value)
} }
} }
impl<'a> From<&'a Arc<Fence>> for NextImageSynchronization<'a> { impl<'a> From<&'a Fence<'a>> for NextImageSynchronization<'a> {
fn from(value: &'a Arc<Fence>) -> Self { fn from(value: &'a Fence<'a>) -> Self {
Self::Fence(value) Self::Fence(value)
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Swapchain { pub struct Swapchain<'a> {
width: AtomicU32, width: u32,
height: AtomicU32, height: u32,
index: AtomicU32, index: u32,
device: Arc<Device>, device: &'a Device,
surface: Arc<Surface>, surface: Surface<'a>,
create_info: Mutex<VkSwapchainCreateInfoKHR>, create_info: VkSwapchainCreateInfoKHR,
swapchain: Mutex<VkSwapchainKHR>, swapchain: VkSwapchainKHR,
usage: VkImageUsageFlagBits, usage: VkImageUsageFlagBits,
raw: bool, raw: bool,
} }
impl Swapchain { impl<'a> Swapchain<'a> {
pub fn new( pub fn new(
device: Arc<Device>, device: &'a Device,
surface: &Arc<Surface>, surface: Surface<'a>,
vsync: bool, vsync: bool,
image_count: u32, image_count: u32,
image_usage: impl Into<VkImageUsageFlagBits>, image_usage: impl Into<VkImageUsageFlagBits>,
prefered_format: VkFormat, prefered_format: VkFormat,
array_layers: u32, array_layers: u32,
) -> Result<Arc<Swapchain>> { ) -> Result<Swapchain<'a>> {
let surface_caps = surface.capabilities(&device)?; let surface_caps = surface.capabilities(&device)?;
let extent = if surface_caps.currentExtent.width == u32::max_value() { let extent = if surface_caps.currentExtent.width == u32::max_value() {
@ -112,57 +112,54 @@ impl Swapchain {
let swapchain = device.create_swapchain(&swapchain_ci)?; let swapchain = device.create_swapchain(&swapchain_ci)?;
Ok(Arc::new(Swapchain { Ok(Swapchain {
width: AtomicU32::new(extent.width), width: AtomicU32::new(extent.width),
height: AtomicU32::new(extent.height), height: AtomicU32::new(extent.height),
usage: swapchain_ci.imageUsage, usage: swapchain_ci.imageUsage,
index: AtomicU32::new(0), index: AtomicU32::new(0),
device, device,
surface: surface.clone(), surface,
create_info: Mutex::new(swapchain_ci), create_info: Mutex::new(swapchain_ci),
swapchain: Mutex::new(swapchain), swapchain: Mutex::new(swapchain),
raw: false, raw: false,
})) })
} }
pub fn from_ci( pub fn from_ci(device: &Device, swapchain_ci: &VkSwapchainCreateInfoKHR) -> Result<Self> {
device: Arc<Device>, Ok(Swapchain {
swapchain_ci: &VkSwapchainCreateInfoKHR, width: swapchain_ci.imageExtent.width,
) -> Result<Arc<Self>> { height: swapchain_ci.imageExtent.height,
Ok(Arc::new(Swapchain {
width: AtomicU32::new(swapchain_ci.imageExtent.width),
height: AtomicU32::new(swapchain_ci.imageExtent.height),
usage: swapchain_ci.imageUsage, usage: swapchain_ci.imageUsage,
index: AtomicU32::new(0), index: 0,
surface: Surface::from_vk_surface( surface: Surface::from_vk_surface(
swapchain_ci.surface, swapchain_ci.surface,
device.physical_device().instance(), device.physical_device().instance(),
), ),
create_info: Mutex::new(swapchain_ci.clone()), create_info: swapchain_ci.clone(),
swapchain: Mutex::new(device.create_swapchain(swapchain_ci)?), swapchain: device.create_swapchain(swapchain_ci)?,
device, device,
raw: false, raw: false,
})) })
} }
pub fn from_raw( pub fn from_raw(
device: Arc<Device>, device: &'a Device,
swapchain_ci: &VkSwapchainCreateInfoKHR, swapchain_ci: &VkSwapchainCreateInfoKHR,
swapchain: VkSwapchainKHR, swapchain: VkSwapchainKHR,
) -> Arc<Self> { ) -> Self {
Arc::new(Swapchain { Swapchain {
width: AtomicU32::new(swapchain_ci.imageExtent.width), width: swapchain_ci.imageExtent.width,
height: AtomicU32::new(swapchain_ci.imageExtent.height), height: swapchain_ci.imageExtent.height,
usage: swapchain_ci.imageUsage, usage: swapchain_ci.imageUsage,
index: AtomicU32::new(0), index: 0,
surface: Surface::from_vk_surface( surface: Surface::from_vk_surface(
swapchain_ci.surface, swapchain_ci.surface,
@ -170,12 +167,11 @@ impl Swapchain {
), ),
device, device,
create_info: Mutex::new(swapchain_ci.clone()), create_info: swapchain_ci.clone(),
swapchain,
swapchain: Mutex::new(swapchain),
raw: true, raw: true,
}) }
} }
pub fn recreate(&self) -> Result<()> { pub fn recreate(&self) -> Result<()> {
@ -217,10 +213,10 @@ impl Swapchain {
Ok(()) Ok(())
} }
pub fn acquire_next_image<'a>( pub fn acquire_next_image<'b>(
&self, &self,
time_out: u64, time_out: u64,
synchro: impl Into<NextImageSynchronization<'a>>, synchro: impl Into<NextImageSynchronization<'b>>,
) -> Result<OutOfDate<u32>> { ) -> Result<OutOfDate<u32>> {
let synchro = synchro.into(); let synchro = synchro.into();
@ -264,9 +260,9 @@ impl Swapchain {
pub fn wrap_images( pub fn wrap_images(
&self, &self,
images: &[VkImage], images: &[VkImage],
queue: &Arc<Mutex<Queue>>, queue: &Mutex<Queue<'a>>,
assume_layout: bool, assume_layout: bool,
) -> Result<Vec<Arc<Image>>> { ) -> Result<Vec<Image<'a>>> {
let format = self.format(); let format = self.format();
let tiling = VK_IMAGE_TILING_OPTIMAL; let tiling = VK_IMAGE_TILING_OPTIMAL;
@ -290,7 +286,7 @@ impl Swapchain {
self.usage, self.usage,
assume_layout, assume_layout,
) )
.attach_sampler(Sampler::nearest_sampler().build(&self.device)?) .attach_sampler(Sampler::nearest_sampler().build(self.device)?)
.build(&self.device, queue)?, .build(&self.device, queue)?,
); );
} }
@ -299,55 +295,42 @@ impl Swapchain {
} }
pub fn width(&self) -> u32 { pub fn width(&self) -> u32 {
self.width.load(SeqCst) self.width
} }
pub fn height(&self) -> u32 { pub fn height(&self) -> u32 {
self.height.load(SeqCst) self.height
} }
pub fn format(&self) -> VkFormat { pub fn format(&self) -> VkFormat {
self.create_info.lock().unwrap().imageFormat self.create_info.imageFormat
} }
#[inline] #[inline]
fn destroy(&self) { fn destroy(&self) {
self.device self.device.destroy_swapchain(self.swapchain)
.destroy_swapchain(*self.swapchain.lock().unwrap())
} }
} }
impl VulkanDevice for Swapchain { impl<'a> VulkanDevice for Swapchain<'a> {
fn device(&self) -> &Arc<Device> { fn device(&self) -> &Device {
&self.device &self.device
} }
} }
impl VkHandle<VkSwapchainKHR> for Swapchain { impl<'a> VkHandle<VkSwapchainKHR> for Swapchain<'a> {
fn vk_handle(&self) -> VkSwapchainKHR { fn vk_handle(&self) -> VkSwapchainKHR {
*self.swapchain.lock().unwrap() self.swapchain
} }
} }
impl<'a> VkHandle<VkSwapchainKHR> for &'a Swapchain { impl<'a> VkHandle<VkSwapchainKHR> for &'a Swapchain<'a> {
fn vk_handle(&self) -> VkSwapchainKHR { fn vk_handle(&self) -> VkSwapchainKHR {
*self.swapchain.lock().unwrap() self.swapchain
} }
} }
impl VkHandle<VkSwapchainKHR> for Arc<Swapchain> { impl<'a> Drop for Swapchain<'a> {
fn vk_handle(&self) -> VkSwapchainKHR {
*self.swapchain.lock().unwrap()
}
}
impl<'a> VkHandle<VkSwapchainKHR> for &'a Arc<Swapchain> {
fn vk_handle(&self) -> VkSwapchainKHR {
*self.swapchain.lock().unwrap()
}
}
impl Drop for Swapchain {
fn drop(&mut self) { fn drop(&mut self) {
if !self.raw { if !self.raw {
self.destroy(); self.destroy();