voxel_cache rewrite 1
This commit is contained in:
@@ -1,2 +1,3 @@
|
||||
// Main common gpu parallel algorithms
|
||||
pub mod buffer_compactor;
|
||||
pub mod radix_sort;
|
||||
|
||||
+89
-1226
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,70 @@
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
|
||||
/// Contains instanciated gpu buffers to hold data for cache attributes
|
||||
pub struct CacheAttributes<const N: usize>
|
||||
{
|
||||
attribute_buffers: Vec<wgpu::Buffer>,
|
||||
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheAttributes<N>
|
||||
{
|
||||
pub fn from_cache_layout(device: &wgpu::Device, layout: &CacheLayout, page_count: usize)
|
||||
-> Self
|
||||
{
|
||||
let attribute_buffers = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.create_buffer(device, N, page_count))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheAttributes::bind_group_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: Some(
|
||||
std::num::NonZero::new(attribute_buffers.len() as u32)
|
||||
.expect("Cannot create cache attributes with no attributes"),
|
||||
),
|
||||
}],
|
||||
});
|
||||
|
||||
let bind_group_bindings = attribute_buffers
|
||||
.iter()
|
||||
.map(|buffer| buffer.as_entire_buffer_binding())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheAttributes::bind_group"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::BufferArray(&bind_group_bindings),
|
||||
}],
|
||||
});
|
||||
|
||||
CacheAttributes {
|
||||
attribute_buffers,
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout
|
||||
{
|
||||
&self.bind_group_layout
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use wgpu::Buffer;
|
||||
|
||||
use crate::sparse_tree::Color;
|
||||
|
||||
#[derive(Clone, Copy, Zeroable, Pod, Debug)]
|
||||
#[repr(C)]
|
||||
pub struct CacheNodeRequest
|
||||
{
|
||||
// Requested ressource
|
||||
pub structure_id: u32,
|
||||
pub structure_locator: u32,
|
||||
|
||||
// Write back info
|
||||
pub node_index: u32,
|
||||
pub child_index: u32,
|
||||
}
|
||||
|
||||
pub struct RequestBufferElement<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
request_count: [u32; N * N * N],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct StructurePoolElement<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub occupancy_low: u32,
|
||||
pub occupancy_high: u32,
|
||||
pub pointers: [StructurePointer; N * N * N],
|
||||
}
|
||||
|
||||
pub struct DestinationElement
|
||||
{
|
||||
pub node: u32,
|
||||
pub child: u32,
|
||||
}
|
||||
|
||||
pub struct ColorBytes(pub u8, pub u8, pub u8, pub u8);
|
||||
|
||||
impl From<Color> for ColorBytes
|
||||
{
|
||||
fn from(value: Color) -> Self
|
||||
{
|
||||
Self(
|
||||
(value.0 * 255.) as u8,
|
||||
(value.1 * 255.) as u8,
|
||||
(value.2 * 255.) as u8,
|
||||
(value.3 * 255.) as u8,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ColorPoolElement<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
colors: [ColorBytes; N * N * N],
|
||||
}
|
||||
|
||||
pub struct LocationPoolElement
|
||||
{
|
||||
pub structure_id: u32,
|
||||
pub structure_locator: u32,
|
||||
}
|
||||
|
||||
pub struct CacheResponse
|
||||
{
|
||||
// Each buffer contains the same amount of elements (structure of arrays style)
|
||||
|
||||
// Cache data to bring in
|
||||
pub structure_nodes: Buffer,
|
||||
pub color_nodes: Buffer,
|
||||
pub locations: Buffer,
|
||||
|
||||
// Which nodes this extends : node_index + child_index
|
||||
pub parents: Buffer,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
#[repr(transparent)]
|
||||
pub struct StructurePointer(pub u32);
|
||||
|
||||
impl StructurePointer
|
||||
{
|
||||
pub fn new(subdivided: bool, occupied: bool) -> Self
|
||||
{
|
||||
StructurePointer(((subdivided as u32) << 31) | ((occupied as u32) << 30))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct ExplicitNTreeNode<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub structure: [StructurePointer; N * N * N],
|
||||
pub colors: [Color; N * N * N],
|
||||
pub normals: [(f32, f32, f32); N * N * N],
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/// Contains structure and logic related to eviction logic in the cache.
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::include_wgsl;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::radix_sort;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::{self};
|
||||
use crate::voxel_cache::CacheRessources;
|
||||
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
|
||||
|
||||
/// Retains usage information about pages in the cache under the form of timestamps.
|
||||
/// Produces a list of LRU eviction order, from which the cache can pull pages to recycle
|
||||
pub struct CacheEvictor
|
||||
{
|
||||
page_count: usize,
|
||||
|
||||
/// Contains a u32 timestamp per page, so that we know when a page was last used
|
||||
timestamp_pages: wgpu::Buffer,
|
||||
|
||||
/// Contains indices in LRU order, after sorting
|
||||
lru_list: wgpu::Buffer,
|
||||
|
||||
// Reset lru list pass
|
||||
reset_lru_list_bind_group: BindGroup,
|
||||
reset_lru_list_pass: ComputePipeline,
|
||||
reset_lru_list_dispatch: u32,
|
||||
}
|
||||
|
||||
impl CacheEvictor
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, page_count: usize, initial_timestamp: u32) -> Self
|
||||
{
|
||||
let timestamp_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheUsage::timestamp_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![initial_timestamp; page_count]),
|
||||
});
|
||||
|
||||
let lru_list = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheUsage::lru_list"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
size: (page_count * size_of::<u32>()) as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let (reset_lru_list_bg_layout, reset_lru_list_bind_group) =
|
||||
create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
[lru_list],
|
||||
Some("CacheEvictor::reset_lru_list_bind_group"),
|
||||
);
|
||||
|
||||
let reset_lru_list_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("CacheEvictor::reset_lru_list_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&reset_lru_list_bg_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let reset_lru_list_pass =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheEvictor::reset_lru_list_pass"),
|
||||
layout: Some(&reset_lru_list_pipeline_layout),
|
||||
module: &device.create_shader_module(include_wgsl!("./shaders/eviction.wgsl")),
|
||||
entry_point: Some("reset_lru_list"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
page_count,
|
||||
timestamp_pages,
|
||||
lru_list,
|
||||
|
||||
reset_lru_list_bind_group,
|
||||
reset_lru_list_pass,
|
||||
reset_lru_list_dispatch: page_count.div_ceil(256) as u32,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prepare_eviction_list<const N: usize>(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
ressources: &CacheRessources<N>,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "CacheEvictor::prepare_eviction_list");
|
||||
// Use the scratch buffer as the sort work buffer
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.timestamp_pages,
|
||||
0,
|
||||
&ressources.scratch_buffer,
|
||||
0,
|
||||
self.timestamp_pages.size(),
|
||||
);
|
||||
|
||||
// Reset lru list
|
||||
{
|
||||
let mut reset_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("CacheEvictor::reset_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
reset_pass.set_bind_group(0, Some(&self.reset_lru_list_bind_group), &[]);
|
||||
reset_pass.set_pipeline(&self.reset_lru_list_pass);
|
||||
reset_pass.dispatch_workgroups(self.reset_lru_list_dispatch, 1, 1);
|
||||
}
|
||||
|
||||
ressources.radix_sorter.sort(
|
||||
device,
|
||||
&ressources.scratch_buffer,
|
||||
&self.lru_list,
|
||||
None,
|
||||
Some(self.page_count),
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Ascending,
|
||||
);
|
||||
}
|
||||
}
|
||||
+55
-77
@@ -1,94 +1,72 @@
|
||||
#[derive(Clone, PartialEq, Eq, Default)]
|
||||
pub struct VoxelCacheLayout
|
||||
{
|
||||
pub(super) attributes: Vec<VoxelCacheAttribute>,
|
||||
}
|
||||
use wgpu::BufferUsages;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum VoxelCacheAttributeRate
|
||||
/// Defines how a [`VoxelCache`]'s attribute is populated upon populating a page
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum CacheAttributeInit
|
||||
{
|
||||
/// Attribute is per page
|
||||
Page,
|
||||
/// Attribute is external : it is copied from the insertion operation
|
||||
External,
|
||||
|
||||
/// Attribute is per pointer in pages
|
||||
Pointer,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum VoxelCacheAttributeInit
|
||||
{
|
||||
Copy,
|
||||
/// Attribute will not be touched by the cache mechanism. It is left to the discrecy of the
|
||||
/// cache user.
|
||||
///
|
||||
/// Some applications requires pieces of data into the resident data of the cache that are
|
||||
/// computed on the fly : e.g. global illumination
|
||||
DontTouch,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub struct VoxelCacheAttribute
|
||||
/// Describes an attribute of a [`VoxelCache`]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CacheAttribute
|
||||
{
|
||||
pub label: Option<&'static str>,
|
||||
pub word_count: u32,
|
||||
pub rate: VoxelCacheAttributeRate,
|
||||
pub init: VoxelCacheAttributeInit,
|
||||
pub init: CacheAttributeInit,
|
||||
}
|
||||
|
||||
impl VoxelCacheLayout
|
||||
impl CacheAttribute
|
||||
{
|
||||
pub fn add_attribute(&mut self, attribute: VoxelCacheAttribute) -> usize
|
||||
/// Creates the wgpu buffer necessary to store this attribute in the cache
|
||||
pub fn create_buffer(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
child_count: usize,
|
||||
page_count: usize,
|
||||
) -> wgpu::Buffer
|
||||
{
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(
|
||||
format!(
|
||||
"VoxelCacheAttribute ({}) {} word(s)",
|
||||
self.label.unwrap_or("no-name"),
|
||||
self.word_count
|
||||
)
|
||||
.as_str(),
|
||||
),
|
||||
size: (self.word_count as usize * page_count * child_count) as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct CacheLayout
|
||||
{
|
||||
pub(super) attributes: Vec<CacheAttribute>,
|
||||
}
|
||||
|
||||
impl CacheLayout
|
||||
{
|
||||
/// Adds a new [`VoxelCacheAttribute`] in the layout
|
||||
///
|
||||
/// Attributes are added starting from 0 counting up
|
||||
///
|
||||
/// Returns the index of the new added attirbute
|
||||
pub fn add_attribute(&mut self, attribute: CacheAttribute) -> usize
|
||||
{
|
||||
let index = self.attributes.len();
|
||||
self.attributes.push(attribute);
|
||||
index
|
||||
}
|
||||
|
||||
pub fn attributes(&self) -> &[VoxelCacheAttribute]
|
||||
{
|
||||
&self.attributes
|
||||
}
|
||||
}
|
||||
|
||||
impl VoxelCacheAttribute
|
||||
{
|
||||
pub fn wgsl_copy_loop(
|
||||
&self,
|
||||
source_array: &str,
|
||||
dest_array: &str,
|
||||
|
||||
source_page_index: &str,
|
||||
dest_page_index: &str,
|
||||
|
||||
child_count: usize,
|
||||
attribute_index: usize,
|
||||
) -> String
|
||||
{
|
||||
match self.init
|
||||
{
|
||||
VoxelCacheAttributeInit::Copy =>
|
||||
{
|
||||
let real_child_count = match self.rate
|
||||
{
|
||||
VoxelCacheAttributeRate::Page => 1,
|
||||
VoxelCacheAttributeRate::Pointer => child_count,
|
||||
};
|
||||
let word_count = self.word_count;
|
||||
let node_size = real_child_count * word_count as usize;
|
||||
format!(
|
||||
"
|
||||
// Iterate on every children
|
||||
for(var i = 0u; i < {real_child_count}; i++){{
|
||||
|
||||
// Iterate on every word of the attribute
|
||||
for(var j = 0u; j < {word_count}; j++){{
|
||||
|
||||
// Offset within child
|
||||
let offset = i * {word_count} + j;
|
||||
|
||||
{source_array}[{attribute_index}].values[{source_page_index} * {node_size} + offset]
|
||||
= {dest_array}[{attribute_index}].values[{dest_page_index} * {node_size} + offset];
|
||||
}}
|
||||
}}
|
||||
|
||||
"
|
||||
)
|
||||
}
|
||||
VoxelCacheAttributeInit::DontTouch => String::from("// Attribute is DontTouch"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,390 +0,0 @@
|
||||
// The cache emits requests, and receives answer to these requests
|
||||
// The cache producer interface provides the necessary buffers to contains
|
||||
// these, so that use applications can fullfill the requests
|
||||
|
||||
use std::num::NonZero;
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupEntry;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::BindGroupLayoutEntry;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::Device;
|
||||
use wgpu::Queue;
|
||||
use wgpu::util::DownloadBuffer;
|
||||
|
||||
use crate::voxel_cache::VoxelAttribute;
|
||||
use crate::voxel_cache::data::ColorPoolElement;
|
||||
use crate::voxel_cache::data::LocationPoolElement;
|
||||
use crate::voxel_cache::data::StructurePoolElement;
|
||||
use crate::voxel_cache::layout::VoxelCacheAttribute;
|
||||
use crate::voxel_cache::layout::VoxelCacheLayout;
|
||||
|
||||
#[derive(Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct CacheRequest
|
||||
{
|
||||
pub structure_id: u32,
|
||||
pub locator: u32,
|
||||
pub child_index: u32,
|
||||
}
|
||||
|
||||
pub(super) struct CacheRequestWbInfo
|
||||
{
|
||||
node_index: u32,
|
||||
child_index: u32,
|
||||
}
|
||||
|
||||
pub struct CacheProducerInterface<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
// Request emissions
|
||||
pub(super) size: usize,
|
||||
|
||||
// Contains the specific node being requested
|
||||
pub(super) requests: Buffer,
|
||||
|
||||
// Contains how many request have effectively been emitted
|
||||
pub(super) request_count: Buffer,
|
||||
|
||||
// Contains on which node the request was done
|
||||
pub(super) requests_wb_info: Buffer,
|
||||
// Request fullfillment
|
||||
pub(super) structure_nodes: Buffer,
|
||||
pub(super) attributes_nodes: Vec<Buffer>,
|
||||
pub(super) location_nodes: Buffer,
|
||||
|
||||
pub(super) request_side_bind_group_layout: BindGroupLayout,
|
||||
pub(super) request_side_bind_group: BindGroup,
|
||||
|
||||
pub(super) producer_side_bind_group_layout: BindGroupLayout,
|
||||
pub(super) producer_side_bind_group: BindGroup,
|
||||
}
|
||||
impl<const N: usize> CacheProducerInterface<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(size: usize, device: &Device, layout: &VoxelCacheLayout) -> Self
|
||||
{
|
||||
let requests = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_request_buffer"),
|
||||
size: (size_of::<CacheRequest>() * size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let requests_wb_info = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_writeback_info"),
|
||||
size: (size_of::<CacheRequestWbInfo>() * size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let structure_nodes = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_structure_nodes"),
|
||||
size: (size_of::<StructurePoolElement<N>>() * size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// Create attributes
|
||||
let attributes_nodes = layout
|
||||
.attributes()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, x)| {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(format!("VoxelCache<{N}>::attributes[{i}]").as_str()),
|
||||
size: ((x.word_count as usize) * N * N * N * size * size_of::<u32>()) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let location_nodes = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_structure_nodes"),
|
||||
size: (size_of::<LocationPoolElement>() * size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let request_count = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_request_count"),
|
||||
size: (size_of::<u32>()) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let request_side_bind_group_layout =
|
||||
Self::request_side_bind_group_layout(device, layout.attributes());
|
||||
let producer_side_bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("cache_interface_producer_side_bind_group_layout"),
|
||||
entries: &[
|
||||
// Reqests
|
||||
BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Request count
|
||||
BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Structure nodes
|
||||
BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Attributes nodes
|
||||
BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: Some(NonZero::new(layout.attributes().len() as u32).unwrap()),
|
||||
},
|
||||
// Location nodes
|
||||
BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Bind groups
|
||||
let attributes_bindings = attributes_nodes
|
||||
.iter()
|
||||
.map(|x| x.as_entire_buffer_binding())
|
||||
.collect::<Vec<wgpu::BufferBinding<'_>>>();
|
||||
let request_side_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("cache_interface_request_side_bind_group"),
|
||||
layout: &request_side_bind_group_layout,
|
||||
entries: &[
|
||||
BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: requests.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: requests_wb_info.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: request_count.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: structure_nodes.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 5,
|
||||
resource: location_nodes.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let producer_side_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("cache_interface_producer_side_bind_group"),
|
||||
layout: &producer_side_bind_group_layout,
|
||||
entries: &[
|
||||
BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: requests.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: request_count.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: structure_nodes.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: location_nodes.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Self {
|
||||
size,
|
||||
requests,
|
||||
request_count,
|
||||
requests_wb_info,
|
||||
structure_nodes,
|
||||
attributes_nodes,
|
||||
location_nodes,
|
||||
|
||||
request_side_bind_group_layout,
|
||||
request_side_bind_group,
|
||||
producer_side_bind_group_layout,
|
||||
producer_side_bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn requests_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.requests
|
||||
}
|
||||
|
||||
pub fn structure_nodes_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.structure_nodes
|
||||
}
|
||||
|
||||
pub fn attributes_buffers(&self) -> &[Buffer]
|
||||
{
|
||||
&self.attributes_nodes
|
||||
}
|
||||
|
||||
pub fn location_nodes_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.location_nodes
|
||||
}
|
||||
|
||||
pub fn total_request_count(&self, device: &Device, queue: &Queue) -> u32
|
||||
{
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(1);
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&self.request_count.slice(0..),
|
||||
move |download_buffer| {
|
||||
let vec = download_buffer.unwrap().to_vec();
|
||||
let value = u32::from_ne_bytes(std::array::from_fn(|i| vec[i]));
|
||||
let _ = tx.try_send(value);
|
||||
},
|
||||
);
|
||||
|
||||
loop
|
||||
{
|
||||
if let Ok(value) = rx.try_recv()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
device.poll(wgpu::wgt::PollType::Poll).unwrap();
|
||||
}
|
||||
|
||||
//panic!("Could not retrieve total request count.");
|
||||
}
|
||||
|
||||
pub fn request_side_bind_group_layout(
|
||||
device: &Device,
|
||||
attributes: &[VoxelCacheAttribute],
|
||||
) -> BindGroupLayout
|
||||
{
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("cache_interface_request_side_bind_group_layout"),
|
||||
entries: &[
|
||||
// Reqests
|
||||
BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Requests writeback
|
||||
BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Request count
|
||||
BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Structure nodes
|
||||
BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Attributes nodes
|
||||
BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: Some(NonZero::new(attributes.len() as u32).unwrap()),
|
||||
},
|
||||
// Location nodes
|
||||
BindGroupLayoutEntry {
|
||||
binding: 5,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,296 +0,0 @@
|
||||
use bytemuck::bytes_of;
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupEntry;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::ShaderStages;
|
||||
|
||||
use crate::gpu::radix_sort;
|
||||
use crate::gpu::radix_sort::RadixSorter;
|
||||
use crate::voxel_cache::data::RequestBufferElement;
|
||||
use crate::voxel_cache::indirect_buffer::NonZeroBufferCompactor;
|
||||
|
||||
pub struct RequestBuffer<const N: usize>
|
||||
{
|
||||
pub device: Device,
|
||||
pub cache_size: usize,
|
||||
|
||||
pub request_buffer: Buffer,
|
||||
pub keys_buffer: Buffer,
|
||||
pub index_buffer: Buffer,
|
||||
|
||||
pub request_count: Buffer,
|
||||
|
||||
pub sorter: RadixSorter,
|
||||
pub buffer_compactor: NonZeroBufferCompactor,
|
||||
pub bindgroup: BindGroup,
|
||||
pub reset_pass: ComputePipeline,
|
||||
pub copy_pass: ComputePipeline,
|
||||
}
|
||||
|
||||
impl<const N: usize> RequestBuffer<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(cache_size: usize, device: Device) -> Self
|
||||
{
|
||||
let buffer_sizes = (size_of::<u32>() * cache_size * N * N * N) as u64;
|
||||
// Contains request counts
|
||||
let request_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(format!("request_buffer_{N}").as_str()),
|
||||
size: buffer_sizes,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// Contains indices compacted by compactor, and later sorted
|
||||
let index_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(format!("request_index_buffer_{N}").as_str()),
|
||||
size: buffer_sizes,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// Used as keys for the sorter
|
||||
let keys_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(format!("request_sort_buffer_{N}").as_str()),
|
||||
size: buffer_sizes,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// Amount of requests produced by non zero compactor
|
||||
let request_count = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("request_count_storage_buffer"),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC | BufferUsages::COPY_DST,
|
||||
size: size_of::<u32>() as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("RequestCount::bindgroup_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let bindgroup = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("RequestCount::bindgroup"),
|
||||
layout: &bindgroup_layout,
|
||||
entries: &[
|
||||
BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: request_buffer.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: index_buffer.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: keys_buffer.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: request_count.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layouts = &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("request_buffer_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bindgroup_layout)],
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let reset_pass =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("RequestBuffer::reset_pass"),
|
||||
layout: Some(pipeline_layouts),
|
||||
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("RequestBuffer::reset_pass_module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
#[allow(clippy::useless_format)]
|
||||
format!("
|
||||
@group(0) @binding(0) var<storage, read_write> request_buffer: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> index_buffer: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> keys_buffer: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> request_count: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
let total = arrayLength(&request_buffer);
|
||||
if(global_invocation_id.x >= total) {{return;}}
|
||||
request_buffer[global_invocation_id.x] = 0;
|
||||
}}
|
||||
")
|
||||
.into(),
|
||||
),
|
||||
}),
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
// This pipeline handles copying the request counts into the key buffer
|
||||
// according to the compacted index_buffer
|
||||
let copy_pass =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("RequestBuffer::copy_pass"),
|
||||
layout: Some(pipeline_layouts),
|
||||
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("RequestBuffer::copy_pass_module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
#[allow(clippy::useless_format)]
|
||||
format!("
|
||||
@group(0) @binding(0) var<storage, read_write> request_buffer: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> index_buffer: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> keys_buffer: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> request_count: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
if(global_invocation_id.x >= request_count) {{return;}}
|
||||
keys_buffer[global_invocation_id.x] = request_buffer[index_buffer[global_invocation_id.x]];
|
||||
}}
|
||||
")
|
||||
.into(),
|
||||
),
|
||||
}),
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
cache_size,
|
||||
request_buffer,
|
||||
index_buffer,
|
||||
keys_buffer,
|
||||
request_count,
|
||||
reset_pass,
|
||||
copy_pass,
|
||||
bindgroup,
|
||||
buffer_compactor: NonZeroBufferCompactor::new(&device, cache_size * N * N * N),
|
||||
sorter: RadixSorter::new(&device, cache_size * N * N * N),
|
||||
device,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn request_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.request_buffer
|
||||
}
|
||||
|
||||
pub fn request_count_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.request_count
|
||||
}
|
||||
|
||||
pub fn index_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.index_buffer
|
||||
}
|
||||
|
||||
pub fn reset_requests(&self, encoder: &mut CommandEncoder)
|
||||
{
|
||||
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("request_buffer_reset_compute_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]);
|
||||
compute_pass.set_pipeline(&self.reset_pass);
|
||||
|
||||
let shader_invocations = self.cache_size * N * N * N; // one invocation per element
|
||||
let workgroup_invocations = shader_invocations.div_ceil(256);
|
||||
compute_pass.dispatch_workgroups(workgroup_invocations as u32, 1, 1);
|
||||
}
|
||||
|
||||
pub fn sort_requests(&self, encoder: &mut CommandEncoder)
|
||||
{
|
||||
// Compact list
|
||||
self.buffer_compactor.compact_buffer(
|
||||
&self.device,
|
||||
encoder,
|
||||
&self.request_buffer,
|
||||
&self.index_buffer,
|
||||
None,
|
||||
);
|
||||
|
||||
self.buffer_compactor
|
||||
.copy_count_to_buffer(encoder, &self.request_count);
|
||||
|
||||
let mut copy_keys_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("RequestBuffer::copy_keys_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
copy_keys_pass.set_bind_group(0, Some(&self.bindgroup), &[]);
|
||||
copy_keys_pass.set_pipeline(&self.copy_pass);
|
||||
let shader_invocations = self.cache_size * N * N * N; // one invocation per element
|
||||
let workgroup_invocations = shader_invocations.div_ceil(256) as u32;
|
||||
copy_keys_pass.dispatch_workgroups(workgroup_invocations, 1, 1);
|
||||
drop(copy_keys_pass);
|
||||
|
||||
self.sorter.sort(
|
||||
&self.device,
|
||||
&self.keys_buffer,
|
||||
&self.index_buffer,
|
||||
Some(&self.request_count),
|
||||
None,
|
||||
encoder,
|
||||
radix_sort::RadixSortDirection::Descending,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::include_wgsl;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::buffer_compactor::NonZeroBufferCompactor;
|
||||
use crate::gpu::radix_sort::{self};
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::{self};
|
||||
use crate::voxel_cache::CacheRessources;
|
||||
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
|
||||
use crate::voxel_cache::schema::RequestInformation;
|
||||
use crate::voxel_cache::schema::RequestMeta;
|
||||
|
||||
/// Records, handles, and produces a list of requested data inside the cache
|
||||
pub struct CacheRequestHandler<const N: usize>
|
||||
{
|
||||
/// Contains a u32 per pointer of the cache, that records an amount of request by the cache user.
|
||||
/// This can then be used to prioritize request based on demand
|
||||
request_counts_pages: wgpu::Buffer,
|
||||
|
||||
// Ultimately contains sorted requests
|
||||
sorted_requests: wgpu::Buffer,
|
||||
|
||||
compactor: NonZeroBufferCompactor,
|
||||
|
||||
// Pass to reset the requests
|
||||
reset_pass_bind_group: BindGroup,
|
||||
reset_pass: ComputePipeline,
|
||||
reset_pass_dispatch: u32,
|
||||
}
|
||||
|
||||
/// Records requests made by the cache
|
||||
pub struct CacheRequestBuffer
|
||||
{
|
||||
pub max_requests: usize,
|
||||
|
||||
/// Buffer containing the amount of requests made by the cache, under max requsets
|
||||
pub request_count: wgpu::Buffer,
|
||||
|
||||
/// Buffer containing the requsets made by the cache, a dense array of [`voxel_cache::schema::RequestInformation`]
|
||||
pub request_informations: wgpu::Buffer,
|
||||
|
||||
/// Buffer containing the meta information about the requests, a dense array of [`voxel_cache::schema::RequestMeta`]
|
||||
request_meta: wgpu::Buffer,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheRequestHandler<N>
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, page_count: usize) -> Self
|
||||
{
|
||||
let request_counts_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::request_counts_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]),
|
||||
});
|
||||
|
||||
let sorted_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::sorted_requests"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]),
|
||||
});
|
||||
|
||||
let (reset_pass_bg_layout, reset_pass_bind_group) = create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
[request_counts_pages],
|
||||
Some("CacheRequestHandler::reset_pass_bind_group"),
|
||||
);
|
||||
|
||||
let reset_pass_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("CacheRequestHandler::reset_pass_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&reset_pass_bg_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let reset_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheRequestHandler::reset_pass"),
|
||||
layout: Some(&reset_pass_pipeline_layout),
|
||||
module: &device.create_shader_module(include_wgsl!("./shaders/requests.wgsl")),
|
||||
entry_point: Some("reset_requests"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
request_counts_pages,
|
||||
sorted_requests,
|
||||
compactor: NonZeroBufferCompactor::new(device, page_count),
|
||||
|
||||
reset_pass_bind_group,
|
||||
reset_pass,
|
||||
reset_pass_dispatch: (page_count as u32).div_ceil(256),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sorts the requests currently held by the request handler in order to process them.
|
||||
///
|
||||
/// Uses both the sorter and the scratch buffer in the ressources
|
||||
///
|
||||
/// The `request_count` buffer will contain the amount of request produced this time.
|
||||
pub fn sort_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
ressources: &CacheRessources<N>,
|
||||
request_count: &wgpu::Buffer,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "RequestHandler::sort_requests");
|
||||
|
||||
// First perform a fast compaction sort
|
||||
self.compactor.compact_buffer(
|
||||
device,
|
||||
&mut encoder,
|
||||
&self.request_counts_pages,
|
||||
&self.sorted_requests,
|
||||
Some(&ressources.scratch_buffer),
|
||||
);
|
||||
|
||||
self.compactor
|
||||
.copy_count_to_buffer(&mut encoder, request_count);
|
||||
|
||||
// State:
|
||||
// At this point the `sorted_requests` buffer contains the compacted indices of the request counts
|
||||
// and the scratch buffer contains the associated values
|
||||
|
||||
// The indices can now be sorted using `sorted_requests` as values and
|
||||
// `ressources.scratch_buffer` as keys for a sort operation
|
||||
|
||||
// We use the amount of non zero request as the indirect count so that we can sort only the
|
||||
// compacted, non-null requests
|
||||
ressources.radix_sorter.sort(
|
||||
device,
|
||||
&ressources.scratch_buffer,
|
||||
&self.sorted_requests,
|
||||
Some(request_count),
|
||||
None,
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Descending,
|
||||
);
|
||||
}
|
||||
|
||||
/// Resets the RequestHandlers request buffer for a next cache usage.
|
||||
pub fn reset(&self, encoder: &mut ScopeEncoder<CommandEncoder>)
|
||||
{
|
||||
let mut compute_pass = encoder.begin_profiled_compute_pass("CacheRequestHandler::reset");
|
||||
|
||||
compute_pass.set_bind_group(0, Some(&self.reset_pass_bind_group), &[]);
|
||||
compute_pass.set_pipeline(&self.reset_pass);
|
||||
compute_pass.dispatch_workgroups(self.reset_pass_dispatch, 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheRequestBuffer
|
||||
{
|
||||
/// Creates a request buffer that can contain at most `max_amount` requests
|
||||
pub fn new(device: &Device, max_requests: usize) -> Self
|
||||
{
|
||||
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestBuffer::request_count"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::bytes_of(&0u32),
|
||||
});
|
||||
|
||||
let request_informations = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheRequestBuffer::request_informations"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
size: (size_of::<RequestInformation>() * max_requests) as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let request_meta = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheRequestBuffer::request_meta"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
size: (size_of::<RequestMeta>() * max_requests) as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
Self {
|
||||
max_requests,
|
||||
request_count,
|
||||
request_informations,
|
||||
request_meta,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
|
||||
/// Contains definitions of the data layouts for the cache
|
||||
|
||||
/// CachePointer represents a pointer in the [`VoxelCache`]
|
||||
///
|
||||
/// Pointers are used in the structure pool of the cache and encodes the N-tree itself
|
||||
///
|
||||
/// Three states are possible :
|
||||
///
|
||||
/// - unsubdivisable: This children of the node cannot be subdivided further
|
||||
/// - subdivisable: This children of the node can be subdivided further ...
|
||||
/// - unavailable: ... but is not currently available in the cache
|
||||
/// - available: ... is currently available in the cache and the pointer is valid
|
||||
///
|
||||
///
|
||||
/// The layout is the following
|
||||
///
|
||||
/// - bit 31: subdivisable?
|
||||
/// - bit 30: available?
|
||||
/// - bit 0..29: pointer (only relevant if available is 1)
|
||||
///
|
||||
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct CachePointer(u32);
|
||||
|
||||
impl CachePointer
|
||||
{
|
||||
/// First option represents subdivisability
|
||||
/// Second option represents availability
|
||||
///
|
||||
/// None -> unsubdivisable
|
||||
/// Some(None) -> subdivisable not available
|
||||
/// Some(Some(ptr)) -> subdivisable, available a pointer ptr
|
||||
pub fn new(value: Option<Option<u32>>) -> Self
|
||||
{
|
||||
CachePointer(match value
|
||||
{
|
||||
Some(available) => match available
|
||||
{
|
||||
Some(pointer) =>
|
||||
{
|
||||
assert_eq!(
|
||||
pointer >> 30,
|
||||
0,
|
||||
"Provided pointer is to big and does not fit in CachePointer. Last two bits must be null."
|
||||
);
|
||||
(1 << 31) | (1 << 30) | pointer
|
||||
}
|
||||
None => 1 << 31,
|
||||
},
|
||||
None => 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn as_option(&self) -> Option<Option<u32>>
|
||||
{
|
||||
let subdivisable = (self.0 >> 31) != 0;
|
||||
let available = ((self.0 >> 30) & 1) != 0;
|
||||
let pointer = self.0 & 0x3FFFFFFF;
|
||||
|
||||
match (subdivisable, available)
|
||||
{
|
||||
(false, true) => panic!("Invalid cache pointer. (not subdivisable and available)"),
|
||||
(false, _) if pointer != 0 =>
|
||||
{
|
||||
panic!("Invalid cache pointer. (non null unsubdivisable pointer)")
|
||||
}
|
||||
(false, _) => None,
|
||||
(true, false) => Some(None),
|
||||
(true, true) => Some(Some(pointer)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u32> for CachePointer
|
||||
{
|
||||
fn from(value: u32) -> Self
|
||||
{
|
||||
CachePointer(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pages encoding the structure of the trees in the cache.
|
||||
/// Occupancy mask is a mask containing a bit per children, based on whether it can be skipped
|
||||
/// during raytracing. This can help faster tracing, and coalesce skips.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
#[repr(C)]
|
||||
pub struct StructurePage<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub occupancy_mask: u64,
|
||||
pub pointers: [CachePointer; N * N * N],
|
||||
}
|
||||
|
||||
/// Data stored alongside cache structure so that application can locate a
|
||||
/// particular request
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct LocationPage
|
||||
{
|
||||
/// Identifier for the structure to which the node pertains
|
||||
pub structure_id: u32,
|
||||
|
||||
/// Identifier for locating this particular node within the structure
|
||||
pub node_id: u32,
|
||||
}
|
||||
|
||||
/// Page storing the depth of the current node related to its root.
|
||||
/// - 0xFFFFFFFF: Page unused
|
||||
/// - 0..0xFFFFFFFF(excl): Depth
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct DepthPage(pub u32);
|
||||
|
||||
impl DepthPage
|
||||
{
|
||||
pub const PAGE_UNUSED: Self = DepthPage(u32::MAX);
|
||||
}
|
||||
|
||||
/// When the cache requests some information, it produces this structure,
|
||||
/// which contains the node on which a subdivision is requested, as well which particular
|
||||
/// children is needed
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct RequestInformation
|
||||
{
|
||||
/// Identifier for the structure to which the node pertains
|
||||
pub structure_id: u32,
|
||||
|
||||
/// Identifier for locating this particular node within the structure
|
||||
pub node_id: u32,
|
||||
|
||||
/// The index of the children on which the request was issued
|
||||
pub children_index: u32,
|
||||
}
|
||||
|
||||
/// Metainformation kept along each request, to know which node made the demand
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct RequestMeta
|
||||
{
|
||||
/// The page on which the request was issued, with the special value 0xFFFFFFFF if the request
|
||||
/// is external
|
||||
pub page_index: u32,
|
||||
|
||||
/// The children on which the request was issued
|
||||
pub children_index: u32,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
@group(0) @binding(0) lru_list: array<u32>;
|
||||
|
||||
/// Resets the lru list
|
||||
@compute
|
||||
@workgroups(256, 1, 1)
|
||||
fn reset_lru_list(@builting(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
{
|
||||
let index = global_invocation_id.x;
|
||||
if(index >= array_length(&request_count_pages))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Indicies must be reset to id, so that the sort operation can use them as values,
|
||||
// and the timestamps as keys
|
||||
request_count_pages = index;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
@group(0) @binding(0) request_count_pages: array<u32>;
|
||||
|
||||
/// Resets the requests
|
||||
@compute
|
||||
@workgroups(256, 1, 1)
|
||||
fn reset_requests(@builting(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
{
|
||||
let index = global_invocation_id.x;
|
||||
if(index >= array_length(&request_count_pages))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
request_count_pages = 0;
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::voxel_cache::schema::DepthPage;
|
||||
use crate::voxel_cache::schema::StructurePage;
|
||||
|
||||
/// Contains the instanciated buffers relevant to the structure of the trees
|
||||
pub struct CacheStructure<const N: usize>
|
||||
{
|
||||
pointer_pages: Buffer,
|
||||
location_pages: Buffer,
|
||||
depth_pages: Buffer,
|
||||
|
||||
bind_group_layout: BindGroupLayout,
|
||||
bind_group: BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheStructure<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub const POINTER_PAGES_BINDING: u32 = 0;
|
||||
pub const LOCATION_PAGES_BINDING: u32 = 1;
|
||||
pub const DEPTH_PAGES_BINDING: u32 = 2;
|
||||
|
||||
pub fn new(device: &wgpu::Device, page_count: usize) -> Self
|
||||
{
|
||||
let pointer_pages = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheStructure::pointer_pages"),
|
||||
size: (size_of::<StructurePage<N>>() * page_count) as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let location_pages = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheStructure::location_pages"),
|
||||
size: (size_of::<StructurePage<N>>() * page_count) as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// Depth pages need to be initialized to unused, this prioritizes them in the
|
||||
// depth sort used in the eviction pass
|
||||
let depth_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheStructure::location_pages"),
|
||||
usage: BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![DepthPage::PAGE_UNUSED; page_count]),
|
||||
});
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheStructure::bind_group_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: Self::POINTER_PAGES_BINDING,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: Self::LOCATION_PAGES_BINDING,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: Self::DEPTH_PAGES_BINDING,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheStructure::bind_group"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: Self::POINTER_PAGES_BINDING,
|
||||
resource: pointer_pages.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: Self::LOCATION_PAGES_BINDING,
|
||||
resource: pointer_pages.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: Self::DEPTH_PAGES_BINDING,
|
||||
resource: pointer_pages.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
CacheStructure {
|
||||
pointer_pages,
|
||||
location_pages,
|
||||
depth_pages,
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bind_group_layout(&self) -> &BindGroupLayout
|
||||
{
|
||||
&self.bind_group_layout
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
use std::num::NonZero;
|
||||
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::Device;
|
||||
use wgpu::Queue;
|
||||
use wgpu::util::StagingBelt;
|
||||
|
||||
use crate::voxel_cache::data::StructurePointer;
|
||||
use crate::voxel_cache::request_buffer::RequestBuffer;
|
||||
|
||||
// Stores root pointers to the cache
|
||||
pub struct StructureTable
|
||||
{
|
||||
pub(crate) device: Device,
|
||||
pub(crate) queue: Queue,
|
||||
pub(crate) allocation_table: Vec<bool>,
|
||||
pub(crate) available_slots: usize,
|
||||
pub(crate) pointer_table: Buffer,
|
||||
pub(crate) request_buffer: RequestBuffer<1>,
|
||||
pub(crate) write_staging: StagingBelt,
|
||||
}
|
||||
|
||||
impl StructureTable
|
||||
{
|
||||
pub fn new(device: Device, queue: Queue) -> Self
|
||||
{
|
||||
let pointer_table = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("structure_table_pointer_table"),
|
||||
size: size_of::<u32>() as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
StructureTable {
|
||||
request_buffer: RequestBuffer::new(1, device.clone()),
|
||||
write_staging: StagingBelt::new(device.clone(), size_of::<u32>() as u64),
|
||||
device,
|
||||
queue,
|
||||
allocation_table: vec![false],
|
||||
available_slots: 1,
|
||||
pointer_table,
|
||||
}
|
||||
}
|
||||
|
||||
fn double_capacity(&mut self, encoder: &mut CommandEncoder)
|
||||
{
|
||||
self.available_slots += self.allocation_table.len();
|
||||
self.allocation_table
|
||||
.extend(vec![false; self.allocation_table.len()]);
|
||||
|
||||
// Copy buffers into bigger buffers
|
||||
let pointer_table = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("structure_table_pointer_table"),
|
||||
size: size_of::<u32>() as u64 * self.allocation_table.len() as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.pointer_table,
|
||||
0,
|
||||
&pointer_table,
|
||||
0,
|
||||
self.pointer_table.size(),
|
||||
);
|
||||
|
||||
self.pointer_table = pointer_table;
|
||||
self.request_buffer = RequestBuffer::new(self.allocation_table.len(), self.device.clone());
|
||||
}
|
||||
|
||||
pub fn request_buffer(&self) -> &RequestBuffer<1>
|
||||
{
|
||||
&self.request_buffer
|
||||
}
|
||||
|
||||
pub fn request_buffer_mut(&mut self) -> &mut RequestBuffer<1>
|
||||
{
|
||||
&mut self.request_buffer
|
||||
}
|
||||
|
||||
pub fn remove_structure(&mut self, structure_id: u32)
|
||||
{
|
||||
self.available_slots += 1;
|
||||
self.allocation_table[structure_id as usize] = false;
|
||||
}
|
||||
|
||||
// Returns a structure Id
|
||||
pub fn allocate_structure(&mut self, subdivided: bool) -> u32
|
||||
{
|
||||
let mut encoder = self
|
||||
.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("structure_table_resize_encoder"),
|
||||
});
|
||||
|
||||
// Get first available element
|
||||
if self.available_slots == 0
|
||||
{
|
||||
self.double_capacity(&mut encoder);
|
||||
}
|
||||
let (first_id, _) = self
|
||||
.allocation_table
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, allocated)| !**allocated)
|
||||
.next()
|
||||
.unwrap();
|
||||
self.allocation_table[first_id] = true;
|
||||
self.available_slots -= 1;
|
||||
|
||||
// Write empty pointer to new pointer
|
||||
self.write_staging
|
||||
.write_buffer(
|
||||
&mut encoder,
|
||||
&self.pointer_table,
|
||||
size_of::<u32>() as u64 * first_id as u64,
|
||||
NonZero::new(size_of::<u32>() as u64).unwrap(),
|
||||
)
|
||||
.copy_from_slice(bytemuck::bytes_of(
|
||||
&StructurePointer::new(subdivided, false).0,
|
||||
));
|
||||
self.write_staging.finish_and_recall_on_submit(&encoder);
|
||||
self.queue.submit([encoder.finish()]);
|
||||
|
||||
first_id as u32
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
use std::ops::Div;
|
||||
|
||||
use bytemuck::bytes_of;
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupEntry;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::ShaderStages;
|
||||
|
||||
use crate::gpu::radix_sort::RadixSorter;
|
||||
|
||||
pub struct UsageBuffer
|
||||
{
|
||||
pub cache_size: usize,
|
||||
pub current_timestamp: u32,
|
||||
|
||||
pub usage_buffer: Buffer,
|
||||
pub key_buffer: Buffer,
|
||||
pub index_buffer: Buffer,
|
||||
|
||||
pub index_bind_group: BindGroup,
|
||||
pub init_indices_pass: ComputePipeline,
|
||||
|
||||
pub sorter: RadixSorter,
|
||||
pub device: Device,
|
||||
}
|
||||
|
||||
impl UsageBuffer
|
||||
{
|
||||
pub fn new(cache_size: usize, device: Device) -> Self
|
||||
{
|
||||
let initial_timestamp = 0;
|
||||
let usage_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("UsageBuffer::usage_buffer"),
|
||||
size: (size_of::<u32>() * cache_size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: true,
|
||||
});
|
||||
|
||||
let key_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("UsageBuffer::key_buffer"),
|
||||
size: (size_of::<u32>() * cache_size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let index_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("UsageBuffer::key_buffer"),
|
||||
size: (size_of::<u32>() * cache_size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
usage_buffer
|
||||
.get_mapped_range_mut(0..)
|
||||
.unwrap()
|
||||
.copy_from_slice(bytemuck::cast_slice(
|
||||
vec![initial_timestamp; cache_size].as_slice(),
|
||||
));
|
||||
usage_buffer.unmap();
|
||||
|
||||
let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("UsageBuffer::bindgroup_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
|
||||
let index_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("UsageBuffer::index_bindgroup"),
|
||||
layout: &bindgroup_layout,
|
||||
entries: &[BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: index_buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
|
||||
let pipeline_layout = &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("UsageBuffer::pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bindgroup_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let init_indices_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("UsageBuffer::init_indices_pass"),
|
||||
layout: Some(pipeline_layout),
|
||||
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("clear_chunk_requests shader module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
"
|
||||
@group(0) @binding(0) var<storage, read_write> index_buffer: array<u32>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
let total = arrayLength(&index_buffer);
|
||||
if(global_invocation_id.x < total)
|
||||
{{
|
||||
index_buffer[global_invocation_id.x] = global_invocation_id.x;
|
||||
}}
|
||||
}}
|
||||
"
|
||||
.into(),
|
||||
),
|
||||
}),
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
cache_size,
|
||||
current_timestamp: initial_timestamp,
|
||||
usage_buffer,
|
||||
key_buffer,
|
||||
index_buffer,
|
||||
index_bind_group,
|
||||
init_indices_pass,
|
||||
sorter: RadixSorter::new(&device, cache_size),
|
||||
device,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn timestamp(&self) -> u32
|
||||
{
|
||||
self.current_timestamp
|
||||
}
|
||||
|
||||
pub fn next_frame(&mut self)
|
||||
{
|
||||
let (new_timestamp, _) = self.current_timestamp.overflowing_add(1);
|
||||
self.current_timestamp = new_timestamp;
|
||||
}
|
||||
|
||||
pub fn usage_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.usage_buffer
|
||||
}
|
||||
|
||||
pub fn sort_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.index_buffer
|
||||
}
|
||||
|
||||
pub fn sort_usage(&self, encoder: &mut CommandEncoder)
|
||||
{
|
||||
// Copy keys to sort buffer
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.usage_buffer,
|
||||
0,
|
||||
&self.key_buffer,
|
||||
0,
|
||||
(self.cache_size * size_of::<u32>()) as u64,
|
||||
);
|
||||
|
||||
// Compute pass to initialize sorting indices
|
||||
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("UsageBuffer::compute_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
compute_pass.set_bind_group(0, &self.index_bind_group, &[]);
|
||||
compute_pass.set_pipeline(&self.init_indices_pass);
|
||||
compute_pass.dispatch_workgroups(self.cache_size.div_ceil(256) as u32, 1, 1);
|
||||
|
||||
drop(compute_pass);
|
||||
|
||||
self.sorter.sort(
|
||||
&self.device,
|
||||
&self.key_buffer,
|
||||
&self.index_buffer,
|
||||
None,
|
||||
None,
|
||||
encoder,
|
||||
crate::gpu::radix_sort::RadixSortDirection::Ascending,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user