392 lines
11 KiB
Rust
392 lines
11 KiB
Rust
use crate::staging::*;
|
|
use slab::Slab;
|
|
use smallvec::SmallVec;
|
|
use std::any::TypeId;
|
|
use std::collections::HashMap;
|
|
use std::sync::Arc;
|
|
|
|
/// An error that can be returned when allocating a mesh.
|
|
pub enum PoolError {
|
|
TooBig,
|
|
NoMoreRoom,
|
|
InvalidIndex,
|
|
AttrTaken,
|
|
AttrUnregistered,
|
|
MismatchedId,
|
|
MismatchedLayout,
|
|
}
|
|
|
|
/// An identifier for a mesh attribute.
|
|
#[repr(transparent)]
|
|
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
|
|
pub struct AttrId(usize);
|
|
|
|
/// A description of an attribute's layout in memory.
|
|
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
|
|
pub struct AttrLayout {
|
|
/// The size (in bytes) of this attribute.
|
|
pub size: usize,
|
|
}
|
|
|
|
/// Information about an [Attribute] registered in [AttrStore].
|
|
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
|
|
pub struct AttrInfo {
|
|
pub layout: AttrLayout,
|
|
pub default_pool_size: usize,
|
|
}
|
|
|
|
/// The data single mesh attribute.
|
|
pub struct AttrBuffer {
|
|
pub id: AttrId,
|
|
pub count: usize,
|
|
pub data: Vec<u8>,
|
|
}
|
|
|
|
/// A compile-time attribute data type.
|
|
pub trait Attribute: Sized {
|
|
/// The memory layout of this data.
|
|
fn get_layout() -> AttrLayout {
|
|
AttrLayout {
|
|
size: std::mem::size_of::<Self>(),
|
|
}
|
|
}
|
|
|
|
/// The default size for new pools of this attribute.
|
|
///
|
|
/// Defaults to 1024 * 1024. (Around one million.)
|
|
fn get_default_pool_size() -> usize {
|
|
1024 * 1024
|
|
}
|
|
}
|
|
|
|
/// A store of [AttrIds][AttrId].
|
|
pub struct AttrStore {
|
|
attributes: Slab<AttrInfo>,
|
|
types: HashMap<TypeId, AttrId>,
|
|
}
|
|
|
|
impl AttrStore {
|
|
pub fn new() -> Arc<Self> {
|
|
Arc::new(Self {
|
|
attributes: Default::default(),
|
|
types: Default::default(),
|
|
})
|
|
}
|
|
|
|
/// Dynamically creates a new [AttrId].
|
|
pub fn add(&mut self, info: AttrInfo) -> AttrId {
|
|
let index = self.attributes.insert(info);
|
|
AttrId(index)
|
|
}
|
|
|
|
/// Gets the [AttrId] for a type implementing [Attribute].
|
|
///
|
|
/// Creates a new [AttrId] for unrecognized types, otherwise reuses an
|
|
/// existing [AttrId].
|
|
pub fn get_type<T: 'static + Attribute>(&mut self) -> AttrId {
|
|
let type_id = TypeId::of::<T>();
|
|
if let Some(id) = self.types.get(&type_id) {
|
|
*id
|
|
} else {
|
|
let layout = T::get_layout();
|
|
let default_pool_size = T::get_default_pool_size();
|
|
let info = AttrInfo {
|
|
layout,
|
|
default_pool_size,
|
|
};
|
|
let id = self.add(info);
|
|
self.types.insert(type_id, id);
|
|
id
|
|
}
|
|
}
|
|
|
|
/// Gets the [AttrInfo] for an [AttrId].
|
|
pub fn get_info(&self, id: &AttrId) -> Option<&AttrInfo> {
|
|
self.attributes.get(id.0)
|
|
}
|
|
}
|
|
|
|
/// Attribute pool allocation location.
|
|
#[derive(Clone)]
|
|
pub struct AttrAllocKey {
|
|
/// The target attribute.
|
|
pub attr: AttrId,
|
|
|
|
/// The index of the attribute pool.
|
|
pub pool: usize,
|
|
|
|
/// The allocation within the attribute pool.
|
|
pub alloc: usize,
|
|
}
|
|
|
|
/// Info about an array of attributes that has been allocated in an [AttrPool].
|
|
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
|
|
pub struct AttrAlloc {
|
|
offset: usize,
|
|
count: usize,
|
|
offset_bytes: usize,
|
|
count_bytes: usize,
|
|
}
|
|
|
|
/// An unused space range in an [AttrPool].
|
|
pub struct FreeSpace {
|
|
offset: usize,
|
|
count: usize,
|
|
}
|
|
|
|
/// A single GPU buffer containing linear arrays of attributes.
|
|
pub struct AttrPool {
|
|
id: AttrId,
|
|
pool_id: usize,
|
|
layout: AttrLayout,
|
|
size: usize,
|
|
allocs: Slab<AttrAlloc>,
|
|
free_space: Vec<FreeSpace>,
|
|
}
|
|
|
|
impl AttrPool {
|
|
pub fn new(id: AttrId, pool_id: usize, info: AttrInfo) -> Self {
|
|
let layout = info.layout;
|
|
let size = info.default_pool_size;
|
|
|
|
Self {
|
|
id,
|
|
pool_id,
|
|
layout,
|
|
size,
|
|
free_space: vec![FreeSpace {
|
|
offset: 0,
|
|
count: size,
|
|
}],
|
|
allocs: Default::default(),
|
|
}
|
|
}
|
|
|
|
/// Loads an [AttrBuffer].
|
|
///
|
|
/// Returns the new [AttrAllocKey].
|
|
pub fn load(&mut self, buf: &AttrBuffer) -> Result<AttrAllocKey, PoolError> {
|
|
let best_index = self.can_load(buf)?;
|
|
self.alloc_at(best_index, buf.count)
|
|
}
|
|
|
|
/// Allocates an array of attributes.
|
|
///
|
|
/// Returns the new [AttrAllocKey].
|
|
pub fn alloc(&mut self, count: usize) -> Result<AttrAllocKey, PoolError> {
|
|
let best_index = self.can_alloc(count)?;
|
|
self.alloc_at(best_index, count)
|
|
}
|
|
|
|
/// Tests if an [AttrBuffer] can be loaded.
|
|
///
|
|
/// Returns the result of [Self::best_fit].
|
|
pub fn can_load(&self, buf: &AttrBuffer) -> Result<usize, PoolError> {
|
|
if buf.id != self.id {
|
|
Err(PoolError::MismatchedId)
|
|
} else if buf.count * self.layout.size != buf.data.len() {
|
|
Err(PoolError::MismatchedLayout)
|
|
} else {
|
|
self.can_alloc(buf.count)
|
|
}
|
|
}
|
|
|
|
/// Tests if an array of attributes can be allocated.
|
|
///
|
|
/// Returns the result of [Self::best_fit].
|
|
pub fn can_alloc(&self, count: usize) -> Result<usize, PoolError> {
|
|
if count > self.size {
|
|
Err(PoolError::TooBig)
|
|
} else if let Some(best_index) = self.best_fit(count) {
|
|
Ok(best_index)
|
|
} else {
|
|
Err(PoolError::NoMoreRoom)
|
|
}
|
|
}
|
|
|
|
/// Finds the index of the best-fit free space for an array of attributes.
|
|
///
|
|
/// TODO: use a binary tree to find best-fit free space in logarithmic time
|
|
fn best_fit(&self, count: usize) -> Option<usize> {
|
|
let mut best_index = None;
|
|
let mut best_count = usize::MAX;
|
|
for (index, space) in self.free_space.iter().enumerate() {
|
|
if space.count >= count && space.count < best_count {
|
|
best_index = Some(index);
|
|
best_count = space.count;
|
|
}
|
|
}
|
|
|
|
best_index
|
|
}
|
|
|
|
/// Allocates an array of attribute at a specific free space index.
|
|
///
|
|
/// Returns the new [AttrAllocKey].
|
|
fn alloc_at(
|
|
&mut self,
|
|
index: usize,
|
|
count: usize,
|
|
) -> Result<AttrAllocKey, PoolError> {
|
|
let free_space = match self.free_space.get_mut(index) {
|
|
Some(index) => index,
|
|
None => return Err(PoolError::InvalidIndex),
|
|
};
|
|
|
|
let offset = free_space.offset;
|
|
|
|
let alloc = AttrAlloc {
|
|
offset,
|
|
count,
|
|
offset_bytes: offset * self.layout.size,
|
|
count_bytes: count * self.layout.size,
|
|
};
|
|
|
|
let index = self.allocs.insert(alloc);
|
|
|
|
let key = AttrAllocKey {
|
|
attr: self.id,
|
|
pool: self.pool_id,
|
|
alloc: index,
|
|
};
|
|
|
|
use std::cmp::Ordering;
|
|
match free_space.count.cmp(&count) {
|
|
Ordering::Less => {
|
|
return Err(PoolError::TooBig);
|
|
}
|
|
Ordering::Equal => {
|
|
self.free_space.remove(index);
|
|
}
|
|
Ordering::Greater => {
|
|
free_space.count -= count;
|
|
free_space.offset += count;
|
|
}
|
|
}
|
|
|
|
Ok(key)
|
|
}
|
|
|
|
/// Frees an allocation (by key) from the pool.
|
|
pub fn free(&mut self, key: usize) -> Result<(), PoolError> {
|
|
let alloc = self.allocs.try_remove(key).ok_or(PoolError::InvalidIndex)?;
|
|
|
|
let free_space = FreeSpace {
|
|
offset: alloc.offset,
|
|
count: alloc.count,
|
|
};
|
|
|
|
// TODO merge free spaces
|
|
self.free_space.push(free_space);
|
|
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// The number of attributes a mesh can have before they're moved to the heap.
|
|
pub const MAX_MESH_INLINE_ATTRIBUTES: usize = 16;
|
|
|
|
/// A mesh and all of its attributes.
|
|
pub struct MeshBuffer {
|
|
pub attributes: SmallVec<[AttrBuffer; MAX_MESH_INLINE_ATTRIBUTES]>,
|
|
}
|
|
|
|
/// An allocated mesh.
|
|
pub struct MeshAlloc {
|
|
pub attributes: SmallVec<[AttrAllocKey; MAX_MESH_INLINE_ATTRIBUTES]>,
|
|
}
|
|
|
|
/// A handle to an allocated mesh.
|
|
#[repr(transparent)]
|
|
pub struct MeshHandle(usize);
|
|
|
|
impl HasMeshHandle for MeshHandle {
|
|
fn get_mesh_handle(&self) -> &Self {
|
|
self
|
|
}
|
|
}
|
|
|
|
/// A trait for structs containing [MeshHandles][MeshHandle] that are not
|
|
/// themselves handles. Used for iteration.
|
|
pub trait HasMeshHandle {
|
|
fn get_mesh_handle(&self) -> &MeshHandle;
|
|
}
|
|
|
|
/// A mesh data pool.
|
|
pub struct MeshPool {
|
|
device: Arc<wgpu::Device>,
|
|
staging: StagingPool<AttrAllocKey>,
|
|
attr_store: Arc<AttrStore>,
|
|
allocs: Slab<MeshAlloc>,
|
|
pools: HashMap<AttrId, Vec<AttrPool>>,
|
|
}
|
|
|
|
impl MeshPool {
|
|
pub fn new(device: Arc<wgpu::Device>, attr_store: Arc<AttrStore>) -> Arc<Self> {
|
|
Arc::new(Self {
|
|
device: device.clone(),
|
|
staging: StagingPool::new(device, 1024 * 1024),
|
|
attr_store,
|
|
allocs: Default::default(),
|
|
pools: Default::default(),
|
|
})
|
|
}
|
|
|
|
/// Loads a [MeshBuffer].
|
|
pub fn load(&mut self, buf: MeshBuffer) -> Result<MeshHandle, PoolError> {
|
|
let mut attrs = HashMap::new();
|
|
|
|
for attr in buf.attributes.into_iter() {
|
|
if let Some(_) = attrs.insert(attr.id, attr) {
|
|
// TODO: support for loading duplicate attribute IDs
|
|
return Err(PoolError::AttrTaken);
|
|
}
|
|
}
|
|
|
|
let mut attr_allocs = SmallVec::new();
|
|
let mut copies = Vec::new();
|
|
for (id, buf) in attrs.drain() {
|
|
let pools = match self.pools.get_mut(&id) {
|
|
Some(pools) => pools,
|
|
None => {
|
|
let info = match self.attr_store.get_info(&id) {
|
|
Some(info) => info,
|
|
None => return Err(PoolError::AttrUnregistered),
|
|
};
|
|
|
|
let pool = AttrPool::new(id, 0, *info);
|
|
self.pools.insert(id, vec![pool]);
|
|
self.pools.get_mut(&id).unwrap()
|
|
}
|
|
};
|
|
|
|
for pool in pools.iter_mut() {
|
|
match pool.load(&buf) {
|
|
Ok(alloc) => {
|
|
let copy = CopyBuffer {
|
|
target: alloc.clone(),
|
|
offset: 0,
|
|
data: buf.data,
|
|
};
|
|
|
|
attr_allocs.push(alloc);
|
|
copies.push(copy);
|
|
break;
|
|
}
|
|
Err(PoolError::NoMoreRoom) => {}
|
|
Err(e) => return Err(e),
|
|
}
|
|
}
|
|
}
|
|
|
|
self.staging.queue_copies(copies);
|
|
|
|
let alloc = MeshAlloc {
|
|
attributes: attr_allocs,
|
|
};
|
|
let key = self.allocs.insert(alloc);
|
|
let handle = MeshHandle(key);
|
|
Ok(handle)
|
|
}
|
|
}
|