split into two crates
This commit is contained in:
@@ -0,0 +1,523 @@
|
||||
//! Manages tape aabb buffers.
|
||||
|
||||
use alloc::borrow::Cow;
|
||||
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_asset::AssetId;
|
||||
use bevy_derive::{Deref, DerefMut};
|
||||
use bevy_ecs::{
|
||||
resource::Resource,
|
||||
schedule::IntoScheduleConfigs as _,
|
||||
system::{Res, ResMut},
|
||||
world::{FromWorld, World},
|
||||
};
|
||||
use bevy_log::warn;
|
||||
use bevy_render::{
|
||||
GpuResourceAppExt, Render, RenderApp, RenderSystems,
|
||||
render_asset::{ExtractedAssets, prepare_assets},
|
||||
renderer::{RenderDevice, RenderQueue},
|
||||
slab_allocator::{
|
||||
Slab, SlabAllocationBufferSlice, SlabAllocator, SlabAllocatorSettings, SlabId, SlabItem,
|
||||
SlabItemLayout,
|
||||
},
|
||||
};
|
||||
use bevy_shape::BoundingVolume;
|
||||
use wgpu::{BufferUsages, COPY_BUFFER_ALIGNMENT};
|
||||
|
||||
use super::{Aabb, RenderTape, TapeMetadata};
|
||||
use crate::tape::Tape;
|
||||
|
||||
/// A plugin that manages GPU memory for tape data.
|
||||
pub struct TapeAllocatorPlugin;
|
||||
|
||||
/// Manages the assignment of tape data to GPU buffers.
|
||||
///
|
||||
/// The Bevy renderer tries to pack vertex and index data for multiple tapes
|
||||
/// together so that multiple tapes can be drawn back-to-back without any
|
||||
/// rebinding. This resource manages these buffers.
|
||||
///
|
||||
/// The [`TapeAllocatorSettings`] allows you to tune the behavior of the
|
||||
/// allocator for better performance with your use case. Most applications won't
|
||||
/// need to change the settings from their default values.
|
||||
#[derive(Resource, Deref, DerefMut)]
|
||||
pub struct TapeAllocator {
|
||||
/// Holds all buffers and offset allocators.
|
||||
#[deref]
|
||||
slab_allocator: SlabAllocator<TapeSlabItem>,
|
||||
}
|
||||
|
||||
/// Tunable parameters that customize the behavior of the allocator.
|
||||
///
|
||||
/// Generally, these parameters adjust the tradeoff between memory fragmentation
|
||||
/// and speed. You can adjust them as desired for your application. Most
|
||||
/// applications can stick with the default values.
|
||||
#[derive(Resource, Deref, DerefMut)]
|
||||
pub struct TapeAllocatorSettings {
|
||||
#[deref]
|
||||
pub slab_allocator_settings: SlabAllocatorSettings,
|
||||
|
||||
/// Additional buffer usages to add to any vertex or index buffers created.
|
||||
pub extra_buffer_usages: BufferUsages,
|
||||
}
|
||||
|
||||
impl Default for TapeAllocatorSettings {
|
||||
fn default() -> TapeAllocatorSettings {
|
||||
TapeAllocatorSettings {
|
||||
slab_allocator_settings: SlabAllocatorSettings::default(),
|
||||
extra_buffer_usages: BufferUsages::empty(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ID of a single slab.
|
||||
pub type TapeSlabId = SlabId<TapeSlabItem>;
|
||||
|
||||
/// The slab buffer and location within that slab in which each tape is
|
||||
/// allocated.
|
||||
pub type TapeBufferSlice<'a> = SlabAllocationBufferSlice<'a, TapeSlabItem>;
|
||||
|
||||
/// The [`SlabItem`] implementation that describes the information needed to
|
||||
/// allocate and free tapes.
|
||||
pub struct TapeSlabItem;
|
||||
|
||||
impl SlabItem for TapeSlabItem {
|
||||
type Key = TapeAllocationKey;
|
||||
type Layout = ElementLayout;
|
||||
|
||||
fn label() -> Cow<'static, str> {
|
||||
"tape".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// IDs of the slabs associated with a single tape.
|
||||
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
|
||||
pub struct TapeSlabs {
|
||||
/// The slab storing the tape's aabb data.
|
||||
pub aabb_slab_id: TapeSlabId,
|
||||
/// The slab storing the tape's metadata.
|
||||
pub metadata_slab_id: Option<TapeSlabId>,
|
||||
}
|
||||
|
||||
/// Returns the type of buffer that this is: vertex, index, metadata.
|
||||
fn element_class(slab: &Slab<TapeSlabItem>) -> ElementClass {
|
||||
slab.element_layout().class
|
||||
}
|
||||
|
||||
/// The handle used to retrieve a single tape allocation.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct TapeAllocationKey {
|
||||
/// The ID of the tape asset.
|
||||
pub tape_id: AssetId<Tape>,
|
||||
/// The type of data: vertex data, index data
|
||||
pub class: ElementClass,
|
||||
}
|
||||
|
||||
impl TapeAllocationKey {
|
||||
/// Creates a new [`TapeAllocationKey`] for the given tape asset ID and
|
||||
/// class.
|
||||
pub fn new(tape_id: AssetId<Tape>, class: ElementClass) -> Self {
|
||||
Self { tape_id, class }
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of element that a tape slab can store.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum ElementClass {
|
||||
/// Per-tape metadata
|
||||
Metadata,
|
||||
/// Data for the aabbs.
|
||||
Aabb,
|
||||
}
|
||||
|
||||
/// Information about the size of individual elements within a slab.
|
||||
///
|
||||
/// Slab objects are allocated in units of *slots*. Usually, each element takes
|
||||
/// up one slot, and so elements and slots are equivalent. Occasionally,
|
||||
/// however, a slot may consist of 2 or even 4 elements. This occurs when the
|
||||
/// size of an element isn't divisible by [`COPY_BUFFER_ALIGNMENT`]. When we
|
||||
/// resize buffers, we perform GPU-to-GPU copies to shuffle the existing
|
||||
/// elements into their new positions, and such copies must be on
|
||||
/// [`COPY_BUFFER_ALIGNMENT`] boundaries. Slots solve this problem by
|
||||
/// guaranteeing that the size of an allocation quantum is divisible by both the
|
||||
/// size of an element and [`COPY_BUFFER_ALIGNMENT`], so we can relocate it
|
||||
/// freely.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ElementLayout {
|
||||
class: ElementClass,
|
||||
|
||||
/// The size in bytes of a single element.
|
||||
size: u64,
|
||||
|
||||
/// The number of elements that make up a single slot.
|
||||
///
|
||||
/// Usually, this is 1, but it can be different if [`ElementLayout::size`]
|
||||
/// isn't divisible by 4. See the comment in [`ElementLayout`] for more
|
||||
/// details.
|
||||
elements_per_slot: u32,
|
||||
|
||||
buffer_usages: BufferUsages,
|
||||
}
|
||||
|
||||
impl Plugin for TapeAllocatorPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
|
||||
render_app
|
||||
.init_resource::<TapeAllocatorSettings>()
|
||||
.add_systems(
|
||||
Render,
|
||||
allocate_and_free_tapes
|
||||
.in_set(RenderSystems::PrepareAssets)
|
||||
.before(prepare_assets::<RenderTape>),
|
||||
);
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The `RenderAdapter` isn't available until now, so we can't do this in
|
||||
// [`Plugin::build`].
|
||||
render_app.init_gpu_resource::<TapeAllocator>();
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorld for TapeAllocator {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
// Take the `extra_buffer_usages` from the tape allocator settings into
|
||||
// account.
|
||||
let tape_allocator_settings = world.resource::<TapeAllocatorSettings>();
|
||||
let mut slab_allocator = SlabAllocator::new();
|
||||
slab_allocator.extra_buffer_usages |= tape_allocator_settings.extra_buffer_usages;
|
||||
|
||||
Self { slab_allocator }
|
||||
}
|
||||
}
|
||||
|
||||
/// A system that processes newly-extracted or newly-removed tapes and writes
|
||||
/// their data into buffers or frees their data as appropriate.
|
||||
pub fn allocate_and_free_tapes(
|
||||
mut tape_allocator: ResMut<TapeAllocator>,
|
||||
tape_allocator_settings: Res<TapeAllocatorSettings>,
|
||||
extracted_tapes: Res<ExtractedAssets<RenderTape>>,
|
||||
render_device: Res<RenderDevice>,
|
||||
render_queue: Res<RenderQueue>,
|
||||
) {
|
||||
bevy_log::debug!("Allocating and freeing tapes");
|
||||
bevy_log::debug!(
|
||||
"extracted tapes ({}): {:?}",
|
||||
extracted_tapes.extracted.len(),
|
||||
extracted_tapes.extracted
|
||||
);
|
||||
// Clear the list of tapes displaced by last frame's slab growth.
|
||||
tape_allocator.clear_displaced_keys();
|
||||
|
||||
// Process removed or modified tapes.
|
||||
tape_allocator.free_tapes(&extracted_tapes);
|
||||
|
||||
// Process newly-added or modified tapes.
|
||||
tape_allocator.allocate_tapes(
|
||||
&tape_allocator_settings,
|
||||
&extracted_tapes,
|
||||
&render_device,
|
||||
&render_queue,
|
||||
);
|
||||
}
|
||||
|
||||
impl TapeAllocator {
|
||||
/// Returns the buffer and range within that buffer of the metadata for
|
||||
/// the tape with the given ID.
|
||||
///
|
||||
/// If the tape wasn't allocated, returns None.
|
||||
pub fn tape_metadata_slice(&self, tape_id: &AssetId<Tape>) -> Option<TapeBufferSlice<'_>> {
|
||||
self.slab_allocation_slice(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Metadata),
|
||||
*self.tape_id_to_metadata_slab(tape_id)?,
|
||||
)
|
||||
}
|
||||
|
||||
/// Tapes that had the buffer under their aabb data replaced
|
||||
/// this frame by a slab they were already resident in growing, so that
|
||||
/// anything caching those buffers can rebuild just the affected
|
||||
/// entries.
|
||||
///
|
||||
/// **It is not the full set of tapes whose buffers changed this frame, and
|
||||
/// is not meant to be.** Callers must handle [`ExtractedAssets`]
|
||||
/// themselves if they want the full set of changed buffers.
|
||||
///
|
||||
/// See [`SlabAllocator::keys_displaced_by_slab_growth`], which this wraps.
|
||||
pub fn tapes_displaced_by_slab_growth(&self) -> impl Iterator<Item = AssetId<Tape>> {
|
||||
self.keys_displaced_by_slab_growth()
|
||||
.iter()
|
||||
.filter(|key| matches!(key.class, ElementClass::Aabb))
|
||||
.map(|key| key.tape_id)
|
||||
}
|
||||
|
||||
/// Returns the buffer and range within that buffer of the aabb data for
|
||||
/// the tape with the given ID.
|
||||
///
|
||||
/// If the tape wasn't allocated, returns None.
|
||||
pub fn tape_aabb_slice(&self, tape_id: &AssetId<Tape>) -> Option<TapeBufferSlice<'_>> {
|
||||
self.slab_allocation_slice(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Aabb),
|
||||
*self.tape_id_to_aabb_slab(tape_id)?,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the IDs of the vertex buffer and index buffer respectively for
|
||||
/// the tape with the given ID.
|
||||
///
|
||||
/// If the tape wasn't allocated, or has no index data in the case of the
|
||||
/// index buffer, the corresponding element in the returned tuple will be
|
||||
/// None.
|
||||
pub fn tape_slabs(&self, tape_id: &AssetId<Tape>) -> Option<TapeSlabs> {
|
||||
Some(TapeSlabs {
|
||||
aabb_slab_id: self.tape_id_to_aabb_slab(tape_id).cloned()?,
|
||||
metadata_slab_id: self.tape_id_to_metadata_slab(tape_id).cloned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the number of aabb allocations that this tape allocator
|
||||
/// manages.
|
||||
pub fn aabb_allocation_count(&self) -> usize {
|
||||
self.key_to_slab
|
||||
.keys()
|
||||
.filter(|key| key.class == ElementClass::Aabb)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Given the ID of a tape, returns the ID of the slab that contains the
|
||||
/// metadata for that tape, if it exists.
|
||||
fn tape_id_to_metadata_slab(&self, tape_id: &AssetId<Tape>) -> Option<&SlabId<TapeSlabItem>> {
|
||||
self.key_to_slab
|
||||
.get(&TapeAllocationKey::new(*tape_id, ElementClass::Metadata))
|
||||
}
|
||||
|
||||
/// Given the ID of a tape, returns the ID of the slab that contains the
|
||||
/// aabb data for that tape, if it exists.
|
||||
fn tape_id_to_aabb_slab(&self, tape_id: &AssetId<Tape>) -> Option<&SlabId<TapeSlabItem>> {
|
||||
self.key_to_slab
|
||||
.get(&TapeAllocationKey::new(*tape_id, ElementClass::Aabb))
|
||||
}
|
||||
|
||||
pub fn metadata_slabs(&self) -> impl Iterator<Item = TapeSlabId> {
|
||||
self.slabs.iter().filter_map(|(slab_id, slab)| {
|
||||
if matches!(element_class(slab), ElementClass::Metadata) {
|
||||
Some(*slab_id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Processes newly-loaded tapes, allocating room in the slabs for their
|
||||
/// tape data and performing upload operations as appropriate.
|
||||
fn allocate_tapes(
|
||||
&mut self,
|
||||
tape_allocator_settings: &TapeAllocatorSettings,
|
||||
extracted_tapes: &ExtractedAssets<RenderTape>,
|
||||
render_device: &RenderDevice,
|
||||
render_queue: &RenderQueue,
|
||||
) {
|
||||
let mut allocation_stage = self.slab_allocator.stage_allocation();
|
||||
|
||||
// Loop over each tape that was extracted this frame.
|
||||
for (tape_id, tape) in &extracted_tapes.extracted {
|
||||
let aabb_buffer_size = tape.get_aabb_buffer_size() as u64;
|
||||
bevy_log::debug!("Tape {:?} has buffer size {}", tape_id, aabb_buffer_size);
|
||||
if aabb_buffer_size == 0 {
|
||||
warn!("Tape {:?} contains no aabbs.", tape_id);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Allocate metadata.
|
||||
let metadata_element_layout = ElementLayout::metadata(tape);
|
||||
bevy_log::debug!(
|
||||
"Tape {:?} has metadata element layout {:?}",
|
||||
tape_id,
|
||||
metadata_element_layout
|
||||
);
|
||||
allocation_stage.allocate(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Metadata),
|
||||
size_of::<TapeMetadata>() as u64,
|
||||
metadata_element_layout,
|
||||
tape_allocator_settings,
|
||||
);
|
||||
|
||||
// Allocate aabb data.
|
||||
let aabb_element_layout = ElementLayout::aabb(tape);
|
||||
bevy_log::debug!(
|
||||
"Tape {:?} has aabb element layout {:?}",
|
||||
tape_id,
|
||||
aabb_element_layout
|
||||
);
|
||||
allocation_stage.allocate(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Aabb),
|
||||
aabb_buffer_size,
|
||||
aabb_element_layout,
|
||||
tape_allocator_settings,
|
||||
);
|
||||
}
|
||||
|
||||
// Perform growth.
|
||||
allocation_stage.commit(render_device, render_queue);
|
||||
for (tape_id, _) in &extracted_tapes.extracted {
|
||||
bevy_log::debug!("Tape {}: Aabb slice allocated", tape_id);
|
||||
debug_assert!(self.tape_id_to_aabb_slab(tape_id).is_some())
|
||||
}
|
||||
|
||||
// Copy new tape data in.
|
||||
for (tape_id, tape) in &extracted_tapes.extracted {
|
||||
let aabb_buffer_size = tape.get_aabb_buffer_size() as u64;
|
||||
if aabb_buffer_size == 0 {
|
||||
continue;
|
||||
}
|
||||
self.copy_tape_aabb(tape_id, tape, render_device, render_queue);
|
||||
self.copy_tape_metadata(tape_id, tape, render_device, render_queue);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies metadata from a tape into the appropriate spot in the slab.
|
||||
fn copy_tape_metadata(
|
||||
&mut self,
|
||||
tape_id: &AssetId<Tape>,
|
||||
tape: &Tape,
|
||||
render_device: &RenderDevice,
|
||||
render_queue: &RenderQueue,
|
||||
) {
|
||||
let metadata = {
|
||||
let aabb = tape.get_aabb(0.0);
|
||||
let aabb_center = aabb.center().into();
|
||||
let aabb_half_extents = aabb.half_size().into();
|
||||
TapeMetadata {
|
||||
aabb_center,
|
||||
aabb_half_extents,
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
// Call the generic function.
|
||||
self.copy_element_data(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Metadata),
|
||||
size_of::<TapeMetadata>(),
|
||||
|mut slice| slice.copy_from_slice(bytemuck::cast_slice(&[metadata])),
|
||||
render_device,
|
||||
render_queue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Fills the tape AABB buffer with zeros.
|
||||
fn copy_tape_aabb(
|
||||
&mut self,
|
||||
tape_id: &AssetId<Tape>,
|
||||
tape: &Tape,
|
||||
render_device: &RenderDevice,
|
||||
render_queue: &RenderQueue,
|
||||
) {
|
||||
let length = tape.get_aabb_buffer_size();
|
||||
// Call the generic function.
|
||||
self.copy_element_data(
|
||||
&TapeAllocationKey::new(*tape_id, ElementClass::Aabb),
|
||||
length as _,
|
||||
|mut slice| slice.fill(0),
|
||||
render_device,
|
||||
render_queue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Frees allocations for tapes that were removed, modified, or
|
||||
/// re-extracted this frame.
|
||||
fn free_tapes(&mut self, extracted_tapes: &ExtractedAssets<RenderTape>) {
|
||||
let mut deallocation_stage = self.slab_allocator.stage_deallocation();
|
||||
|
||||
// TODO: Consider explicitly reusing allocations for changed tapes of
|
||||
// the same size
|
||||
|
||||
// Free every tape that `allocate_tapes` is about to reallocate.
|
||||
// Despite its name, `added` holds every tape extracted this
|
||||
// frame rather than only the new ones, so it's exactly that
|
||||
// set. This catches a tape removed from `Assets` and reinserted
|
||||
// under the same ID, which arrives as `Removed` then `Added`
|
||||
// and so never appears in `modified`.
|
||||
let tapes_to_free = extracted_tapes
|
||||
.removed
|
||||
.iter()
|
||||
.chain(extracted_tapes.modified.iter())
|
||||
.chain(extracted_tapes.added.iter());
|
||||
|
||||
for tape_id in tapes_to_free {
|
||||
deallocation_stage.free(&TapeAllocationKey::new(*tape_id, ElementClass::Metadata));
|
||||
deallocation_stage.free(&TapeAllocationKey::new(*tape_id, ElementClass::Aabb));
|
||||
}
|
||||
|
||||
deallocation_stage.commit();
|
||||
}
|
||||
}
|
||||
|
||||
impl ElementLayout {
|
||||
/// Creates an [`ElementLayout`] for tape data of the given class (vertex or
|
||||
/// index) with the given byte size.
|
||||
fn new(class: ElementClass, size: u64) -> ElementLayout {
|
||||
const {
|
||||
assert!(4 == COPY_BUFFER_ALIGNMENT);
|
||||
}
|
||||
|
||||
// this is equivalent to `4 / gcd(4,size)` but lets us not implement
|
||||
// gcd. ping @atlv if above assert ever fails (likely never)
|
||||
let elements_per_slot = [1, 4, 2, 4][size as usize & 3];
|
||||
ElementLayout {
|
||||
class,
|
||||
size,
|
||||
// Make sure that slot boundaries begin and end on
|
||||
// `COPY_BUFFER_ALIGNMENT`-byte (4-byte) boundaries.
|
||||
elements_per_slot,
|
||||
buffer_usages: class.buffer_usages(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the appropriate [`ElementLayout`] for the given tape's metadata
|
||||
/// data.
|
||||
fn metadata(_tape: &Tape) -> ElementLayout {
|
||||
ElementLayout {
|
||||
class: ElementClass::Metadata,
|
||||
size: size_of::<TapeMetadata>() as u64,
|
||||
elements_per_slot: 1,
|
||||
buffer_usages: ElementClass::Metadata.buffer_usages(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the appropriate [`ElementLayout`] for the given tape's aabb
|
||||
/// data.
|
||||
fn aabb(_tape: &Tape) -> ElementLayout {
|
||||
ElementLayout::new(ElementClass::Aabb, size_of::<Aabb>() as u64)
|
||||
}
|
||||
}
|
||||
|
||||
impl SlabItemLayout for ElementLayout {
|
||||
fn size(&self) -> u64 {
|
||||
self.size
|
||||
}
|
||||
|
||||
fn elements_per_slot(&self) -> u32 {
|
||||
self.elements_per_slot
|
||||
}
|
||||
|
||||
fn buffer_usages(&self) -> BufferUsages {
|
||||
self.buffer_usages
|
||||
}
|
||||
}
|
||||
|
||||
impl ElementClass {
|
||||
/// Returns the `wgpu` [`BufferUsages`] appropriate for a buffer of this
|
||||
/// class.
|
||||
const fn buffer_usages(&self) -> BufferUsages {
|
||||
match *self {
|
||||
ElementClass::Metadata => BufferUsages::STORAGE,
|
||||
ElementClass::Aabb => {
|
||||
BufferUsages::union(BufferUsages::STORAGE, BufferUsages::BLAS_INPUT)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
struct TapeMetadata {
|
||||
/// AABB for decompressing positions.
|
||||
aabb_center: vec3<f32>,
|
||||
pad_a: u32,
|
||||
aabb_half_extents: vec3<f32>,
|
||||
pad_b: u32,
|
||||
};
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* Vaguely analagous to bevy_render::mesh
|
||||
*/
|
||||
pub mod allocator;
|
||||
|
||||
use allocator::TapeAllocatorPlugin;
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_asset::{AssetId, AssetServer, Assets, Handle};
|
||||
use bevy_ecs::{
|
||||
prelude::*,
|
||||
system::{SystemParamItem, lifetimeless::SRes},
|
||||
};
|
||||
use bevy_math::Vec3;
|
||||
use bevy_reflect::Reflect;
|
||||
use bevy_render::{
|
||||
Render, RenderApp, RenderSystems,
|
||||
render_asset::{
|
||||
AssetExtractionError, PrepareAssetError, RenderAsset, RenderAssetPlugin, prepare_assets,
|
||||
},
|
||||
render_resource::{
|
||||
BindGroupLayoutDescriptor, Buffer, CachedComputePipelineId, ComputePipelineDescriptor,
|
||||
PipelineCache, ShaderType,
|
||||
},
|
||||
};
|
||||
use bevy_shader::{Shader, load_shader_library};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use rspirv::dr::Module;
|
||||
|
||||
use crate::{
|
||||
render::allocator::{ElementClass, TapeAllocationKey, TapeAllocator, TapeSlabId},
|
||||
tape::Tape,
|
||||
};
|
||||
|
||||
/// Makes sure that [`Tape`]es are extracted and prepared for the GPU.
|
||||
/// Does *not* add the [`Tape`] as an asset. Use [`TapePlugin`] for that.
|
||||
pub struct TapeRenderAssetPlugin;
|
||||
|
||||
impl Plugin for TapeRenderAssetPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
load_shader_library!(app, "metadata_types.wesl");
|
||||
|
||||
app.add_plugins(RenderAssetPlugin::<RenderTape>::default())
|
||||
.add_plugins(TapeAllocatorPlugin);
|
||||
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
|
||||
render_app.add_systems(
|
||||
Render,
|
||||
prepare_tape_metadata_fallback_buffer
|
||||
.in_set(RenderSystems::PrepareAssets)
|
||||
.after(prepare_assets::<RenderTape>),
|
||||
);
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let mut tape_assets = app.world_mut().resource_mut::<Assets<Tape>>();
|
||||
let handle =
|
||||
tape_assets.add(crate::primitives::sphere::SphereTapeBuilder::build_with_radius(1.0));
|
||||
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
|
||||
render_app.insert_resource(TapeMetadataFallbackTape(handle));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct TapeMetadataFallbackTape(pub Handle<Tape>);
|
||||
|
||||
/// Metadata slab ID and buffer of [`TapeMetadataFallbackTape`],
|
||||
/// used to fill bind group for tape without metadata.
|
||||
#[derive(Resource)]
|
||||
pub struct TapeMetadataFallbackBuffer {
|
||||
pub slab_id: TapeSlabId,
|
||||
pub buffer: Buffer,
|
||||
}
|
||||
|
||||
pub fn prepare_tape_metadata_fallback_buffer(
|
||||
mut commands: Commands,
|
||||
tape_allocator: Res<TapeAllocator>,
|
||||
metadata_fallback_tape: Res<TapeMetadataFallbackTape>,
|
||||
) {
|
||||
let slab_id = tape_allocator
|
||||
.key_to_slab
|
||||
.get(&TapeAllocationKey::new(
|
||||
metadata_fallback_tape.0.id(),
|
||||
ElementClass::Metadata,
|
||||
))
|
||||
.cloned()
|
||||
.unwrap();
|
||||
let buffer = tape_allocator.buffer_for_slab(slab_id).unwrap().clone();
|
||||
commands.insert_resource(TapeMetadataFallbackBuffer { slab_id, buffer });
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Copy, Reflect)]
|
||||
#[reflect(Debug, PartialEq, Clone)]
|
||||
pub struct Aabb {
|
||||
/// The minimum point of the box
|
||||
pub min: Vec3,
|
||||
/// The maximum point of the box
|
||||
pub max: Vec3,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct ReplacementModules {
|
||||
pub enable_gen: Module,
|
||||
pub fuzz: Module,
|
||||
pub normals: Module,
|
||||
pub spatial_texture: Module,
|
||||
pub trace: Module,
|
||||
|
||||
pub enable_gen_layout: BindGroupLayoutDescriptor,
|
||||
pub fuzz_layout: BindGroupLayoutDescriptor,
|
||||
pub spatial_texture_layout: BindGroupLayoutDescriptor,
|
||||
}
|
||||
|
||||
/// Per-tape metadata, stored in [`super::allocator::TapeAllocator`].
|
||||
/// Currently this is used to decompress vertex.
|
||||
#[derive(Default, Pod, Zeroable, Clone, Copy, Debug, ShaderType)]
|
||||
#[repr(C)]
|
||||
pub struct TapeMetadata {
|
||||
// AABB for decompressing positions.
|
||||
pub aabb_center: Vec3,
|
||||
pub pad1: u32,
|
||||
// AABB for decompressing positions.
|
||||
pub aabb_half_extents: Vec3,
|
||||
pub pad2: u32,
|
||||
}
|
||||
|
||||
/// The render world representation of a [`Tape`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RenderTape {
|
||||
pub seed: u64,
|
||||
pub subdivision: u32,
|
||||
|
||||
pub enable_gen: Handle<Shader>,
|
||||
pub fuzz: Handle<Shader>,
|
||||
pub normals: Handle<Shader>,
|
||||
pub spatial_texture: Handle<Shader>,
|
||||
pub trace: Handle<Shader>,
|
||||
|
||||
pub enable_gen_pipeline: CachedComputePipelineId,
|
||||
pub fuzz_pipeline: CachedComputePipelineId,
|
||||
pub spatial_texture_pipeline: CachedComputePipelineId,
|
||||
}
|
||||
|
||||
impl RenderAsset for RenderTape {
|
||||
type Param = (
|
||||
SRes<AssetServer>,
|
||||
SRes<ReplacementModules>,
|
||||
SRes<PipelineCache>,
|
||||
);
|
||||
type SourceAsset = Tape;
|
||||
|
||||
fn take_gpu_data(
|
||||
source: &mut Self::SourceAsset,
|
||||
_previous_gpu_asset: Option<&Self>,
|
||||
) -> Result<Self::SourceAsset, AssetExtractionError> {
|
||||
Ok(source.clone())
|
||||
}
|
||||
|
||||
fn byte_len(_tape: &Self::SourceAsset) -> Option<usize> {
|
||||
// Some(0) // Is this really correct?
|
||||
None
|
||||
}
|
||||
|
||||
/// Converts the extracted tape into a [`RenderTape`].
|
||||
fn prepare_asset(
|
||||
tape: Self::SourceAsset,
|
||||
_tape_id: AssetId<Self::SourceAsset>,
|
||||
(asset_server, replacement_modules, pipeline_cache): &mut SystemParamItem<Self::Param>,
|
||||
_: Option<&Self>,
|
||||
) -> Result<Self, PrepareAssetError<Self::SourceAsset>> {
|
||||
let key = tape.get_tape_key();
|
||||
|
||||
let enable_gen = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.enable_gen.clone(),
|
||||
"enable_gen",
|
||||
));
|
||||
let fuzz = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.fuzz.clone(),
|
||||
"fuzz",
|
||||
));
|
||||
let normals = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.normals.clone(),
|
||||
"normals",
|
||||
));
|
||||
let spatial_texture = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.spatial_texture.clone(),
|
||||
"spatial_texture",
|
||||
));
|
||||
let trace = asset_server.add(tape.sdf_specialize_module_with_key(
|
||||
key,
|
||||
replacement_modules.trace.clone(),
|
||||
"trace",
|
||||
));
|
||||
|
||||
let enable_gen_pipeline =
|
||||
pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
||||
label: Some(format!("bevy_tape_drive::gen_shader::enable_gen::{key}").into()),
|
||||
layout: vec![replacement_modules.enable_gen_layout.clone()],
|
||||
shader: enable_gen.clone(),
|
||||
entry_point: Some("enable_gen_entry".into()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let fuzz_pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
||||
label: Some(format!("bevy_tape_drive::gen_shader::fuzz::{key}").into()),
|
||||
layout: vec![replacement_modules.fuzz_layout.clone()],
|
||||
shader: fuzz.clone(),
|
||||
entry_point: Some("fuzz_entry".into()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let spatial_texture_pipeline =
|
||||
pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
||||
label: Some(format!("bevy_tape_drive::gen_shader::spatial_texture::{key}").into()),
|
||||
layout: vec![replacement_modules.spatial_texture_layout.clone()],
|
||||
shader: spatial_texture.clone(),
|
||||
entry_point: Some("spatial_texture_entry".into()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
Ok(RenderTape {
|
||||
seed: tape.seed,
|
||||
subdivision: tape.subdivision,
|
||||
enable_gen,
|
||||
fuzz,
|
||||
normals,
|
||||
spatial_texture,
|
||||
trace,
|
||||
enable_gen_pipeline,
|
||||
fuzz_pipeline,
|
||||
spatial_texture_pipeline,
|
||||
})
|
||||
}
|
||||
|
||||
fn unload_asset(_tape_id: AssetId<Self::SourceAsset>, (..): &mut SystemParamItem<Self::Param>) {
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user