Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic meshes #251

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions core/src/casts.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,46 @@
//! Contains functions for casting
use std::{any::TypeId, borrow::Cow};
use std::{
any::TypeId,
borrow::Cow,
mem::{align_of, size_of},
};

/// Cast vec of some arbitrary type into vec of bytes.
/// Can lead to UB if allocator changes. Use with caution.
/// TODO: Replace with something safer.
pub fn cast_vec<T: Copy>(mut vec: Vec<T>) -> Vec<u8> {
let len = std::mem::size_of::<T>() * vec.len();
let cap = std::mem::size_of::<T>() * vec.capacity();
let len = size_of::<T>() * vec.len();
let cap = size_of::<T>() * vec.capacity();
let ptr = vec.as_mut_ptr();
std::mem::forget(vec);
unsafe { Vec::from_raw_parts(ptr as _, len, cap) }
}

/// Cast slice of some arbitrary type into slice of bytes.
pub fn cast_slice<T>(slice: &[T]) -> &[u8] {
let len = std::mem::size_of::<T>() * slice.len();
let len = size_of::<T>() * slice.len();
let ptr = slice.as_ptr();
unsafe { std::slice::from_raw_parts(ptr as _, len) }
}

/// Cast slice of some arbitrary type into slice of bytes.
pub unsafe fn cast_arbitrary_slice<T, U>(slice: &[T]) -> &[U] {
let bytes = size_of::<T>() * slice.len();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is terribly unsafe in so many ways, a comment should definitely mention that it's effectively equivalen to transmute. You are only using it on Copy types, so it should probably be typeguarded as such. That way we at least get rid of Drop related issues.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also intended as internal method. Shouldn't be pub.

let u_s = bytes / size_of::<U>();
let ptr = slice.as_ptr();
assert_eq!(ptr as usize % align_of::<U>(), 0);
std::slice::from_raw_parts(ptr as _, u_s)
}

/// Cast slice of some arbitrary type into slice of bytes.
pub unsafe fn cast_arbitrary_slice_mut<T, U>(slice: &mut [T]) -> &mut [U] {
let bytes = size_of::<T>() * slice.len();
let u_s = bytes / size_of::<U>();
let ptr = slice.as_ptr();
assert_eq!(ptr as usize % align_of::<U>(), 0);
std::slice::from_raw_parts_mut(ptr as _, u_s)
}

/// Cast `cow` of some arbitrary type into `cow` of bytes.
/// Can lead to UB if allocator changes. Use with caution.
/// TODO: Replace with something safer.
Expand Down
35 changes: 24 additions & 11 deletions factory/src/factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ use {
HasRawWindowHandle,
},
smallvec::SmallVec,
std::{borrow::BorrowMut, cmp::max, mem::ManuallyDrop},
std::{
borrow::BorrowMut,
cmp::max,
mem::{size_of_val, ManuallyDrop},
},
thread_profiler::profile_scope,
};

Expand Down Expand Up @@ -442,15 +446,15 @@ where
/// Update content of the buffer bound to host visible memory.
/// This function (unlike [`upload_buffer`]) update content immediatelly.
///
/// Buffers allocated from host-invisible memory types cannot be
/// Buffers allocated not from host-invisible memory types cannot be
/// updated via this function.
///
/// Updated content will be automatically made visible to device operations
/// that will be submitted later.
///
/// # Panics
///
/// Panics if buffer size is less than `offset` + size of `content`.
/// Panics if buffer size is less than `offset + size_of_val(content)`.
///
/// # Safety
///
Expand All @@ -466,10 +470,8 @@ where
where
T: 'static + Copy,
{
let content = std::slice::from_raw_parts(
content.as_ptr() as *const u8,
content.len() * std::mem::size_of::<T>(),
);
let content =
std::slice::from_raw_parts(content.as_ptr() as *const u8, size_of_val(content));

let mut mapped = buffer.map(&self.device, offset..offset + content.len() as u64)?;
mapped
Expand Down Expand Up @@ -512,7 +514,7 @@ where
{
assert!(buffer.info().usage.contains(buffer::Usage::TRANSFER_DST));

let content_size = content.len() as u64 * std::mem::size_of::<T>() as u64;
let content_size = size_of_val(content) as u64;
let mut staging = self
.create_buffer(
BufferInfo {
Expand All @@ -527,7 +529,18 @@ where
.map_err(UploadError::Map)?;

self.uploader
.upload_buffer(&self.device, buffer, offset, staging, last, next)
.upload_buffer(
&self.device,
buffer,
staging,
last,
next,
Some(rendy_core::hal::command::BufferCopy {
src: 0,
dst: offset,
size: content_size,
}),
)
.map_err(UploadError::Upload)
}

Expand All @@ -548,15 +561,15 @@ where
pub unsafe fn upload_from_staging_buffer(
&self,
buffer: &Buffer<B>,
offset: u64,
staging: Escape<Buffer<B>>,
last: Option<BufferState>,
next: BufferState,
ranges: impl IntoIterator<Item = rendy_core::hal::command::BufferCopy>,
) -> Result<(), OutOfMemory> {
assert!(buffer.info().usage.contains(buffer::Usage::TRANSFER_DST));
assert!(staging.info().usage.contains(buffer::Usage::TRANSFER_SRC));
self.uploader
.upload_buffer(&self.device, buffer, offset, staging, last, next)
.upload_buffer(&self.device, buffer, staging, last, next, ranges)
}

/// Update image layers content with provided data.
Expand Down
12 changes: 2 additions & 10 deletions factory/src/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,10 @@ where
&self,
device: &Device<B>,
buffer: &Buffer<B>,
offset: u64,
staging: Escape<Buffer<B>>,
last: Option<BufferState>,
next: BufferState,
ranges: impl IntoIterator<Item = rendy_core::hal::command::BufferCopy>,
) -> Result<(), OutOfMemory> {
let mut family_uploads = self.family_uploads[next.queue.family.index]
.as_ref()
Expand All @@ -195,15 +195,7 @@ where

let next_upload = family_uploads.next_upload(device, next.queue.index)?;
let mut encoder = next_upload.command_buffer.encoder();
encoder.copy_buffer(
staging.raw(),
buffer.raw(),
Some(rendy_core::hal::command::BufferCopy {
src: 0,
dst: offset,
size: staging.size(),
}),
);
encoder.copy_buffer(staging.raw(), buffer.raw(), ranges);

next_upload.staging_buffers.push(staging);

Expand Down
5 changes: 2 additions & 3 deletions memory/src/mapping/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub(crate) mod write;
use {
crate::{memory::Memory, util::fits_usize},
gfx_hal::{device::Device as _, Backend},
std::{ops::Range, ptr::NonNull},
std::{mem::MaybeUninit, ops::Range, ptr::NonNull},
};

pub(crate) use self::range::{
Expand Down Expand Up @@ -118,12 +118,11 @@ where
/// # Safety
///
/// * Caller must ensure that device won't write to the memory region until the borrowing ends.
/// * `T` Must be plain-old-data type compatible with data in mapped region.
pub unsafe fn read<'b, T>(
&'b mut self,
device: &B::Device,
range: Range<u64>,
) -> Result<&'b [T], gfx_hal::device::MapError>
) -> Result<&'b [MaybeUninit<T>], gfx_hal::device::MapError>
where
'a: 'b,
T: Copy,
Expand Down
18 changes: 9 additions & 9 deletions memory/src/mapping/range.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use {
crate::util::fits_usize,
std::{
mem::{align_of, size_of},
mem::{align_of, size_of, MaybeUninit},
ops::Range,
ptr::NonNull,
slice::{from_raw_parts, from_raw_parts_mut},
Expand Down Expand Up @@ -62,8 +62,10 @@ pub(crate) fn mapped_sub_range(
/// User must ensure that:
/// * this function won't create aliasing slices.
/// * returned slice doesn't outlive mapping.
/// * `T` Must be plain-old-data type compatible with data in mapped region.
pub(crate) unsafe fn mapped_slice_mut<'a, T>(ptr: NonNull<u8>, size: usize) -> &'a mut [T] {
pub(crate) unsafe fn mapped_slice_mut<'a, T>(
ptr: NonNull<u8>,
size: usize,
) -> &'a mut [MaybeUninit<T>] {
assert_eq!(
size % size_of::<T>(),
0,
Expand All @@ -76,15 +78,13 @@ pub(crate) unsafe fn mapped_slice_mut<'a, T>(ptr: NonNull<u8>, size: usize) -> &
"Range offset must be multiple of element alignment"
);
assert!(usize::max_value() - size >= ptr.as_ptr() as usize);
from_raw_parts_mut(ptr.as_ptr() as *mut T, size)
from_raw_parts_mut(ptr.as_ptr() as *mut MaybeUninit<T>, size)
}

/// # Safety
///
/// User must ensure that:
/// * returned slice doesn't outlive mapping.
/// * `T` Must be plain-old-data type compatible with data in mapped region.
pub(crate) unsafe fn mapped_slice<'a, T>(ptr: NonNull<u8>, size: usize) -> &'a [T] {
/// User must ensure that returned slice doesn't outlive mapping.
pub(crate) unsafe fn mapped_slice<'a, T>(ptr: NonNull<u8>, size: usize) -> &'a [MaybeUninit<T>] {
assert_eq!(
size % size_of::<T>(),
0,
Expand All @@ -97,5 +97,5 @@ pub(crate) unsafe fn mapped_slice<'a, T>(ptr: NonNull<u8>, size: usize) -> &'a [
"Range offset must be multiple of element alignment"
);
assert!(usize::max_value() - size >= ptr.as_ptr() as usize);
from_raw_parts(ptr.as_ptr() as *const T, size)
from_raw_parts(ptr.as_ptr() as *const MaybeUninit<T>, size)
}
17 changes: 7 additions & 10 deletions memory/src/mapping/write.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::ptr::copy_nonoverlapping;
use std::{mem::MaybeUninit, ptr::copy_nonoverlapping};

/// Trait for memory region suitable for host writes.
pub trait Write<T: Copy> {
Expand All @@ -7,7 +7,7 @@ pub trait Write<T: Copy> {
/// # Safety
///
/// * Returned slice should not be read.
unsafe fn slice(&mut self) -> &mut [T];
unsafe fn slice(&mut self) -> &mut [MaybeUninit<T>];

/// Write data into mapped memory sub-region.
///
Expand All @@ -18,14 +18,13 @@ pub trait Write<T: Copy> {
unsafe {
let slice = self.slice();
assert!(data.len() <= slice.len());
copy_nonoverlapping(data.as_ptr(), slice.as_mut_ptr(), data.len());
copy_nonoverlapping(data.as_ptr(), slice.as_mut_ptr() as *mut T, data.len());
}
}
}

#[derive(Debug)]
pub(super) struct WriteFlush<'a, T, F: FnOnce() + 'a> {
pub(super) slice: &'a mut [T],
pub(super) slice: &'a mut [MaybeUninit<T>],
pub(super) flush: Option<F>,
}

Expand All @@ -49,15 +48,13 @@ where
/// # Safety
///
/// [See doc comment for trait method](trait.Write#method.slice)
unsafe fn slice(&mut self) -> &mut [T] {
unsafe fn slice(&mut self) -> &mut [MaybeUninit<T>] {
self.slice
}
}

#[warn(dead_code)]
#[derive(Debug)]
pub(super) struct WriteCoherent<'a, T> {
pub(super) slice: &'a mut [T],
pub(super) slice: &'a mut [MaybeUninit<T>],
}

impl<'a, T> Write<T> for WriteCoherent<'a, T>
Expand All @@ -67,7 +64,7 @@ where
/// # Safety
///
/// [See doc comment for trait method](trait.Write#method.slice)
unsafe fn slice(&mut self) -> &mut [T] {
unsafe fn slice(&mut self) -> &mut [MaybeUninit<T>] {
self.slice
}
}
Loading