Compare commits
2
Commits
48ff78f58d
...
570ec62bdf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
570ec62bdf | ||
|
|
92d61b75a8 |
+8
-6
@@ -85,9 +85,10 @@ RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
[[vk::binding(3, 0)]]
|
||||
RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
[[vk::binding(4, 0)]]
|
||||
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
[[vk::binding(5, 0)]]
|
||||
[[vk::binding(1, 1)]]
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
|
||||
ByteColor fetch_color(uint32_t index, uint32_t child_index)
|
||||
@@ -109,19 +110,19 @@ bool3 min_mask(float3 val)
|
||||
return val == min_val;
|
||||
}
|
||||
|
||||
[[vk::binding(0, 1)]]
|
||||
[[vk::binding(0, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
WTexture2D<float4> target_texture;
|
||||
|
||||
[[vk::binding(1, 1)]]
|
||||
[[vk::binding(1, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
RWTexture2D<float4> gbuffer_position;
|
||||
|
||||
[[vk::binding(2, 1)]]
|
||||
[[vk::binding(2, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
RWTexture2D<float4> gbuffer_albedo;
|
||||
|
||||
[[vk::binding(3, 1)]]
|
||||
[[vk::binding(3, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
RWTexture2D<float4> gbuffer_normal;
|
||||
|
||||
@@ -154,6 +155,7 @@ void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_Gr
|
||||
let albedo = gbuffer_albedo.Load(location.xy);
|
||||
target_texture.Store(location.xy, albedo);
|
||||
return;
|
||||
|
||||
let illumination = dot(float3(0., 1., 0.), normal.xyz);
|
||||
|
||||
let view_dir = pos.xyz - constants.cam_pos;
|
||||
|
||||
Binary file not shown.
@@ -87,8 +87,9 @@ public struct VoxelCache
|
||||
public RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
public RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
public RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
public RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
public RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
|
||||
public RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
public RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
}
|
||||
|
||||
ByteColor fetch_color(VoxelCache cache, uint32_t index, uint32_t child_index)
|
||||
@@ -165,6 +166,8 @@ HitInformation chunk_ray_march(
|
||||
hit.hit = false;
|
||||
return hit;
|
||||
}
|
||||
// _hit.color = float4(0., 1., 0., 1.);
|
||||
// return _hit;
|
||||
|
||||
// Ray mirroring
|
||||
ray_origin += float3(1.);
|
||||
@@ -232,7 +235,6 @@ HitInformation chunk_ray_march(
|
||||
|
||||
uint64_t occupancy = get_child_mask(cache.structure_pool[current_node_index].occupancy_low, cache.structure_pool[current_node_index].occupancy_high);
|
||||
let occupied = ((occupancy >> child_index) & 1) != 0;
|
||||
// if (occupied)
|
||||
if (fetch_color(cache, current_node_index, child_index).byte_a != 0)
|
||||
{
|
||||
var hit : HitInformation;
|
||||
@@ -342,7 +344,8 @@ public HitInformation ray_cast(
|
||||
{
|
||||
let off = t - abs(1. / context.ray_direction);
|
||||
let t_adv = max(max(off.x, max(off.y, off.z)), 0.);
|
||||
let chunk_index = current_voxel.y + current_voxel.z * context.bounds.y + current_voxel.x * context.bounds.y * context.bounds.z;
|
||||
// let chunk_index = current_voxel.y + current_voxel.z * context.bounds.y + current_voxel.x * context.bounds.y * context.bounds.z;
|
||||
let chunk_index = current_voxel.x + current_voxel.z * context.bounds.x + current_voxel.y * context.bounds.x * context.bounds.z;
|
||||
let position = context.ray_origin + context.ray_direction * t_adv;
|
||||
var hit = chunk_ray_march(
|
||||
cache,
|
||||
|
||||
+9
-6
@@ -85,9 +85,10 @@ RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
[[vk::binding(3, 0)]]
|
||||
RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
[[vk::binding(4, 0)]]
|
||||
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
[[vk::binding(5, 0)]]
|
||||
[[vk::binding(1, 1)]]
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
|
||||
ByteColor fetch_color(uint32_t index, uint32_t child_index)
|
||||
@@ -109,15 +110,15 @@ bool3 min_mask(float3 val)
|
||||
return val == min_val;
|
||||
}
|
||||
|
||||
[[vk::binding(0, 1)]]
|
||||
[[vk::binding(0, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
WTexture2D<float4> gbuffer_position;
|
||||
|
||||
[[vk::binding(1, 1)]]
|
||||
[[vk::binding(1, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
WTexture2D<float4> gbuffer_albedo;
|
||||
|
||||
[[vk::binding(2, 1)]]
|
||||
[[vk::binding(2, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
WTexture2D<float4> gbuffer_normal;
|
||||
|
||||
@@ -174,8 +175,10 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_
|
||||
{
|
||||
// Gather
|
||||
let hit_pos = hit.hit_pos;
|
||||
|
||||
let hit_normal = fetch_normal(hit.node_index, hit.child_index);
|
||||
let hit_albedo = fetch_color(hit.node_index, hit.child_index).float_color;
|
||||
var hit_albedo = float4(0.);
|
||||
hit_albedo = fetch_color(hit.node_index, hit.child_index).float_color;
|
||||
// let hit_albedo = hit.color;
|
||||
|
||||
gbuffer_position.Store(location.xy, float4(hit_pos, 1.));
|
||||
|
||||
Binary file not shown.
@@ -1,30 +0,0 @@
|
||||
use wgpu::Device;
|
||||
use wgpu::Queue;
|
||||
|
||||
use crate::voxel_cache::PageList;
|
||||
use crate::voxel_cache::VoxelCache;
|
||||
use crate::voxel_cache::layout::VoxelCacheLayout;
|
||||
|
||||
pub struct VoxelGiPipeline<const N: usize>
|
||||
{
|
||||
voxel_cache: VoxelCache<N>,
|
||||
// ~~ Leaf list ~~
|
||||
// The leaf list is maintained in a sparse swap'n'pop fashion
|
||||
leaf_list: PageList,
|
||||
}
|
||||
|
||||
impl<const N: usize> VoxelGiPipeline<N>
|
||||
{
|
||||
pub fn new(device: &Device, queue: &Queue, cache_size: usize, layout: VoxelCacheLayout) -> Self
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let voxel_cache = VoxelCache::new(cache_size, device.clone(), queue.clone(), &layout);
|
||||
let leaf_list = PageList::new(device, cache_size);
|
||||
|
||||
VoxelGiPipeline {
|
||||
voxel_cache,
|
||||
leaf_list,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// Main common gpu parallel algorithms
|
||||
pub mod buffer_compactor;
|
||||
pub mod indirect_buffer;
|
||||
pub mod radix_sort;
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
use wgpu::Buffer;
|
||||
use wgpu::CommandEncoder;
|
||||
|
||||
/// Provides utility object to manage indirect dispatches workgroup count computations on the GPU
|
||||
|
||||
/// Takes in a single u32, and computes the amount of workgroups to dispatch given a workgroup size
|
||||
pub struct IndirectBuffer1D
|
||||
{
|
||||
/// Buffer used in the indirect dispatch command
|
||||
indirect_buffer: wgpu::Buffer,
|
||||
|
||||
/// Buffer visible from compute shaders to compute the amount
|
||||
indirect_storage: wgpu::Buffer,
|
||||
indirect_storage_bind_group: wgpu::BindGroup,
|
||||
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
compute_pipeline: wgpu::ComputePipeline,
|
||||
}
|
||||
|
||||
impl IndirectBuffer1D
|
||||
{
|
||||
pub fn new(device: &wgpu::Device) -> Self
|
||||
{
|
||||
let indirect_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("IndirectBuffer1D::indirect_buffer"),
|
||||
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let indirect_storage = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("IndirectBuffer1D::indirect_storage"),
|
||||
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("IndirectBuffer1D::bind_group_layout"),
|
||||
entries: &[wgpu::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,
|
||||
}],
|
||||
});
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("IndirectBuffer1D::bind_group"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: indirect_storage.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("IndirectBuffer1D::shader_module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
"
|
||||
struct IndirectDispatchArgs
|
||||
{
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<storage, read_write> indirect_storage: IndirectDispatchArgs;
|
||||
@group(1) @binding(0) var<storage, read_write> user_count: u32;
|
||||
|
||||
var<immediate> workgroup_size: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(1, 1, 1)
|
||||
fn main()
|
||||
{
|
||||
let workgroup_count = (user_count / workgroup_size) + select(u32(1), u32(0), user_count % workgroup_size == 0);
|
||||
|
||||
var args: IndirectDispatchArgs;
|
||||
args.x = workgroup_count;
|
||||
args.y = 1;
|
||||
args.z = 1;
|
||||
indirect_storage = args;
|
||||
}
|
||||
".into(),
|
||||
),
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("IndirectBuffer1D::pipeline_layout"),
|
||||
bind_group_layouts: &[
|
||||
// Group 0: indirect args buffer
|
||||
Some(&bind_group_layout),
|
||||
// Group 1: user count buffer
|
||||
Some(&bind_group_layout),
|
||||
],
|
||||
|
||||
// workgroup size
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("IndirectBuffer1D::pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
indirect_buffer,
|
||||
indirect_storage,
|
||||
indirect_storage_bind_group: bind_group,
|
||||
bind_group_layout,
|
||||
compute_pipeline: pipeline,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn workgroup_count(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut CommandEncoder,
|
||||
count_buffer: &Buffer,
|
||||
workgroup_size: u32,
|
||||
) -> &Buffer
|
||||
{
|
||||
// Transient bind group
|
||||
let user_count_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("IndirectBuffer1D::bind_group"),
|
||||
layout: &self.bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: count_buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
|
||||
{
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("IndirectBuffer1D::compute_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
pass.set_pipeline(&self.compute_pipeline);
|
||||
pass.set_bind_group(0, &self.indirect_storage_bind_group, &[]);
|
||||
pass.set_bind_group(1, &user_count_bind_group, &[]);
|
||||
pass.set_immediates(0, bytemuck::bytes_of(&workgroup_size));
|
||||
|
||||
pass.dispatch_workgroups(1, 1, 1);
|
||||
}
|
||||
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.indirect_storage,
|
||||
0,
|
||||
&self.indirect_buffer,
|
||||
0,
|
||||
Some(self.indirect_storage.size()),
|
||||
);
|
||||
|
||||
&self.indirect_buffer
|
||||
}
|
||||
}
|
||||
+351
-81
@@ -3,7 +3,8 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::sync_channel;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
@@ -16,11 +17,6 @@ use glam::Mat4;
|
||||
use glam::Vec3;
|
||||
use glam::Vec4;
|
||||
use itertools::Itertools;
|
||||
use rand::random;
|
||||
use rand::random_range;
|
||||
use rayon::iter::IndexedParallelIterator;
|
||||
use rayon::iter::IntoParallelRefIterator;
|
||||
use rayon::iter::ParallelIterator;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
@@ -60,12 +56,13 @@ use crate::producers::SdfGenerator;
|
||||
use crate::producers::TerrainGenerator;
|
||||
use crate::sparse_tree::NTreeNodeLocator;
|
||||
use crate::voxel_cache::VoxelCache;
|
||||
use crate::voxel_cache::data::ColorBytes;
|
||||
use crate::voxel_cache::data::LocationPoolElement;
|
||||
use crate::voxel_cache::data::StructurePoolElement;
|
||||
use crate::voxel_cache::layout::VoxelCacheLayout;
|
||||
use crate::voxel_cache::producer_interface::CacheProducerInterface;
|
||||
use crate::voxel_cache::producer_interface::CacheRequest;
|
||||
use crate::voxel_cache::VoxelCacheInsertion;
|
||||
use crate::voxel_cache::insertion::CacheInsertionData;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::schema::InsertionInformation;
|
||||
use crate::voxel_cache::schema::LocationPage;
|
||||
use crate::voxel_cache::schema::RequestInformation;
|
||||
use crate::voxel_cache::tables::FixedStructureTable;
|
||||
|
||||
mod camera;
|
||||
mod egui_renderer;
|
||||
@@ -108,10 +105,16 @@ struct State
|
||||
gi_pipeline: ComputePipeline,
|
||||
surface_bg_layout: BindGroupLayout,
|
||||
gi_bg_layout: BindGroupLayout,
|
||||
|
||||
voxel_cache: Arc<Mutex<VoxelCache<4>>>,
|
||||
cache_interface: Arc<CacheProducerInterface<4>>,
|
||||
//terrain_generator: Arc<SdfGenerator<4>>,
|
||||
terrain_generator: Arc<TerrainGenerator<4>>,
|
||||
request_buffer: Arc<CacheRequestBuffer>,
|
||||
cache_insertion: Arc<CacheInsertionData<4>>,
|
||||
|
||||
structure_table: Arc<Mutex<FixedStructureTable>>,
|
||||
structure_table_request_buffer: Arc<CacheRequestBuffer>,
|
||||
structure_table_cache_insertion: Arc<CacheInsertionData<4>>,
|
||||
terrain_generator: Arc<SdfGenerator<4>>,
|
||||
//terrain_generator: Arc<TerrainGenerator<4>>,
|
||||
chunk_pos_map: Arc<HashMap<u32, (usize, usize, usize)>>,
|
||||
instance_buffer: Buffer,
|
||||
instance_count: usize,
|
||||
@@ -188,6 +191,7 @@ impl State
|
||||
| Features::TIMESTAMP_QUERY_INSIDE_ENCODERS
|
||||
| Features::TIMESTAMP_QUERY_INSIDE_PASSES
|
||||
| Features::STORAGE_RESOURCE_BINDING_ARRAY
|
||||
| Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
|
||||
| Features::BUFFER_BINDING_ARRAY
|
||||
| Features::PASSTHROUGH_SHADERS
|
||||
| Features::SHADER_INT64,
|
||||
@@ -338,24 +342,24 @@ impl State
|
||||
|
||||
let egui_renderer = EguiRenderer::new(&device, surface_format, &window);
|
||||
|
||||
let mut attributes = VoxelCacheLayout::default();
|
||||
attributes.add_attribute(voxel_cache::layout::VoxelCacheAttribute {
|
||||
let mut layout = voxel_cache::layout::CacheLayout::default();
|
||||
layout.add_attribute(voxel_cache::CacheAttribute {
|
||||
label: Some("color"),
|
||||
word_count: 1,
|
||||
rate: voxel_cache::layout::VoxelCacheAttributeRate::Pointer,
|
||||
init: voxel_cache::layout::VoxelCacheAttributeInit::Copy,
|
||||
init: voxel_cache::CacheAttributeInit::External,
|
||||
});
|
||||
attributes.add_attribute(voxel_cache::layout::VoxelCacheAttribute {
|
||||
layout.add_attribute(voxel_cache::CacheAttribute {
|
||||
label: Some("normal"),
|
||||
word_count: 3,
|
||||
rate: voxel_cache::layout::VoxelCacheAttributeRate::Pointer,
|
||||
init: voxel_cache::layout::VoxelCacheAttributeInit::Copy,
|
||||
init: voxel_cache::CacheAttributeInit::External,
|
||||
});
|
||||
|
||||
let mut voxel_cache =
|
||||
VoxelCache::<4>::new(150_000, device.clone(), queue.clone(), &attributes);
|
||||
let cache_interface = CacheProducerInterface::new(1024, &device, &attributes);
|
||||
let voxel_cache = VoxelCache::<4>::new(&device, 100_000, &layout);
|
||||
let request_buffer = CacheRequestBuffer::new(&device, 1024);
|
||||
let insertion_data = CacheInsertionData::new(&device, 1024, &layout);
|
||||
|
||||
let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg");
|
||||
//let terrain_generator = SdfGenerator::<4>::new(5);
|
||||
//let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg");
|
||||
let terrain_generator = SdfGenerator::<4>::new(5);
|
||||
// let terrain_generator = TerrainGenerator::<4>::new(
|
||||
// 5,
|
||||
// "./pointe_percee/height.tif",
|
||||
@@ -370,31 +374,36 @@ impl State
|
||||
// );
|
||||
//
|
||||
|
||||
let terrain_width = terrain_generator.chunk_width;
|
||||
let terrain_height = terrain_generator.chunk_height;
|
||||
let terrain_alt = terrain_generator.chunk_alt;
|
||||
// let terrain_width = 10;
|
||||
// let terrain_height = 10;
|
||||
// let terrain_alt = 10;
|
||||
// let terrain_width = terrain_generator.chunk_width;
|
||||
// let terrain_height = terrain_generator.chunk_height;
|
||||
// let terrain_alt = terrain_generator.chunk_alt;
|
||||
let terrain_width = 10;
|
||||
let terrain_height = 10;
|
||||
let terrain_alt = 10;
|
||||
println!(
|
||||
"Chunk count : {}",
|
||||
terrain_width * terrain_height * terrain_width
|
||||
terrain_width * terrain_height * terrain_alt
|
||||
);
|
||||
|
||||
let mut chunk_pos_map = HashMap::new();
|
||||
let chunk_instances = (0..terrain_width)
|
||||
.cartesian_product(0..terrain_height)
|
||||
.cartesian_product(0..terrain_alt)
|
||||
.map(|((x, z), y)| {
|
||||
let chunk_id = voxel_cache.structure_table.allocate_structure(true);
|
||||
//dbg!(chunk_id);
|
||||
let total_chunk_count = terrain_height * terrain_width * terrain_alt;
|
||||
|
||||
chunk_pos_map.insert(chunk_id, (x, y, z));
|
||||
let structure_table = FixedStructureTable::new(&device, total_chunk_count, &layout);
|
||||
let structure_table_request_buffer = CacheRequestBuffer::new(&device, 1024);
|
||||
let structure_table_insertion_data = CacheInsertionData::new(&device, 1024, &layout);
|
||||
let chunk_instances = (0..terrain_alt)
|
||||
.cartesian_product(0..terrain_height)
|
||||
.cartesian_product(0..terrain_width)
|
||||
.map(|((y, z), x)| {
|
||||
//dbg!(chunk_id);
|
||||
let chunk_id = y * terrain_width * terrain_height + z * terrain_width + x;
|
||||
|
||||
chunk_pos_map.insert(chunk_id as u32, (x, y, z));
|
||||
InstanceAttribute {
|
||||
x: x as f32,
|
||||
y: y as f32,
|
||||
z: z as f32,
|
||||
id: chunk_id,
|
||||
id: chunk_id as u32,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -587,7 +596,8 @@ impl State
|
||||
label: Some("Voxel pipeline layout"),
|
||||
|
||||
bind_group_layouts: &[
|
||||
Some(voxel_cache.user_bind_group_layout()),
|
||||
Some(voxel_cache.raytrace_bind_group_layout()),
|
||||
Some(structure_table.raytrace_bind_group_layout()),
|
||||
Some(&ray_march_bind_group_layout),
|
||||
],
|
||||
immediate_size: size_of::<Immediates>() as u32,
|
||||
@@ -609,7 +619,8 @@ impl State
|
||||
label: Some("Gi pipeline layout"),
|
||||
|
||||
bind_group_layouts: &[
|
||||
Some(&voxel_cache.user_bind_group_layout()),
|
||||
Some(voxel_cache.raytrace_bind_group_layout()),
|
||||
Some(structure_table.raytrace_bind_group_layout()),
|
||||
Some(&gi_bind_group_layout),
|
||||
],
|
||||
immediate_size: size_of::<Immediates>() as u32,
|
||||
@@ -666,7 +677,13 @@ impl State
|
||||
usage_vec: Arc::new(Mutex::new(vec![])),
|
||||
pipeline: chunk_pipeline,
|
||||
voxel_cache: Arc::new(Mutex::new(voxel_cache)),
|
||||
cache_interface: cache_interface.into(),
|
||||
request_buffer: Arc::new(request_buffer),
|
||||
cache_insertion: Arc::new(insertion_data),
|
||||
|
||||
structure_table: Arc::new(Mutex::new(structure_table)),
|
||||
structure_table_cache_insertion: Arc::new(structure_table_insertion_data),
|
||||
structure_table_request_buffer: Arc::new(structure_table_request_buffer),
|
||||
|
||||
insertion_debounce: false,
|
||||
camera: Default::default(),
|
||||
instance_buffer,
|
||||
@@ -881,7 +898,6 @@ impl State
|
||||
fn render(&mut self)
|
||||
{
|
||||
self.camera.update();
|
||||
self.voxel_cache.lock().next_frame();
|
||||
|
||||
// Create texture view.
|
||||
// NOTE: We must handle Timeout because the surface may be unavailable
|
||||
@@ -999,8 +1015,13 @@ impl State
|
||||
});
|
||||
|
||||
renderpass.set_pipeline(&self.pipeline);
|
||||
renderpass.set_bind_group(0, &self.voxel_cache.lock().user_bind_group(), &[]);
|
||||
renderpass.set_bind_group(1, Some(&surface_bg), &[]);
|
||||
renderpass.set_bind_group(0, self.voxel_cache.lock().raytrace_bind_group(), &[]);
|
||||
renderpass.set_bind_group(
|
||||
1,
|
||||
self.structure_table.lock().raytrace_bind_group(),
|
||||
&[],
|
||||
);
|
||||
renderpass.set_bind_group(2, Some(&surface_bg), &[]);
|
||||
let imm = [Immediates {
|
||||
view_proj: self.camera.view_proj().inverse(),
|
||||
cam_pos: self.camera.position,
|
||||
@@ -1023,7 +1044,7 @@ impl State
|
||||
);
|
||||
renderpass.set_pipeline(&self.gi_pipeline);
|
||||
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
|
||||
renderpass.set_bind_group(1, Some(&gi_surface_bg), &[]);
|
||||
renderpass.set_bind_group(2, Some(&gi_surface_bg), &[]);
|
||||
renderpass.dispatch_workgroups(
|
||||
self.size.width.div_ceil(16),
|
||||
self.size.height.div_ceil(16),
|
||||
@@ -1130,24 +1151,24 @@ impl State
|
||||
}
|
||||
|
||||
// ~~ Build usage buffer histogram
|
||||
let time_stamp = self.voxel_cache.lock().current_timestamp();
|
||||
let cloned_usage_histogram = self.usage_vec.clone();
|
||||
DownloadBuffer::read_buffer(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
&self.voxel_cache.lock().usage_buffer.slice(..),
|
||||
move |slice| {
|
||||
let slice = slice.unwrap();
|
||||
let cache_slice: &[u32] = bytemuck::cast_slice(&slice);
|
||||
let mut v = vec![0; 100];
|
||||
for x in cache_slice.iter()
|
||||
{
|
||||
let diff = (time_stamp - x).min(99);
|
||||
v[diff as usize] += 1;
|
||||
}
|
||||
*cloned_usage_histogram.lock() = v;
|
||||
},
|
||||
);
|
||||
// let time_stamp = self.voxel_cache.lock().current_timestamp();
|
||||
// let cloned_usage_histogram = self.usage_vec.clone();
|
||||
// DownloadBuffer::read_buffer(
|
||||
// &self.device,
|
||||
// &self.queue,
|
||||
// &self.voxel_cache.lock().usage_buffer.slice(..),
|
||||
// move |slice| {
|
||||
// let slice = slice.unwrap();
|
||||
// let cache_slice: &[u32] = bytemuck::cast_slice(&slice);
|
||||
// let mut v = vec![0; 100];
|
||||
// for x in cache_slice.iter()
|
||||
// {
|
||||
// let diff = (time_stamp - x).min(99);
|
||||
// v[diff as usize] += 1;
|
||||
// }
|
||||
// *cloned_usage_histogram.lock() = v;
|
||||
// },
|
||||
// );
|
||||
|
||||
// DownloadBuffer::read_buffer(
|
||||
// &self.device,
|
||||
@@ -1172,9 +1193,17 @@ impl State
|
||||
.pressed_keyset
|
||||
.contains(&winit::keyboard::KeyCode::KeyF)
|
||||
{
|
||||
self.voxel_cache
|
||||
.lock()
|
||||
.cache_post_render(&mut encoder, &self.cache_interface);
|
||||
self.voxel_cache.lock().gather_requests(
|
||||
&self.device,
|
||||
&mut encoder,
|
||||
&self.request_buffer,
|
||||
);
|
||||
|
||||
self.structure_table.lock().gather_requests(
|
||||
&self.device,
|
||||
&mut encoder,
|
||||
&self.structure_table_request_buffer,
|
||||
);
|
||||
}
|
||||
|
||||
// ~~ Submit command buffer ~~
|
||||
@@ -1220,23 +1249,169 @@ impl State
|
||||
.contains(&winit::keyboard::KeyCode::KeyF)
|
||||
{
|
||||
self.insertion_debounce = true;
|
||||
let request_count = self
|
||||
.cache_interface
|
||||
.total_request_count(&self.device, &self.queue);
|
||||
let cloned_cache = self.voxel_cache.clone();
|
||||
let cloned_device = self.device.clone();
|
||||
let cloned_queue = self.queue.clone();
|
||||
let cloned_generator = self.terrain_generator.clone();
|
||||
let cloned_map = self.chunk_pos_map.clone();
|
||||
let cloned_cache_interface = self.cache_interface.clone();
|
||||
let cloned_insert_profile = self.insert_profile.clone();
|
||||
let (tx, rx) = sync_channel(1);
|
||||
let finished = Arc::new(AtomicU32::new(0));
|
||||
|
||||
// Cache requests
|
||||
let cloned_insertion_data = self.cache_insertion.clone();
|
||||
let request_buffer_done = Arc::new(AtomicBool::new(false));
|
||||
let request_buffer_done_1 = request_buffer_done.clone();
|
||||
let finshed_1 = finished.clone();
|
||||
self.request_buffer.host_download_requests(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
move |request_informations| {
|
||||
let done = request_buffer_done_1.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if !done
|
||||
{
|
||||
request_buffer_done_1.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
finshed_1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
else
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//println!("Cache : {} requests", request_informations.len());
|
||||
|
||||
let mut insertion_infos = vec![];
|
||||
let mut color_attributes = vec![];
|
||||
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
|
||||
let mut location_pages = vec![];
|
||||
|
||||
for request in request_informations.iter()
|
||||
{
|
||||
let (colors, normals, insertion_info, location) = fullfill_request(
|
||||
cloned_generator.as_ref(),
|
||||
request,
|
||||
cloned_map.as_ref(),
|
||||
);
|
||||
|
||||
insertion_infos.push(insertion_info);
|
||||
color_attributes.push(colors);
|
||||
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
|
||||
location_pages.push(location);
|
||||
}
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
cloned_insertion_data.insertion_information_buffer(),
|
||||
0,
|
||||
bytemuck::cast_slice(&insertion_infos),
|
||||
);
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
cloned_insertion_data.location_pages_buffer(),
|
||||
0,
|
||||
bytemuck::cast_slice(&location_pages),
|
||||
);
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
&cloned_insertion_data.attributes_buffers()[0],
|
||||
0,
|
||||
bytemuck::cast_slice(&color_attributes),
|
||||
);
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
&cloned_insertion_data.attributes_buffers()[1],
|
||||
0,
|
||||
bytemuck::cast_slice(&normal_attributes),
|
||||
);
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
cloned_insertion_data.page_count_buffer(),
|
||||
0,
|
||||
bytemuck::bytes_of(&(request_informations.len() as u32)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
let cloned_queue = self.queue.clone();
|
||||
let cloned_generator = self.terrain_generator.clone();
|
||||
let cloned_map = self.chunk_pos_map.clone();
|
||||
|
||||
// Structure table requests
|
||||
let cloned_st_insertion_data = self.structure_table_cache_insertion.clone();
|
||||
let structure_table_request_buffer_done = Arc::new(AtomicBool::new(false));
|
||||
let structure_table_request_buffer_done_1 = structure_table_request_buffer_done.clone();
|
||||
let finshed_2 = finished.clone();
|
||||
self.structure_table_request_buffer.host_download_requests(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
move |request_informations| {
|
||||
let done = structure_table_request_buffer_done_1
|
||||
.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if !done
|
||||
{
|
||||
structure_table_request_buffer_done_1
|
||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
finshed_2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
else
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//println!("Structure table: {} requests", request_informations.len());
|
||||
|
||||
let mut insertion_infos = vec![];
|
||||
let mut color_attributes = vec![];
|
||||
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
|
||||
let mut location_pages = vec![];
|
||||
|
||||
for request in request_informations.iter()
|
||||
{
|
||||
let (colors, normals, insertion_info, location) = fullfill_request(
|
||||
cloned_generator.as_ref(),
|
||||
request,
|
||||
cloned_map.as_ref(),
|
||||
);
|
||||
|
||||
insertion_infos.push(insertion_info);
|
||||
color_attributes.push(colors);
|
||||
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
|
||||
location_pages.push(location);
|
||||
}
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
cloned_st_insertion_data.insertion_information_buffer(),
|
||||
0,
|
||||
bytemuck::cast_slice(&insertion_infos),
|
||||
);
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
cloned_st_insertion_data.location_pages_buffer(),
|
||||
0,
|
||||
bytemuck::cast_slice(&location_pages),
|
||||
);
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
&cloned_st_insertion_data.attributes_buffers()[0],
|
||||
0,
|
||||
bytemuck::cast_slice(&color_attributes),
|
||||
);
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
&cloned_st_insertion_data.attributes_buffers()[1],
|
||||
0,
|
||||
bytemuck::cast_slice(&normal_attributes),
|
||||
);
|
||||
|
||||
cloned_queue.write_buffer(
|
||||
cloned_st_insertion_data.page_count_buffer(),
|
||||
0,
|
||||
bytemuck::bytes_of(&(request_informations.len() as u32)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// ~~ Download request buffer, fullfill requests, writeback to cache ~~
|
||||
/*
|
||||
DownloadBuffer::read_buffer(
|
||||
&self.device.clone(),
|
||||
&self.queue.clone(),
|
||||
&self.cache_interface.requests_buffer().slice(..),
|
||||
&self.request_buffer.requests_buffer().slice(..),
|
||||
move |buffer| {
|
||||
if tx.try_send(()).is_err()
|
||||
{
|
||||
@@ -1371,17 +1546,52 @@ impl State
|
||||
}
|
||||
},
|
||||
);
|
||||
*/
|
||||
//println!("Total request count: {}", request_count);
|
||||
loop
|
||||
{
|
||||
if rx.try_recv().is_ok()
|
||||
if finished.load(std::sync::atomic::Ordering::Relaxed) >= 2
|
||||
{
|
||||
break;
|
||||
}
|
||||
let _ = self.device.poll(wgpu::wgt::PollType::Poll);
|
||||
}
|
||||
|
||||
drop(rx);
|
||||
let mut encoder = self.device.create_command_encoder(&Default::default());
|
||||
|
||||
let mut scoped_encoder = ProfilingEncoder::new(&self.device, &mut encoder);
|
||||
{
|
||||
gpu_profiler::begin_frame!(scoped_encoder, "Cache insertion");
|
||||
let mut locked_st = self.structure_table.lock();
|
||||
self.voxel_cache.lock().insert(
|
||||
&self.device,
|
||||
&mut scoped_encoder,
|
||||
&mut [
|
||||
&mut VoxelCacheInsertion::InternalRequest(
|
||||
&self.cache_insertion,
|
||||
&self.request_buffer,
|
||||
),
|
||||
&mut VoxelCacheInsertion::ExternalRequest(
|
||||
&self.structure_table_cache_insertion,
|
||||
&mut *locked_st,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
locked_st.insert(
|
||||
&self.device,
|
||||
&mut scoped_encoder,
|
||||
&self.structure_table_cache_insertion,
|
||||
&self.structure_table_request_buffer,
|
||||
);
|
||||
}
|
||||
|
||||
let cloned_insert_profile = self.insert_profile.clone();
|
||||
let gpu_profile = scoped_encoder.finish_profiler();
|
||||
self.queue.submit([encoder.finish()]);
|
||||
gpu_profile.read_back(&self.device, &self.queue, move |profile| {
|
||||
*cloned_insert_profile.lock() = profile;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1507,3 +1717,63 @@ pub struct ChunkImmediate
|
||||
root_subdiv: bool,
|
||||
frame_timestamp: u32,
|
||||
}
|
||||
|
||||
fn fullfill_request<const N: usize>(
|
||||
generator: &dyn ChunkedProducer<N>,
|
||||
request: &RequestInformation,
|
||||
map: &HashMap<u32, (usize, usize, usize)>,
|
||||
) -> (
|
||||
[u32; N * N * N],
|
||||
[[f32; 3]; N * N * N],
|
||||
InsertionInformation<N>,
|
||||
LocationPage,
|
||||
)
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
// Unpack structure id
|
||||
let (chunk_x, chunk_y, chunk_z) = *map.get(&request.structure_id).unwrap();
|
||||
|
||||
let location;
|
||||
let node;
|
||||
if request.node_id == 0
|
||||
{
|
||||
// Produce root node
|
||||
node = generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z));
|
||||
location = LocationPage {
|
||||
structure_id: request.structure_id,
|
||||
node_id: NTreeNodeLocator::<4>::root().as_usize() as u32,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
// Figure out depth of request
|
||||
let locator = NTreeNodeLocator::<4>::from_usize(request.node_id as usize);
|
||||
let depth = locator.depth();
|
||||
//let (x, y, z) = locator.node_location();
|
||||
|
||||
let child_z = request.children_index / (4 * 4);
|
||||
let child_y = (request.children_index % (4 * 4)) / 4;
|
||||
let child_x = request.children_index % 4;
|
||||
|
||||
let child_locator = locator.child(child_x as usize, child_y as usize, child_z as usize);
|
||||
|
||||
let (nx, ny, nz) = child_locator.node_location();
|
||||
|
||||
node = generator.produce_node(depth + 1, nx, ny, nz, (chunk_x, chunk_y, chunk_z));
|
||||
|
||||
location = LocationPage {
|
||||
structure_id: request.structure_id,
|
||||
node_id: child_locator.as_usize() as u32,
|
||||
};
|
||||
}
|
||||
|
||||
(
|
||||
node.colors,
|
||||
node.normals,
|
||||
InsertionInformation {
|
||||
children: node.children,
|
||||
},
|
||||
location,
|
||||
)
|
||||
}
|
||||
|
||||
+31
-143
@@ -13,8 +13,7 @@ use noise::Worley;
|
||||
use rand::random;
|
||||
|
||||
use crate::sparse_tree::Color;
|
||||
use crate::voxel_cache::data::ExplicitNTreeNode;
|
||||
use crate::voxel_cache::data::StructurePointer;
|
||||
use crate::voxel_cache::schema::ChildInformation;
|
||||
|
||||
pub struct BallGenerator<const N: usize>
|
||||
{
|
||||
@@ -36,7 +35,7 @@ pub trait Producer<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ExplicitNTreeNode<N>;
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>;
|
||||
}
|
||||
|
||||
impl<const N: usize> BallGenerator<N>
|
||||
@@ -53,7 +52,7 @@ impl<const N: usize> Producer<N> for BallGenerator<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ExplicitNTreeNode<N>
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>
|
||||
{
|
||||
let node_size = N.pow((self.chunk_power - depth) as u32);
|
||||
let child_size = node_size / N;
|
||||
@@ -91,19 +90,17 @@ where
|
||||
}
|
||||
else if dist > (global_size as f32 / 2.)
|
||||
{
|
||||
children.push(StructurePointer(0));
|
||||
subdivided = false;
|
||||
alpha = 0.;
|
||||
}
|
||||
else
|
||||
{
|
||||
children.push(StructurePointer(0));
|
||||
subdivided = false;
|
||||
alpha = 1.;
|
||||
}
|
||||
|
||||
// let alpha = 1.;
|
||||
children.push(StructurePointer::new(subdivided, subdivided || alpha != 0.));
|
||||
children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.));
|
||||
children_normal.push((0., 0., 0.));
|
||||
children_color.push(Color(
|
||||
gvx as f32 / global_size as f32,
|
||||
@@ -113,128 +110,10 @@ where
|
||||
));
|
||||
}
|
||||
|
||||
ExplicitNTreeNode {
|
||||
structure: std::array::from_fn(|i| children[i]),
|
||||
colors: std::array::from_fn(|i| children_color[i]),
|
||||
normals: std::array::from_fn(|i| children_normal[i]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SineGenerator<const N: usize>
|
||||
{
|
||||
chunk_power: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize> SineGenerator<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(chunk_power: usize) -> Self
|
||||
{
|
||||
Self { chunk_power }
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Producer<N> for SineGenerator<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ExplicitNTreeNode<N>
|
||||
{
|
||||
let node_size = N.pow((self.chunk_power - depth) as u32);
|
||||
let child_size = node_size / N;
|
||||
let global_size = N.pow(self.chunk_power as u32);
|
||||
|
||||
let mut children = vec![];
|
||||
let mut children_normal = vec![];
|
||||
let mut children_color = vec![];
|
||||
|
||||
let gnx = nx * node_size;
|
||||
let gny = ny * node_size;
|
||||
let gnz = nz * node_size;
|
||||
// Iterate on children of this node
|
||||
for ((cx, cy), cz) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
|
||||
{
|
||||
let total_sub_voxels = child_size * child_size * child_size;
|
||||
let mut filled_sub_voxels = 0;
|
||||
|
||||
let gcx = gnx + cx * child_size;
|
||||
let gcy = gny + cy * child_size;
|
||||
let gcz = gnz + cz * child_size;
|
||||
|
||||
// prepare 2d values
|
||||
|
||||
// Iterate on children
|
||||
for (x, z) in (0..child_size).cartesian_product(0..child_size)
|
||||
{
|
||||
let gvx = gcx + x;
|
||||
let gvz = gcz + z;
|
||||
//let gvy = gcy;
|
||||
let sx = map(gvx as f32, 0., global_size as f32, -8., 8.).abs();
|
||||
let sz = map(gvz as f32, 0., global_size as f32, -8., 8.).abs();
|
||||
let sample = (fastapprox::fast::cos(sx) + fastapprox::fast::cos(sz)) * 0.5;
|
||||
let sample_height = map(sample, -1., 1., 0., 500.);
|
||||
|
||||
let prop = map(
|
||||
sample_height,
|
||||
gcy as f32,
|
||||
(gcy + child_size) as f32,
|
||||
0.,
|
||||
child_size as f32,
|
||||
)
|
||||
.clamp(0., child_size as f32)
|
||||
.floor() as usize;
|
||||
filled_sub_voxels += prop;
|
||||
}
|
||||
|
||||
let alpha;
|
||||
if filled_sub_voxels == 0
|
||||
{
|
||||
children.push(StructurePointer(0));
|
||||
alpha = 0.;
|
||||
}
|
||||
else if filled_sub_voxels >= total_sub_voxels
|
||||
{
|
||||
children.push(StructurePointer(0));
|
||||
alpha = 1.;
|
||||
}
|
||||
else
|
||||
{
|
||||
children.push(StructurePointer(
|
||||
if depth < (self.chunk_power - 1)
|
||||
{
|
||||
0xFFFFFFFF
|
||||
}
|
||||
else
|
||||
{
|
||||
0
|
||||
},
|
||||
));
|
||||
//children.push(StructurePointer(0));
|
||||
alpha = if filled_sub_voxels > total_sub_voxels / 2
|
||||
{
|
||||
1.
|
||||
}
|
||||
else
|
||||
{
|
||||
0.
|
||||
};
|
||||
}
|
||||
|
||||
children_normal.push((0., 0., 0.));
|
||||
children_color.push(Color(
|
||||
(gcx + child_size / 2) as f32 / global_size as f32,
|
||||
(gcy + child_size / 2) as f32 / global_size as f32,
|
||||
(gcz + child_size / 2) as f32 / global_size as f32,
|
||||
alpha,
|
||||
));
|
||||
}
|
||||
|
||||
ExplicitNTreeNode {
|
||||
structure: std::array::from_fn(|i| children[i]),
|
||||
colors: std::array::from_fn(|i| children_color[i]),
|
||||
normals: std::array::from_fn(|i| children_normal[i]),
|
||||
ProducedChunk {
|
||||
children: std::array::from_fn(|i| children[i]),
|
||||
colors: std::array::from_fn(|i| children_color[i].as_packed_u32()),
|
||||
normals: std::array::from_fn(|i| children_normal[i].into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -424,13 +303,13 @@ where
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ExplicitNTreeNode<N>
|
||||
) -> ProducedChunk<N>
|
||||
{
|
||||
let node_size = N.pow((self.chunk_power - depth) as u32);
|
||||
let child_size = node_size / N;
|
||||
let global_size = N.pow(self.chunk_power as u32);
|
||||
|
||||
let mut children = vec![StructurePointer(0); N * N * N];
|
||||
let mut children = vec![ChildInformation::NONE; N * N * N];
|
||||
let mut children_color = vec![Color(0., 0., 0., 0.); N * N * N];
|
||||
let mut children_normals = vec![(0., 0., 0.); N * N * N];
|
||||
|
||||
@@ -563,21 +442,30 @@ where
|
||||
};
|
||||
}
|
||||
|
||||
children[index] = StructurePointer::new(subdivided, subdivided || alpha != 0.);
|
||||
children[index] = ChildInformation::new(subdivided, subdivided || alpha != 0.);
|
||||
children_normals[index] = (0., 0., 0.);
|
||||
children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha);
|
||||
//children_color[index] = Color(1., 1., 1., alpha);
|
||||
}
|
||||
}
|
||||
|
||||
ExplicitNTreeNode {
|
||||
structure: std::array::from_fn(|i| children[i]),
|
||||
colors: std::array::from_fn(|i| children_color[i]),
|
||||
normals: std::array::from_fn(|i| children_normals[i]),
|
||||
ProducedChunk {
|
||||
children: std::array::from_fn(|i| children[i]),
|
||||
colors: std::array::from_fn(|i| children_color[i].as_packed_u32()),
|
||||
normals: std::array::from_fn(|i| children_normals[i].into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ProducedChunk<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub children: [ChildInformation; N * N * N],
|
||||
pub colors: [u32; N * N * N],
|
||||
pub normals: [[f32; 3]; N * N * N],
|
||||
}
|
||||
|
||||
pub trait ChunkedProducer<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
@@ -589,7 +477,7 @@ where
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ExplicitNTreeNode<N>;
|
||||
) -> ProducedChunk<N>;
|
||||
}
|
||||
|
||||
pub struct SdfGenerator<const N: usize>
|
||||
@@ -620,7 +508,7 @@ where
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ExplicitNTreeNode<N>
|
||||
) -> ProducedChunk<N>
|
||||
{
|
||||
// let sdf = |x: f32, y: f32, z: f32| {
|
||||
// Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512.
|
||||
@@ -723,16 +611,16 @@ where
|
||||
// (gvz - cz) as f32 / global_size as f32,
|
||||
// alpha,
|
||||
// ));
|
||||
children.push(StructurePointer::new(subdivided, subdivided || alpha != 0.));
|
||||
children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.));
|
||||
children_color.push(Color(color + random::<f32>() * 0.02, color, color, alpha));
|
||||
children_normals.push((normal.x, normal.y, normal.z));
|
||||
//children_color.push(Color(normal.x, normal.y, normal.z, alpha));
|
||||
}
|
||||
|
||||
ExplicitNTreeNode {
|
||||
structure: std::array::from_fn(|i| children[i]),
|
||||
colors: std::array::from_fn(|i| children_color[i]),
|
||||
normals: std::array::from_fn(|i| children_normals[i]),
|
||||
ProducedChunk {
|
||||
children: std::array::from_fn(|i| children[i]),
|
||||
colors: std::array::from_fn(|i| children_color[i].as_packed_u32()),
|
||||
normals: std::array::from_fn(|i| children_normals[i].into()),
|
||||
//normals: std::array::from_fn(|i| (1., 0., 0.)),
|
||||
}
|
||||
}
|
||||
|
||||
+9
-3
@@ -5,9 +5,6 @@ use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use itertools::Itertools;
|
||||
|
||||
use crate::voxel_cache::data::ExplicitNTreeNode;
|
||||
use crate::voxel_cache::data::StructurePointer;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct Color(pub f32, pub f32, pub f32, pub f32);
|
||||
@@ -32,6 +29,15 @@ impl Color
|
||||
c.3 /= count as f32;
|
||||
c
|
||||
}
|
||||
|
||||
pub fn as_packed_u32(&self) -> u32
|
||||
{
|
||||
let mapped_r = (self.0 * 255.0) as u32;
|
||||
let mapped_g = (self.1 * 255.0) as u32;
|
||||
let mapped_b = (self.2 * 255.0) as u32;
|
||||
let mapped_a = (self.3 * 255.0) as u32;
|
||||
mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
||||
+284
-3
@@ -1,16 +1,34 @@
|
||||
use std::num::NonZero;
|
||||
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::Device;
|
||||
|
||||
use crate::gpu::radix_sort::RadixSorter;
|
||||
use crate::gpu_profiler;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::voxel_cache::attributes::CacheAttributes;
|
||||
use crate::voxel_cache::eviction::CacheEvictor;
|
||||
use crate::voxel_cache::insertion::CacheInsertionData;
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
use crate::voxel_cache::pipelines::CacheInsertionPass;
|
||||
use crate::voxel_cache::pipelines::CacheInvalidationPass;
|
||||
use crate::voxel_cache::pipelines::WritePointersPass;
|
||||
use crate::voxel_cache::pipelines::WriteRequestsPass;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::requests::CacheRequestHandler;
|
||||
use crate::voxel_cache::structure::CacheStructure;
|
||||
|
||||
pub mod attributes;
|
||||
pub mod eviction;
|
||||
pub mod insertion;
|
||||
pub mod layout;
|
||||
pub mod pipelines;
|
||||
pub mod requests;
|
||||
pub mod schema;
|
||||
pub mod structure;
|
||||
pub mod tables;
|
||||
|
||||
pub use layout::*;
|
||||
|
||||
/// Stores some ressources that can be reused throughout the modules of the cache
|
||||
struct CacheRessources<const N: usize>
|
||||
@@ -25,7 +43,7 @@ impl<const N: usize> CacheRessources<N>
|
||||
{
|
||||
let scratch_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheRessources::scratch_buffer"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
size: (size_of::<u32>() * page_count * N * N * N) as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
@@ -45,31 +63,294 @@ where
|
||||
{
|
||||
page_count: usize,
|
||||
structure: CacheStructure<N>,
|
||||
attributes: CacheAttributes<N>,
|
||||
request_handler: CacheRequestHandler<N>,
|
||||
evictor: CacheEvictor,
|
||||
|
||||
common_ressources: CacheRessources<N>,
|
||||
|
||||
// Operations
|
||||
write_requests_pass: WriteRequestsPass<N>,
|
||||
cache_insertion_pass: CacheInsertionPass<N>,
|
||||
cache_invalidation_pass: CacheInvalidationPass<N>,
|
||||
write_pointers_pass: WritePointersPass<N>,
|
||||
|
||||
// Raytracing
|
||||
raytrace_bind_group_layout: wgpu::BindGroupLayout,
|
||||
raytrace_bind_group: wgpu::BindGroup,
|
||||
|
||||
frame_timestamp: u32,
|
||||
}
|
||||
|
||||
pub trait CacheInvalidable
|
||||
{
|
||||
fn invalidate(
|
||||
&mut self,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
invalid_timestamp: u32,
|
||||
);
|
||||
}
|
||||
|
||||
pub enum VoxelCacheInsertion<'a, const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable),
|
||||
InternalRequest(&'a CacheInsertionData<N>, &'a CacheRequestBuffer),
|
||||
}
|
||||
|
||||
impl<const N: usize> VoxelCache<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize) -> Self
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
let structure = CacheStructure::new(device, page_count);
|
||||
let attributes = CacheAttributes::from_cache_layout(device, layout, page_count);
|
||||
let request_handler = CacheRequestHandler::new(device, page_count);
|
||||
let evictor = CacheEvictor::new(device, page_count, 0u32);
|
||||
let common_ressources = CacheRessources::new(device, page_count);
|
||||
|
||||
let write_requests_pass = WriteRequestsPass::new(device, page_count, layout);
|
||||
let cache_insertion_pass = CacheInsertionPass::new(device, page_count, layout);
|
||||
let cache_invalidation_pass = CacheInvalidationPass::new(device, page_count, layout);
|
||||
let write_pointers_pass = WritePointersPass::new(device, page_count, layout);
|
||||
|
||||
let (raytrace_bind_group_layout, raytrace_bind_group) = Self::create_raytrace_bind_group(
|
||||
device,
|
||||
&structure,
|
||||
&attributes,
|
||||
&request_handler,
|
||||
&evictor,
|
||||
);
|
||||
|
||||
Self {
|
||||
page_count,
|
||||
structure,
|
||||
attributes,
|
||||
request_handler,
|
||||
evictor,
|
||||
common_ressources,
|
||||
|
||||
write_requests_pass,
|
||||
cache_insertion_pass,
|
||||
cache_invalidation_pass,
|
||||
write_pointers_pass,
|
||||
|
||||
raytrace_bind_group_layout,
|
||||
raytrace_bind_group,
|
||||
|
||||
frame_timestamp: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gather_requests(
|
||||
&self,
|
||||
device: &Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "gather_requests");
|
||||
|
||||
self.request_handler
|
||||
.sort_requests(device, &self.common_ressources, &mut encoder);
|
||||
|
||||
self.write_requests_pass.encode(
|
||||
&mut encoder,
|
||||
device,
|
||||
&self.structure,
|
||||
&self.request_handler,
|
||||
request_buffer,
|
||||
);
|
||||
|
||||
self.request_handler.reset(&mut encoder);
|
||||
}
|
||||
|
||||
/// Inserts new pages into the cache. Two insertion modes are available:
|
||||
///
|
||||
/// External: Inserts brand new pages, regardless of the misses in the cache. This can be used
|
||||
/// to bring external requests into the cache
|
||||
///
|
||||
/// Internal: This is the response to requests emited inside the cache (gotten through the
|
||||
/// gather requests method)
|
||||
pub fn insert(
|
||||
&mut self,
|
||||
device: &Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
insertions: &mut [&mut VoxelCacheInsertion<N>],
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "insertion");
|
||||
let new_timestamp = self.frame_timestamp + 1;
|
||||
|
||||
self.evictor
|
||||
.prepare_eviction_list(device, &self.common_ressources, &mut encoder);
|
||||
|
||||
for insertion in insertions.iter()
|
||||
{
|
||||
match insertion
|
||||
{
|
||||
VoxelCacheInsertion::ExternalRequest(cache_insertion_data, _)
|
||||
| VoxelCacheInsertion::InternalRequest(cache_insertion_data, _) =>
|
||||
{
|
||||
self.cache_insertion_pass.encode(
|
||||
device,
|
||||
&mut encoder,
|
||||
&self.attributes,
|
||||
&self.structure,
|
||||
cache_insertion_data,
|
||||
&self.evictor,
|
||||
new_timestamp,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Invalidate external structures pointing inside the cache
|
||||
for insertion in insertions.iter_mut()
|
||||
{
|
||||
if let VoxelCacheInsertion::ExternalRequest(_, invalidable) = insertion
|
||||
{
|
||||
invalidable.invalidate(&mut encoder, &self.evictor, new_timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
// Invalidate cache pages
|
||||
self.cache_invalidation_pass.encode(
|
||||
&mut encoder,
|
||||
&self.structure,
|
||||
&self.evictor,
|
||||
new_timestamp,
|
||||
);
|
||||
|
||||
// Write internal requests pointers
|
||||
for insertion in insertions.iter_mut()
|
||||
{
|
||||
if let VoxelCacheInsertion::InternalRequest(insertion, request) = insertion
|
||||
{
|
||||
self.write_pointers_pass.encode(
|
||||
&mut encoder,
|
||||
device,
|
||||
&self.structure,
|
||||
request,
|
||||
insertion,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Proceed to new frame
|
||||
self.frame_timestamp = new_timestamp;
|
||||
}
|
||||
|
||||
pub fn current_timestamp(&self) -> u32
|
||||
{
|
||||
self.frame_timestamp
|
||||
}
|
||||
|
||||
fn create_raytrace_bind_group(
|
||||
device: &wgpu::Device,
|
||||
structure: &CacheStructure<N>,
|
||||
attributes: &CacheAttributes<N>,
|
||||
request_handler: &CacheRequestHandler<N>,
|
||||
evictor: &CacheEvictor,
|
||||
) -> (wgpu::BindGroupLayout, wgpu::BindGroup)
|
||||
{
|
||||
let attribute_count = attributes.attribute_buffers().len();
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("VoxelCache::raytrace_bind_group_layout"),
|
||||
entries: &[
|
||||
// Structure pointers
|
||||
wgpu::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,
|
||||
},
|
||||
// Attributes
|
||||
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(
|
||||
NonZero::new(attribute_count as u32)
|
||||
.expect("Null amount of cache attributes."),
|
||||
),
|
||||
},
|
||||
// Request pages
|
||||
wgpu::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,
|
||||
},
|
||||
// Usage pages
|
||||
wgpu::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,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let attributes_bindings = attributes
|
||||
.attribute_buffers()
|
||||
.iter()
|
||||
.map(|buffer| buffer.as_entire_buffer_binding())
|
||||
.collect::<Vec<_>>();
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("VoxelCache::raytrace_bind_group"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: structure.pointer_pages().as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: request_handler.request_pages_buffer().as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: evictor.timestamp_pages_buffer().as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
(bind_group_layout, bind_group)
|
||||
}
|
||||
|
||||
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout
|
||||
{
|
||||
&self.raytrace_bind_group_layout
|
||||
}
|
||||
|
||||
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
&self.raytrace_bind_group
|
||||
}
|
||||
}
|
||||
|
||||
// Utilities
|
||||
@@ -123,7 +404,7 @@ fn create_multi_buffers_bind_group(
|
||||
|
||||
fn create_multi_buffers_bg_bg_layout(
|
||||
device: &Device,
|
||||
buffers: &[&Buffer],
|
||||
buffers: &[&wgpu::Buffer],
|
||||
label: Option<&str>,
|
||||
) -> (wgpu::BindGroupLayout, wgpu::BindGroup)
|
||||
{
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
|
||||
/// Contains instanciated gpu buffers to hold data for cache attributes
|
||||
@@ -17,25 +21,12 @@ impl<const N: usize> CacheAttributes<N>
|
||||
let attribute_buffers = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.create_buffer(device, N, page_count))
|
||||
.map(|attribute| {
|
||||
attribute.create_buffer(device, N * N * N, page_count, BufferUsages::STORAGE)
|
||||
})
|
||||
.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_layout = Self::create_bind_group_layout(device, layout);
|
||||
|
||||
let bind_group_bindings = attribute_buffers
|
||||
.iter()
|
||||
@@ -58,6 +49,27 @@ impl<const N: usize> CacheAttributes<N>
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device, layout: &CacheLayout)
|
||||
-> BindGroupLayout
|
||||
{
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheAttributes::bind_group_layout"),
|
||||
entries: &[wgpu::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: Some(
|
||||
std::num::NonZero::new(layout.attributes.len() as u32)
|
||||
.expect("Cannot create cache attributes with no attributes"),
|
||||
),
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout
|
||||
{
|
||||
&self.bind_group_layout
|
||||
@@ -67,4 +79,9 @@ impl<const N: usize> CacheAttributes<N>
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn attribute_buffers(&self) -> &[Buffer]
|
||||
{
|
||||
&self.attribute_buffers
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/// Contains structure and logic related to eviction logic in the cache.
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::include_wgsl;
|
||||
@@ -10,6 +11,8 @@ 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::create_multi_buffers_bind_group;
|
||||
use crate::voxel_cache::create_multi_buffers_bind_group_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
|
||||
@@ -23,10 +26,17 @@ pub struct CacheEvictor
|
||||
/// Contains indices in LRU order, after sorting
|
||||
lru_list: wgpu::Buffer,
|
||||
|
||||
/// When reusing pages, count of lru pages consumed
|
||||
consumed_count: wgpu::Buffer,
|
||||
|
||||
// Reset lru list pass
|
||||
reset_lru_list_bind_group: BindGroup,
|
||||
reset_lru_list_pass: ComputePipeline,
|
||||
reset_lru_list_dispatch: u32,
|
||||
|
||||
// For external passes
|
||||
bind_group_layout: BindGroupLayout,
|
||||
bind_group: BindGroup,
|
||||
}
|
||||
|
||||
impl CacheEvictor
|
||||
@@ -35,7 +45,7 @@ impl CacheEvictor
|
||||
{
|
||||
let timestamp_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheUsage::timestamp_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
contents: bytemuck::cast_slice(&vec![initial_timestamp; page_count]),
|
||||
});
|
||||
|
||||
@@ -46,10 +56,16 @@ impl CacheEvictor
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let consumed_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheUsage::consumed_count"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::bytes_of(&0u32),
|
||||
});
|
||||
|
||||
let (reset_lru_list_bg_layout, reset_lru_list_bind_group) =
|
||||
create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
[lru_list],
|
||||
&[&lru_list, &consumed_count],
|
||||
Some("CacheEvictor::reset_lru_list_bind_group"),
|
||||
);
|
||||
|
||||
@@ -70,14 +86,26 @@ impl CacheEvictor
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device);
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[×tamp_pages, &lru_list, &consumed_count],
|
||||
Some("CacheEvictor::bind_group"),
|
||||
);
|
||||
|
||||
Self {
|
||||
page_count,
|
||||
timestamp_pages,
|
||||
lru_list,
|
||||
consumed_count,
|
||||
|
||||
reset_lru_list_bind_group,
|
||||
reset_lru_list_pass,
|
||||
reset_lru_list_dispatch: page_count.div_ceil(256) as u32,
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,4 +148,19 @@ impl CacheEvictor
|
||||
radix_sort::RadixSortDirection::Ascending,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
{
|
||||
create_multi_buffers_bind_group_layout(device, 3, Some("CacheEvictor::bind_group_layout"))
|
||||
}
|
||||
|
||||
pub fn timestamp_pages_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
&self.timestamp_pages
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
use std::num::NonZero;
|
||||
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::ShaderStages;
|
||||
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
use crate::voxel_cache::schema::InsertionInformation;
|
||||
use crate::voxel_cache::schema::LocationPage;
|
||||
|
||||
/// Data to be inserted in a cache insertion operation
|
||||
pub struct CacheInsertionData<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// The amount of pages to insert this structure can hold
|
||||
max_page_count: usize,
|
||||
|
||||
/// Amount of pages that the structure actually contains
|
||||
page_count_buffer: wgpu::Buffer,
|
||||
|
||||
/// Information about inserted pages : dense array of [`InsertionInformation<N>`] structs
|
||||
insertion_information: wgpu::Buffer,
|
||||
|
||||
/// Location of the new nodes : dense array of [`LocationPage`] structs
|
||||
location_pages: wgpu::Buffer,
|
||||
|
||||
/// Contains the attributes to import in the cache.
|
||||
attributes: Vec<wgpu::Buffer>,
|
||||
|
||||
/// Contains the indicies of the page in which the data was written
|
||||
destination_indices: wgpu::Buffer,
|
||||
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheInsertionData<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, max_page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
let page_count_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::page_count_buffer"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: size_of::<u32>() as u64,
|
||||
});
|
||||
|
||||
let insertion_information = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::insertion_information"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<InsertionInformation<N>>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let location_pages = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::location_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<LocationPage>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let destination_indices = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::destination_indices"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<u32>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let attributes = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| {
|
||||
attribute.create_buffer(
|
||||
device,
|
||||
N * N * N,
|
||||
max_page_count,
|
||||
BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let bind_group_bindings = attributes
|
||||
.iter()
|
||||
.map(|buffer| buffer.as_entire_buffer_binding())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device, layout);
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheInsertionData::bind_group"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: page_count_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: insertion_information.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: location_pages.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: destination_indices.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: wgpu::BindingResource::BufferArray(&bind_group_bindings),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Self {
|
||||
page_count_buffer,
|
||||
max_page_count,
|
||||
insertion_information,
|
||||
location_pages,
|
||||
destination_indices,
|
||||
attributes,
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device, layout: &CacheLayout)
|
||||
-> BindGroupLayout
|
||||
{
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheInsertionData::bind_group_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,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
visibility: 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()),
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn page_count(&self) -> usize
|
||||
{
|
||||
self.max_page_count
|
||||
}
|
||||
|
||||
pub fn page_count_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
&self.page_count_buffer
|
||||
}
|
||||
|
||||
pub fn insertion_information_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
&self.insertion_information
|
||||
}
|
||||
|
||||
pub fn location_pages_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
&self.location_pages
|
||||
}
|
||||
|
||||
pub fn attributes_buffers(&self) -> &[wgpu::Buffer]
|
||||
{
|
||||
&self.attributes
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use wgpu::BufferUsages;
|
||||
|
||||
/// Defines how a [`VoxelCache`]'s attribute is populated upon populating a page
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CacheAttributeInit
|
||||
{
|
||||
/// Attribute is external : it is copied from the insertion operation
|
||||
@@ -32,6 +32,7 @@ impl CacheAttribute
|
||||
device: &wgpu::Device,
|
||||
child_count: usize,
|
||||
page_count: usize,
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> wgpu::Buffer
|
||||
{
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
@@ -43,8 +44,8 @@ impl CacheAttribute
|
||||
)
|
||||
.as_str(),
|
||||
),
|
||||
size: (self.word_count as usize * page_count * child_count) as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
size: (self.word_count as usize * page_count * child_count * size_of::<u32>()) as u64,
|
||||
usage,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
@@ -69,4 +70,59 @@ impl CacheLayout
|
||||
self.attributes.push(attribute);
|
||||
index
|
||||
}
|
||||
|
||||
/// Produces a wgsl declaration describing this layout :
|
||||
///
|
||||
/// ```wgsl
|
||||
///
|
||||
/// const ATTRIBUTE_COUNT: u32 = /* attribute count */;
|
||||
/// const ATTRIBUTE_WORD_COUNTS: array<u32, ...> = {
|
||||
/// /* word count for attribute 0 */,
|
||||
/// /* word count for attribute 1 */,
|
||||
/// ...
|
||||
/// };
|
||||
///
|
||||
/// const ATTRIBUTE_COPY: array<bool, ...> = {
|
||||
/// /* external? for attribute 0 */,
|
||||
/// /* external? for attribute 1 */,
|
||||
/// ...
|
||||
/// };
|
||||
///
|
||||
/// ```
|
||||
pub fn wgsl_layout_decl(&self) -> String
|
||||
{
|
||||
let mut decl = String::new();
|
||||
|
||||
decl += &format!("const ATTRIBUTE_COUNT: u32 = {};", self.attributes.len());
|
||||
|
||||
// Word counts
|
||||
decl += &format!(
|
||||
"const ATTRIBUTE_WORD_COUNTS: array<u32, {}> = array<u32, {}>(",
|
||||
self.attributes.len(),
|
||||
self.attributes.len()
|
||||
);
|
||||
|
||||
for attribute in self.attributes.iter()
|
||||
{
|
||||
decl += &format!(" {},", attribute.word_count);
|
||||
}
|
||||
|
||||
decl += ");";
|
||||
|
||||
// Copy
|
||||
decl += &format!(
|
||||
"const ATTRIBUTE_COPY: array<bool, {}> = array<bool, {}>(",
|
||||
self.attributes.len(),
|
||||
self.attributes.len()
|
||||
);
|
||||
|
||||
for attribute in self.attributes.iter()
|
||||
{
|
||||
decl += &format!(" {},", attribute.init == CacheAttributeInit::External);
|
||||
}
|
||||
|
||||
decl += ");";
|
||||
|
||||
decl
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::indirect_buffer::IndirectBuffer1D;
|
||||
use crate::gpu_profiler;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::voxel_cache::attributes::CacheAttributes;
|
||||
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
|
||||
use crate::voxel_cache::eviction::CacheEvictor;
|
||||
use crate::voxel_cache::insertion::CacheInsertionData;
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::requests::CacheRequestHandler;
|
||||
use crate::voxel_cache::structure::CacheStructure;
|
||||
|
||||
macro_rules! programmatic_common_wgsl {
|
||||
($children_count:ident, $page_count:ident, $cache_layout:ident) => {
|
||||
format!(
|
||||
"
|
||||
const CHILDREN_COUNT: u32 = u32({});
|
||||
const PAGE_COUNT: u32 = u32({});
|
||||
|
||||
// Cache layout
|
||||
{}
|
||||
",
|
||||
$children_count * $children_count * $children_count,
|
||||
$page_count,
|
||||
$cache_layout.wgsl_layout_decl()
|
||||
)
|
||||
.as_str()
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! include_cache_wgsl {
|
||||
($path:literal, $children_count:ident, $page_count:ident, $cache_layout:ident) => {{
|
||||
let mut full_shader = String::new();
|
||||
|
||||
full_shader.push_str(include_str!("./shaders/common.wgsl"));
|
||||
full_shader.push_str(programmatic_common_wgsl!(
|
||||
$children_count,
|
||||
$page_count,
|
||||
$cache_layout
|
||||
));
|
||||
full_shader.push_str(include_str!("./shaders/cache_common.wgsl"));
|
||||
full_shader.push_str(include_str!($path));
|
||||
|
||||
wgpu::ShaderModuleDescriptor {
|
||||
label: Some($path),
|
||||
source: wgpu::ShaderSource::Wgsl(full_shader.into()),
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
pub(super) use include_cache_wgsl;
|
||||
|
||||
pub struct WriteRequestsPass<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pipeline: ComputePipeline,
|
||||
// To compute indirect dispatch count from request count
|
||||
indirect_buffer: IndirectBuffer1D,
|
||||
}
|
||||
|
||||
impl<const N: usize> WriteRequestsPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, cache_layout: &CacheLayout) -> Self
|
||||
{
|
||||
// Binds
|
||||
// - structure
|
||||
// - request buffer
|
||||
|
||||
let bindings = [
|
||||
// To get the location information
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// To get which pages have had a request issued on them
|
||||
Some(&CacheRequestHandler::<N>::create_bind_group_layout(device)),
|
||||
// To write the request information to target
|
||||
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
|
||||
];
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("WriteRequestsPass::pipeline_layout"),
|
||||
bind_group_layouts: &bindings,
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(include_cache_wgsl!(
|
||||
"./shaders/write_requests.wgsl",
|
||||
N,
|
||||
page_count,
|
||||
cache_layout
|
||||
));
|
||||
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("WriteRequestsPass::pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("write_requests"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
pipeline,
|
||||
indirect_buffer: IndirectBuffer1D::new(device),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(
|
||||
&self,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
device: &Device,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
cache_request_handler: &CacheRequestHandler<N>,
|
||||
target_request_buffer: &CacheRequestBuffer,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "WriteRequests");
|
||||
|
||||
let indirect_dispatch_buffer = self.indirect_buffer.workgroup_count(
|
||||
device,
|
||||
&mut encoder,
|
||||
cache_request_handler.request_count_buffer(),
|
||||
256,
|
||||
);
|
||||
|
||||
encoder.copy_buffer_to_buffer(
|
||||
cache_request_handler.request_count_buffer(),
|
||||
0,
|
||||
&target_request_buffer.request_count,
|
||||
0,
|
||||
cache_request_handler.request_count_buffer().size(),
|
||||
);
|
||||
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("WriteRequestsPass::pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
|
||||
pass.set_bind_group(1, cache_request_handler.bind_group(), &[]);
|
||||
pass.set_bind_group(2, target_request_buffer.bind_group(), &[]);
|
||||
|
||||
pass.dispatch_workgroups_indirect(indirect_dispatch_buffer, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts new pages in the cache
|
||||
pub struct CacheInsertionPass<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// Copies new pages into cache using LRU order
|
||||
write_pipeline: ComputePipeline,
|
||||
|
||||
/// u32 buffer containing amount of inserted data of current pass
|
||||
inserted_count: wgpu::Buffer,
|
||||
inserted_count_bind_group: wgpu::BindGroup,
|
||||
|
||||
/// Reports the consumed pages to the evictor by incrementing the consumed pages count
|
||||
consume_pipeline: ComputePipeline,
|
||||
|
||||
/// To dispatch the correct amount of writters depending on the amout of pages to insert
|
||||
indirect_dispatcher: IndirectBuffer1D,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheInsertionPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
// Binds
|
||||
// - structure
|
||||
// - request buffer
|
||||
|
||||
let inserted_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheInsertionPass::inserted_count"),
|
||||
contents: bytemuck::bytes_of(&0u32),
|
||||
usage: BufferUsages::STORAGE,
|
||||
});
|
||||
|
||||
let (inserted_count_bind_group_layout, inserted_count_bind_group) =
|
||||
create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
&[&inserted_count],
|
||||
Some("CacheInsertionPass::inserted_count_bind_group"),
|
||||
);
|
||||
|
||||
let bindings = [
|
||||
// To write the new attributes
|
||||
Some(&CacheAttributes::<N>::create_bind_group_layout(
|
||||
device, layout,
|
||||
)),
|
||||
// To write the new locations, pointers
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// New incoming attributes
|
||||
Some(&CacheInsertionData::<N>::create_bind_group_layout(
|
||||
device, layout,
|
||||
)),
|
||||
// To get recyclable pages, and mark pages dirty
|
||||
Some(&CacheEvictor::create_bind_group_layout(device)),
|
||||
Some(&inserted_count_bind_group_layout),
|
||||
];
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("CacheInsertionPass::pipeline_layout"),
|
||||
bind_group_layouts: &bindings,
|
||||
|
||||
// To pass the new timestamp
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(include_cache_wgsl!(
|
||||
"./shaders/insertion.wgsl",
|
||||
N,
|
||||
page_count,
|
||||
layout
|
||||
));
|
||||
|
||||
let write_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheInsertionPass::write_pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("insertion"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let consume_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheInsertionPass::consume_pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("consume"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
write_pipeline,
|
||||
consume_pipeline,
|
||||
inserted_count,
|
||||
inserted_count_bind_group,
|
||||
indirect_dispatcher: IndirectBuffer1D::new(device),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn encode(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
cache_attributes: &CacheAttributes<N>,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
insertion_data: &CacheInsertionData<N>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
timestamp: u32,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "PageInsertion");
|
||||
|
||||
let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count(
|
||||
device,
|
||||
&mut encoder,
|
||||
insertion_data.page_count_buffer(),
|
||||
256,
|
||||
);
|
||||
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("CacheInsertionPass::pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
pass.set_bind_group(0, cache_attributes.bind_group(), &[]);
|
||||
pass.set_bind_group(1, cache_structure.bind_group(), &[]);
|
||||
pass.set_bind_group(2, insertion_data.bind_group(), &[]);
|
||||
pass.set_bind_group(3, cache_evictor.bind_group(), &[]);
|
||||
pass.set_bind_group(4, &self.inserted_count_bind_group, &[]);
|
||||
|
||||
// Write pass
|
||||
pass.set_pipeline(&self.write_pipeline);
|
||||
pass.set_immediates(0, bytemuck::bytes_of(×tamp));
|
||||
pass.dispatch_workgroups_indirect(indirect_write_dispatch, 0);
|
||||
|
||||
// Consume pass
|
||||
pass.set_pipeline(&self.consume_pipeline);
|
||||
pass.set_immediates(0, bytemuck::bytes_of(&0u32)); // Unused
|
||||
pass.dispatch_workgroups(1, 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalidates pointers that are pointing to recycled pages
|
||||
pub struct CacheInvalidationPass<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
workgroup_count: u32,
|
||||
pipeline: ComputePipeline,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheInvalidationPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
// Binds
|
||||
// - structure
|
||||
// - request buffer
|
||||
|
||||
let bindings = [
|
||||
// To find where pages are pointing
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// To read timestamp on which invalidation is marked
|
||||
Some(&CacheEvictor::create_bind_group_layout(device)),
|
||||
];
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("CacheInvalidationPass::pipeline_layout"),
|
||||
bind_group_layouts: &bindings,
|
||||
|
||||
// For setting the correct timestamp after invalidation
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(include_cache_wgsl!(
|
||||
"./shaders/invalidation.wgsl",
|
||||
N,
|
||||
page_count,
|
||||
layout
|
||||
));
|
||||
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheInvalidationPass::pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("invalidation"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
workgroup_count: page_count.div_ceil(256) as u32,
|
||||
pipeline,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(
|
||||
&self,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
timestamp: u32,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "CacheInvalidation");
|
||||
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("CacheInvalidationPass::pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
|
||||
pass.set_bind_group(1, cache_evictor.bind_group(), &[]);
|
||||
|
||||
pass.set_immediates(0, bytemuck::bytes_of(×tamp));
|
||||
|
||||
pass.dispatch_workgroups(self.workgroup_count, 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Points the pages to the newly cached pages
|
||||
pub struct WritePointersPass<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pipeline: ComputePipeline,
|
||||
indirect_buffer: IndirectBuffer1D,
|
||||
}
|
||||
|
||||
impl<const N: usize> WritePointersPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
let bindings = [
|
||||
// To find where pages are pointing
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// To find where the requests came from
|
||||
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
|
||||
// To find where the request's response went
|
||||
Some(&CacheInsertionData::<N>::create_bind_group_layout(
|
||||
device, layout,
|
||||
)),
|
||||
];
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("WritePointersPass::pipeline_layout"),
|
||||
bind_group_layouts: &bindings,
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(include_cache_wgsl!(
|
||||
"./shaders/write_pointers.wgsl",
|
||||
N,
|
||||
page_count,
|
||||
layout
|
||||
));
|
||||
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("WritePointersPass::pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("write_pointers"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
pipeline,
|
||||
indirect_buffer: IndirectBuffer1D::new(device),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(
|
||||
&self,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
device: &Device,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
cache_insertion_data: &CacheInsertionData<N>,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "WritePointers");
|
||||
|
||||
let indirect_buffer = self.indirect_buffer.workgroup_count(
|
||||
device,
|
||||
&mut encoder,
|
||||
cache_insertion_data.page_count_buffer(),
|
||||
256,
|
||||
);
|
||||
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("WritePointersPass::pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
|
||||
pass.set_bind_group(1, request_buffer.bind_group(), &[]);
|
||||
pass.set_bind_group(2, cache_insertion_data.bind_group(), &[]);
|
||||
|
||||
pass.dispatch_workgroups_indirect(indirect_buffer, 0);
|
||||
}
|
||||
}
|
||||
+202
-25
@@ -1,4 +1,8 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
@@ -11,6 +15,8 @@ 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::create_multi_buffers_bind_group;
|
||||
use crate::voxel_cache::create_multi_buffers_bind_group_layout;
|
||||
use crate::voxel_cache::schema::RequestInformation;
|
||||
use crate::voxel_cache::schema::RequestMeta;
|
||||
|
||||
@@ -21,15 +27,22 @@ pub struct CacheRequestHandler<const N: usize>
|
||||
/// This can then be used to prioritize request based on demand
|
||||
request_counts_pages: wgpu::Buffer,
|
||||
|
||||
// Ultimately contains sorted requests
|
||||
/// Ultimately contains sorted requests
|
||||
sorted_requests: wgpu::Buffer,
|
||||
|
||||
/// Number of requests
|
||||
request_count: wgpu::Buffer,
|
||||
|
||||
compactor: NonZeroBufferCompactor,
|
||||
|
||||
// Pass to reset the requests
|
||||
reset_pass_bind_group: BindGroup,
|
||||
reset_pass: ComputePipeline,
|
||||
reset_pass_dispatch: u32,
|
||||
|
||||
// External bind group
|
||||
bind_group_layout: BindGroupLayout,
|
||||
bind_group: BindGroup,
|
||||
}
|
||||
|
||||
/// Records requests made by the cache
|
||||
@@ -45,6 +58,9 @@ pub struct CacheRequestBuffer
|
||||
|
||||
/// Buffer containing the meta information about the requests, a dense array of [`voxel_cache::schema::RequestMeta`]
|
||||
request_meta: wgpu::Buffer,
|
||||
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheRequestHandler<N>
|
||||
@@ -63,9 +79,17 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]),
|
||||
});
|
||||
|
||||
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::request_count"),
|
||||
usage: wgpu::BufferUsages::STORAGE
|
||||
| wgpu::BufferUsages::COPY_DST
|
||||
| wgpu::BufferUsages::COPY_SRC,
|
||||
contents: bytemuck::bytes_of(&0u32),
|
||||
});
|
||||
|
||||
let (reset_pass_bg_layout, reset_pass_bind_group) = create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
[request_counts_pages],
|
||||
&[&request_counts_pages],
|
||||
Some("CacheRequestHandler::reset_pass_bind_group"),
|
||||
);
|
||||
|
||||
@@ -85,14 +109,26 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device);
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[&request_count, &sorted_requests],
|
||||
Some("CacheRequestHandler::bind_group"),
|
||||
);
|
||||
|
||||
Self {
|
||||
request_counts_pages,
|
||||
sorted_requests,
|
||||
compactor: NonZeroBufferCompactor::new(device, page_count),
|
||||
request_count,
|
||||
compactor: NonZeroBufferCompactor::new(device, page_count * N * N * N),
|
||||
|
||||
reset_pass_bind_group,
|
||||
reset_pass,
|
||||
reset_pass_dispatch: (page_count as u32).div_ceil(256),
|
||||
reset_pass_dispatch: ((page_count * N * N * N) as u32).div_ceil(256),
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,23 +141,25 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
&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),
|
||||
);
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "compaction");
|
||||
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);
|
||||
.copy_count_to_buffer(&mut encoder, &self.request_count);
|
||||
|
||||
// State:
|
||||
// At this point the `sorted_requests` buffer contains the compacted indices of the request counts
|
||||
@@ -132,15 +170,42 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
|
||||
// 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(
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "radix");
|
||||
ressources.radix_sorter.sort(
|
||||
device,
|
||||
&ressources.scratch_buffer,
|
||||
&self.sorted_requests,
|
||||
Some(&self.request_count),
|
||||
None,
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Descending,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
{
|
||||
create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
&ressources.scratch_buffer,
|
||||
&self.sorted_requests,
|
||||
Some(request_count),
|
||||
None,
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Descending,
|
||||
);
|
||||
2,
|
||||
Some("CacheRequestHandler::bind_group_layout"),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn request_count_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
&self.request_count
|
||||
}
|
||||
|
||||
pub fn request_pages_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
&self.request_counts_pages
|
||||
}
|
||||
|
||||
/// Resets the RequestHandlers request buffer for a next cache usage.
|
||||
@@ -148,8 +213,8 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
{
|
||||
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.set_bind_group(0, Some(&self.reset_pass_bind_group), &[]);
|
||||
compute_pass.dispatch_workgroups(self.reset_pass_dispatch, 1, 1);
|
||||
}
|
||||
}
|
||||
@@ -161,29 +226,141 @@ impl CacheRequestBuffer
|
||||
{
|
||||
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestBuffer::request_count"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
usage: wgpu::BufferUsages::STORAGE
|
||||
| wgpu::BufferUsages::COPY_SRC
|
||||
| wgpu::BufferUsages::COPY_DST,
|
||||
contents: bytemuck::bytes_of(&0u32),
|
||||
});
|
||||
|
||||
let request_informations = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheRequestBuffer::request_informations"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
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,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
size: (size_of::<RequestMeta>() * max_requests) as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device);
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[&request_count, &request_informations, &request_meta],
|
||||
Some("CacheRequestBuffer::bind_group"),
|
||||
);
|
||||
|
||||
Self {
|
||||
max_requests,
|
||||
request_count,
|
||||
request_informations,
|
||||
request_meta,
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &Device) -> BindGroupLayout
|
||||
{
|
||||
create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
3,
|
||||
Some("CacheRequestBuffer::bind_group_layout"),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn host_download_requests<F: FnMut(&[RequestInformation]) + Send + Sync + 'static>(
|
||||
&self,
|
||||
device: &Device,
|
||||
queue: &wgpu::Queue,
|
||||
callback: F,
|
||||
)
|
||||
{
|
||||
// Once the two required buffer have been mapped, the requestMapState will automatically
|
||||
// fire the callback
|
||||
let request_map_state = Arc::new(Mutex::new(RequestMapState::new(callback)));
|
||||
|
||||
let request_map_state_1 = request_map_state.clone();
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&self.request_count.slice(..),
|
||||
move |buffer| {
|
||||
let mapped_buffer = buffer.expect("Could not map request buffer (count).");
|
||||
let request_count: u32 = bytemuck::pod_read_unaligned(&mapped_buffer);
|
||||
|
||||
request_map_state_1
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_request_count(request_count as usize);
|
||||
},
|
||||
);
|
||||
|
||||
let request_map_state_2 = request_map_state.clone();
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&self.request_informations.slice(..),
|
||||
move |buffer| {
|
||||
let mapped_buffer = buffer.expect("Could not map request buffer (informations).");
|
||||
let request_infos: Vec<RequestInformation> =
|
||||
bytemuck::pod_collect_to_vec(&mapped_buffer);
|
||||
|
||||
request_map_state_2
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_request_infos(request_infos);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
struct RequestMapState<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static>
|
||||
{
|
||||
request_count: Option<usize>,
|
||||
request_infos: Option<Vec<RequestInformation>>,
|
||||
callback: F,
|
||||
}
|
||||
|
||||
impl<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static> RequestMapState<F>
|
||||
{
|
||||
pub fn new(callback: F) -> Self
|
||||
{
|
||||
Self {
|
||||
request_count: None,
|
||||
request_infos: None,
|
||||
callback,
|
||||
}
|
||||
}
|
||||
|
||||
fn try_callback(&mut self)
|
||||
{
|
||||
if let (Some(request_count), Some(request_infos)) =
|
||||
(self.request_count, &self.request_infos)
|
||||
{
|
||||
(self.callback)(&request_infos[0..request_count])
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_request_count(&mut self, request_count: usize)
|
||||
{
|
||||
self.request_count = Some(request_count);
|
||||
self.try_callback();
|
||||
}
|
||||
|
||||
pub fn set_request_infos(&mut self, request_infos: Vec<RequestInformation>)
|
||||
{
|
||||
self.request_infos = Some(request_infos);
|
||||
self.try_callback();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/// Contains definitions of the data layouts for the cache
|
||||
use std::ops::BitOr;
|
||||
|
||||
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
|
||||
@@ -85,7 +86,7 @@ impl From<u32> for CachePointer
|
||||
/// 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)]
|
||||
#[derive(Debug, Clone, Copy, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct StructurePage<const N: usize>
|
||||
where
|
||||
@@ -95,6 +96,9 @@ where
|
||||
pub pointers: [CachePointer; N * N * N],
|
||||
}
|
||||
|
||||
// SAFETY: u64, then packed u32s ([`CachePointer`]s), so no padding, all bit patterns are allowed
|
||||
unsafe impl<const N: usize> Pod for StructurePage<N> where [(); N * N * N]: {}
|
||||
|
||||
/// Data stored alongside cache structure so that application can locate a
|
||||
/// particular request
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
@@ -149,3 +153,63 @@ pub struct RequestMeta
|
||||
/// The children on which the request was issued
|
||||
pub children_index: u32,
|
||||
}
|
||||
|
||||
/// Structure information about the children of a node.
|
||||
/// Used when inserting data in the cache, to setup structure pointers
|
||||
///
|
||||
/// A specific child of a node being inserted can be in four state by
|
||||
///
|
||||
/// Whether it can be subdivided further or not
|
||||
/// Whether it is considered occupied or not
|
||||
/// 31st bit : subdivisable?
|
||||
/// 30th bit : occupied?
|
||||
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct ChildInformation(u32);
|
||||
|
||||
impl ChildInformation
|
||||
{
|
||||
pub const NONE: Self = Self(0);
|
||||
pub const SUBDIVISABLE: Self = Self(1 << 31);
|
||||
pub const OCCUPIED: Self = Self(1 << 30);
|
||||
|
||||
pub fn new(subdivisable: bool, occupied: bool) -> Self
|
||||
{
|
||||
let mut n = Self::NONE;
|
||||
if subdivisable
|
||||
{
|
||||
n = n | Self::SUBDIVISABLE;
|
||||
}
|
||||
|
||||
if occupied
|
||||
{
|
||||
n = n | Self::OCCUPIED;
|
||||
}
|
||||
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
impl BitOr for ChildInformation
|
||||
{
|
||||
type Output = Self;
|
||||
|
||||
fn bitor(self, rhs: Self) -> Self::Output
|
||||
{
|
||||
Self(self.0 | rhs.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Information given for an page insertion operation
|
||||
#[derive(Debug, Clone, Copy, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct InsertionInformation<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// Information to setup structure pointers
|
||||
pub children: [ChildInformation; N * N * N],
|
||||
}
|
||||
|
||||
// SAFETY: Packed array of u32, no padding, all bit patterns allowed
|
||||
unsafe impl<const N: usize> Pod for InsertionInformation<N> where [(); N * N * N]: {}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// For things that depend upon the cache layout/children count
|
||||
|
||||
struct PointerPage
|
||||
{
|
||||
occupancy_low: u32,
|
||||
occupancy_high: u32,
|
||||
pointers: array<u32, CHILDREN_COUNT>,
|
||||
}
|
||||
|
||||
struct InsertionInformation
|
||||
{
|
||||
/// [`ChildInformation`] in schema.rs
|
||||
children: array<u32, CHILDREN_COUNT>
|
||||
}
|
||||
|
||||
// Takes index of pointer and gives cache index
|
||||
fn pointer_index_to_cache_index(request_index: u32) -> CacheIndex
|
||||
{
|
||||
var cache_index: CacheIndex;
|
||||
cache_index.page_index = request_index / CHILDREN_COUNT;
|
||||
cache_index.children_index = request_index % CHILDREN_COUNT;
|
||||
return cache_index;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
enable wgpu_binding_array;
|
||||
|
||||
struct CacheIndex
|
||||
{
|
||||
page_index: u32,
|
||||
children_index: u32,
|
||||
}
|
||||
struct RequestInformation
|
||||
{
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
children_index: u32
|
||||
}
|
||||
|
||||
struct RequestMeta
|
||||
{
|
||||
page_index: u32,
|
||||
children_index: u32
|
||||
}
|
||||
|
||||
struct AttributeArray
|
||||
{
|
||||
values: array<u32>
|
||||
}
|
||||
|
||||
struct LocationPage
|
||||
{
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
}
|
||||
|
||||
struct DepthPage
|
||||
{
|
||||
depth: u32
|
||||
}
|
||||
|
||||
|
||||
fn child_information_occupied(info: u32) -> bool
|
||||
{
|
||||
return ((info >> 30) & 1) != 0;
|
||||
}
|
||||
|
||||
fn child_information_subdivided(info: u32) -> bool
|
||||
{
|
||||
return ((info >> 31) & 1) != 0;
|
||||
}
|
||||
|
||||
// Makes an empty child pointer, which can be subdivisible or not
|
||||
// but not available
|
||||
fn child_pointer_empty(subdivisible: bool) -> u32
|
||||
{
|
||||
return select(u32(0), u32(1), subdivisible) << 31;
|
||||
}
|
||||
|
||||
fn child_pointer_subdivided(pointer: u32) -> bool
|
||||
{
|
||||
return ((pointer >> 31) & 1) != 0;
|
||||
}
|
||||
|
||||
fn child_pointer_available(pointer: u32) -> bool
|
||||
{
|
||||
// both bits set ?
|
||||
return pointer >> 30 == u32(3);
|
||||
}
|
||||
|
||||
fn child_pointer_pointer(pointer: u32) -> u32
|
||||
{
|
||||
return pointer & u32(0x3FFFFFFF);
|
||||
}
|
||||
|
||||
fn child_pointer_make_available(pointer: u32) -> u32
|
||||
{
|
||||
return pointer | 0xC0000000;
|
||||
}
|
||||
@@ -1,17 +1,19 @@
|
||||
@group(0) @binding(0) lru_list: array<u32>;
|
||||
@group(0) @binding(0) var<storage, read_write> lru_list: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> consumed_count: u32;
|
||||
|
||||
/// Resets the lru list
|
||||
@compute
|
||||
@workgroups(256, 1, 1)
|
||||
fn reset_lru_list(@builting(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn reset_lru_list(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
{
|
||||
let index = global_invocation_id.x;
|
||||
if(index >= array_length(&request_count_pages))
|
||||
if(index >= arrayLength(&lru_list))
|
||||
{
|
||||
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;
|
||||
lru_list[index] = index;
|
||||
consumed_count = 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Group 0: Table pointers
|
||||
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>; // Request count
|
||||
|
||||
// Group 1: Cache insertion data
|
||||
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
|
||||
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
|
||||
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(1) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
|
||||
|
||||
/// Group 2: Request buffer
|
||||
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@group(2) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(2) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
if(index >= insertion_data_page_count_buffer)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let destination = insertion_data_destination_indices[index];
|
||||
if(destination != 0xFFFFFFFF)
|
||||
{
|
||||
let request_location = request_buffer_informations[index].structure_id;
|
||||
fixed_table_pointers[request_location] = child_pointer_make_available(insertion_data_destination_indices[index]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/// Group 0: Table pointers
|
||||
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>; // Request count
|
||||
|
||||
// Group 1: Cache evictor
|
||||
@group(1) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
|
||||
@group(1) @binding(1) var<storage, read_write> cache_evictor_lru_pages: array<u32>;
|
||||
@group(1) @binding(2) var<storage, read_write> cache_evictor_consumed_count: u32;
|
||||
|
||||
var<immediate> new_timestamp: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn invalidation(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
let table_length = arrayLength(&fixed_table_pointers);
|
||||
if(index >= table_length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let pointer = fixed_table_pointers[index];
|
||||
if(pointer_invalid(pointer))
|
||||
{
|
||||
// Invalidate
|
||||
fixed_table_pointers[index] = child_pointer_empty(child_pointer_subdivided(pointer));
|
||||
}
|
||||
}
|
||||
|
||||
fn pointer_invalid(pointer: u32) -> bool
|
||||
{
|
||||
if(child_pointer_available(pointer))
|
||||
{
|
||||
let pointer = child_pointer_pointer(pointer);
|
||||
let pointed_timestamp = cache_evictor_timestamps[pointer];
|
||||
|
||||
// Is dirty marker ?
|
||||
return pointed_timestamp == new_timestamp;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/// Group 0: Cache request handler
|
||||
@group(0) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
|
||||
@group(0) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
|
||||
|
||||
/// Group 1: Request buffer
|
||||
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
request_buffer_count = request_handler_count;
|
||||
if(index >= request_handler_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var request_info: RequestInformation;
|
||||
request_info.structure_id = request_handler_requests[index];
|
||||
request_info.node_id = 0;
|
||||
request_info.children_index = 0;
|
||||
|
||||
var request_meta: RequestMeta;
|
||||
request_meta.page_index = 0;
|
||||
request_meta.children_index = 0;
|
||||
|
||||
request_buffer_informations[index] = request_info;
|
||||
request_buffer_meta[index] = request_meta;
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
|
||||
// Group 0: cache_attributes
|
||||
@group(0) @binding(0) var<storage, read_write> cache_attributes: binding_array<AttributeArray>;
|
||||
|
||||
/// Group 1: Cache structure
|
||||
@group(1) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
|
||||
@group(1) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
|
||||
@group(1) @binding(2) var<storage, read_write> structure_depth_pages: array<DepthPage>;
|
||||
|
||||
// Group 2: Cache insertion data
|
||||
@group(2) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
|
||||
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
|
||||
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(2) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
|
||||
|
||||
// Group 3: Cache evictor
|
||||
@group(3) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
|
||||
@group(3) @binding(1) var<storage, read_write> cache_evictor_lru_pages: array<u32>;
|
||||
@group(3) @binding(2) var<storage, read_write> cache_evictor_consumed_count: u32;
|
||||
|
||||
// Group 4: Inserted count
|
||||
@group(4) @binding(0) var<storage, read_write> pass_inserted_count: atomic<u32>;
|
||||
|
||||
var<immediate> new_timestamp: u32;
|
||||
|
||||
// Computes amount of available LRU pages
|
||||
fn available_amount() -> u32
|
||||
{
|
||||
let lru_remaining = arrayLength(&cache_evictor_timestamps) - cache_evictor_consumed_count;
|
||||
let available_amount = min(lru_remaining, insertion_data_page_count_buffer);
|
||||
|
||||
return available_amount;
|
||||
}
|
||||
|
||||
@compute
|
||||
@workgroup_size(1, 1, 1)
|
||||
fn consume(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
// Report consumed amount of LRU pages to cache evictor
|
||||
// So that subsequent insertions can can continue to use new pages
|
||||
cache_evictor_consumed_count += atomicLoad(&pass_inserted_count);
|
||||
atomicStore(&pass_inserted_count, 0);
|
||||
}
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
//let insertion_count = min(array_length(&insertion_data_information), insertion_data_page_count_buffer);
|
||||
let insertion_count = available_amount();
|
||||
|
||||
if(index >= insertion_data_page_count_buffer)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if(index >= insertion_count)
|
||||
{
|
||||
// Report that page was not written
|
||||
insertion_data_destination_indices[index] = 0xFFFFFFFF;
|
||||
return;
|
||||
}
|
||||
|
||||
// Get a page to evict
|
||||
let page_index = cache_evictor_lru_pages[index + cache_evictor_consumed_count];
|
||||
let page_timestamp = cache_evictor_timestamps[page_index];
|
||||
|
||||
if(page_timestamp >= new_timestamp - 1)
|
||||
{
|
||||
// Do not insert page
|
||||
insertion_data_destination_indices[index] = 0xFFFFFFFF;
|
||||
return;
|
||||
}
|
||||
|
||||
atomicAdd(&pass_inserted_count, 1);
|
||||
insertion_data_destination_indices[index] = page_index;
|
||||
|
||||
// Copy new location
|
||||
structure_location_pages[page_index] = insertion_data_location_pages[index];
|
||||
|
||||
// Copy new pointers
|
||||
let new_pointers = insertion_info_to_pointer_page(insertion_data_information[index]);
|
||||
structure_pointer_pages[page_index] = new_pointers;
|
||||
|
||||
// Mark page as dirty for invalidation
|
||||
cache_evictor_timestamps[page_index] = new_timestamp;
|
||||
|
||||
// Copy new depth
|
||||
// TODO: Copy new depth
|
||||
|
||||
// Copy attributes
|
||||
for(var attribute_index = u32(0); attribute_index < ATTRIBUTE_COUNT; attribute_index ++)
|
||||
{
|
||||
if(!ATTRIBUTE_COPY[attribute_index])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var page_stride = CHILDREN_COUNT * ATTRIBUTE_WORD_COUNTS[attribute_index];
|
||||
var dest_offset = page_stride * page_index;
|
||||
var src_offset = page_stride * index;
|
||||
|
||||
// Copy all words of the attribute page
|
||||
for(var word = u32(0); word < page_stride; word ++)
|
||||
{
|
||||
cache_attributes[attribute_index].values[dest_offset + word] = insertion_data_attributes[attribute_index].values[src_offset + word];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage
|
||||
{
|
||||
var page: PointerPage;
|
||||
|
||||
var occupancy_low = u32(0);
|
||||
var occupancy_high = u32(0);
|
||||
for(var i = u32(0); i < CHILDREN_COUNT; i++)
|
||||
{
|
||||
let insert_info = info.children[i];
|
||||
|
||||
// Pointer
|
||||
page.pointers[i] = child_pointer_empty(child_information_subdivided(insert_info));
|
||||
|
||||
// Occupancy
|
||||
var bit = select(u32(0), u32(1), child_information_occupied(insert_info));
|
||||
|
||||
// Dispatch set bit on low or high word
|
||||
bit = bit << (i % u32(32));
|
||||
if(i < 32)
|
||||
{
|
||||
occupancy_low |= bit;
|
||||
}
|
||||
else
|
||||
{
|
||||
occupancy_high |= bit;
|
||||
}
|
||||
}
|
||||
|
||||
page.occupancy_low = occupancy_low;
|
||||
page.occupancy_high = occupancy_high;
|
||||
|
||||
return page;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/// Group 0: Cache structure
|
||||
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
|
||||
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
|
||||
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<DepthPage>;
|
||||
|
||||
// Group 1: Cache evictor
|
||||
@group(1) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
|
||||
@group(1) @binding(1) var<storage, read_write> cache_evictor_lru_pages: array<u32>;
|
||||
@group(1) @binding(2) var<storage, read_write> cache_evictor_consumed_count: u32;
|
||||
|
||||
var<immediate> new_timestamp: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn invalidation(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
if(index >= arrayLength(&structure_pointer_pages)) { return; }
|
||||
|
||||
for(var i = u32(0); i < CHILDREN_COUNT; i++)
|
||||
{
|
||||
if(pointer_invalid(structure_pointer_pages[index].pointers[i]))
|
||||
{
|
||||
pointer_invalidate(index, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pointer_invalid(pointer: u32) -> bool
|
||||
{
|
||||
if(child_pointer_available(pointer))
|
||||
{
|
||||
let pointer = child_pointer_pointer(pointer);
|
||||
let pointed_timestamp = cache_evictor_timestamps[pointer];
|
||||
|
||||
// Is dirty marker ?
|
||||
return pointed_timestamp == new_timestamp;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
fn pointer_invalidate(page_index: u32, child_index: u32)
|
||||
{
|
||||
let pointer = structure_pointer_pages[page_index].pointers[child_index];
|
||||
let pointed_page = child_pointer_pointer(pointer);
|
||||
|
||||
let new_pointer = child_pointer_empty(child_pointer_subdivided(pointer));
|
||||
structure_pointer_pages[page_index].pointers[child_index] = new_pointer;
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
@group(0) @binding(0) request_count_pages: array<u32>;
|
||||
@group(0) @binding(0) var<storage, read_write> 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>)
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn reset_requests(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
{
|
||||
let index = global_invocation_id.x;
|
||||
if(index >= array_length(&request_count_pages))
|
||||
if(index >= arrayLength(&request_count_pages))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
request_count_pages = 0;
|
||||
request_count_pages[index] = 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/// Group 0: Cache structure
|
||||
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
|
||||
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
|
||||
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<DepthPage>;
|
||||
|
||||
/// Group 1: Request buffer
|
||||
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
// Group 2: Cache insertion data
|
||||
@group(2) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
|
||||
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
|
||||
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(2) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
if(index >= request_buffer_count || index >= insertion_data_page_count_buffer) { return; }
|
||||
|
||||
// The write pages pass establishes a one-to-one corresepondancy
|
||||
// between requests and recycled pages
|
||||
let meta_inf = request_buffer_meta[index];
|
||||
let page_index = insertion_data_destination_indices[index];
|
||||
|
||||
if(page_index != 0xFFFFFFFF)
|
||||
{
|
||||
structure_pointer_pages[meta_inf.page_index].pointers[meta_inf.children_index]
|
||||
= child_pointer_make_available(page_index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/// Pipeline to write the requests out in to the request buffer
|
||||
|
||||
/// Group 0: Cache structure
|
||||
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
|
||||
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
|
||||
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<DepthPage>;
|
||||
|
||||
/// Group 1: Cache request handler
|
||||
@group(1) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
|
||||
@group(1) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
|
||||
|
||||
/// Group 3: Request buffer
|
||||
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@group(2) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(2) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
|
||||
// Max size of request buffer and request count
|
||||
let max_requests =
|
||||
min(arrayLength(&request_buffer_informations), request_handler_count);
|
||||
if(index >= max_requests) { return; }
|
||||
|
||||
|
||||
let request_index = request_handler_requests[index];
|
||||
let request_location = pointer_index_to_cache_index(request_index);
|
||||
let page_index = request_location.page_index;
|
||||
|
||||
// Fill out request information
|
||||
var request_information: RequestInformation;
|
||||
request_information.structure_id = structure_location_pages[page_index].structure_id;
|
||||
request_information.node_id = structure_location_pages[page_index].node_id;
|
||||
request_information.children_index = request_location.children_index;
|
||||
|
||||
// Fill out request meta information
|
||||
var request_meta: RequestMeta;
|
||||
request_meta.page_index = page_index;
|
||||
request_meta.children_index = request_location.children_index;
|
||||
|
||||
// Write them to request buffer
|
||||
request_buffer_informations[index] = request_information;
|
||||
request_buffer_meta[index] = request_meta;
|
||||
|
||||
// Write request count
|
||||
request_buffer_count = max_requests;
|
||||
}
|
||||
@@ -4,11 +4,15 @@ use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::voxel_cache::create_multi_buffers_bind_group;
|
||||
use crate::voxel_cache::create_multi_buffers_bind_group_layout;
|
||||
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>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pointer_pages: Buffer,
|
||||
location_pages: Buffer,
|
||||
@@ -50,60 +54,13 @@ where
|
||||
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(),
|
||||
},
|
||||
],
|
||||
});
|
||||
let bind_group_layout = Self::create_bind_group_layout(device);
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[&pointer_pages, &location_pages, &depth_pages],
|
||||
Some("CacheStructure::bind_group"),
|
||||
);
|
||||
|
||||
CacheStructure {
|
||||
pointer_pages,
|
||||
@@ -115,6 +72,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
{
|
||||
create_multi_buffers_bind_group_layout(device, 3, Some("CacheStructure::bind_group_layout"))
|
||||
}
|
||||
|
||||
pub fn bind_group_layout(&self) -> &BindGroupLayout
|
||||
{
|
||||
&self.bind_group_layout
|
||||
@@ -124,4 +86,9 @@ where
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn pointer_pages(&self) -> &Buffer
|
||||
{
|
||||
&self.pointer_pages
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::indirect_buffer::IndirectBuffer1D;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::voxel_cache::CacheInvalidable;
|
||||
use crate::voxel_cache::CacheRessources;
|
||||
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
|
||||
use crate::voxel_cache::eviction::CacheEvictor;
|
||||
use crate::voxel_cache::insertion::CacheInsertionData;
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::requests::CacheRequestHandler;
|
||||
use crate::voxel_cache::schema::CachePointer;
|
||||
|
||||
use super::pipelines::include_cache_wgsl;
|
||||
|
||||
/// Cache keeps pages from different structures within itself.
|
||||
/// Pages are pieces of structure pointing to each other. But, in order to start tracing inside the
|
||||
/// voxels, we must enter the cache from somewhere
|
||||
///
|
||||
/// The structure table is a structure that keeps information about where to find the root node
|
||||
/// inside the cache, or if it is not preset, emit requests.
|
||||
///
|
||||
|
||||
macro_rules! include_table_wgsl {
|
||||
($path:literal) => {{
|
||||
let mut full_shader = String::new();
|
||||
|
||||
full_shader.push_str(include_str!("./shaders/common.wgsl"));
|
||||
full_shader.push_str(include_str!($path));
|
||||
|
||||
wgpu::ShaderModuleDescriptor {
|
||||
label: Some($path),
|
||||
source: wgpu::ShaderSource::Wgsl(full_shader.into()),
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// A structure table with a fixed length
|
||||
pub struct FixedStructureTable
|
||||
{
|
||||
size: usize,
|
||||
/// Contains [`CachePointer`]s to locations in the cahce
|
||||
pointers: wgpu::Buffer,
|
||||
pointers_bind_group: wgpu::BindGroup,
|
||||
common_ressources: CacheRessources<1>,
|
||||
request_handler: CacheRequestHandler<1>,
|
||||
|
||||
// To dispatch write request passes per request count
|
||||
indirect_buffer: IndirectBuffer1D,
|
||||
write_requests_pass: wgpu::ComputePipeline,
|
||||
invalidation_pass: wgpu::ComputePipeline,
|
||||
insertion_pass: wgpu::ComputePipeline,
|
||||
|
||||
// Raytrace
|
||||
raytrace_bind_group_layout: wgpu::BindGroupLayout,
|
||||
raytrace_bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl FixedStructureTable
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, size: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
let pointer = CachePointer::new(Some(None));
|
||||
let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("FixedStructureTable::pointers"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![pointer; size]),
|
||||
});
|
||||
|
||||
let request_handler = CacheRequestHandler::<1>::new(device, size);
|
||||
|
||||
let (pointers_bind_group_layout, pointers_bind_group) = create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
&[&pointers],
|
||||
Some("FixedStructureTable::pointers"),
|
||||
);
|
||||
|
||||
// Write requests
|
||||
let write_requests_bindings = [
|
||||
Some(&CacheRequestHandler::<1>::create_bind_group_layout(device)),
|
||||
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
|
||||
];
|
||||
|
||||
let write_requests_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("FixedStructureTable::pipeline_layout"),
|
||||
bind_group_layouts: &write_requests_bindings,
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let write_requests_shader_module = device.create_shader_module(include_table_wgsl!(
|
||||
"./shaders/fixed_table/write_requests.wgsl"
|
||||
));
|
||||
|
||||
let write_requests_pass =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("FixedStructureTable::write_requests_pass"),
|
||||
layout: Some(&write_requests_pipeline_layout),
|
||||
module: &write_requests_shader_module,
|
||||
entry_point: Some("write_requests"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
// Invalidation
|
||||
let invalidation_bindings = [
|
||||
Some(&pointers_bind_group_layout),
|
||||
Some(&CacheEvictor::create_bind_group_layout(device)),
|
||||
];
|
||||
|
||||
let invalidation_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("FixedStructureTable::invalidation_pipeline_layout"),
|
||||
bind_group_layouts: &invalidation_bindings,
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let invalidation_shader_module = device.create_shader_module(include_table_wgsl!(
|
||||
"./shaders/fixed_table/invalidation.wgsl"
|
||||
));
|
||||
|
||||
let invalidation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("FixedStructureTable::invalidation_pass"),
|
||||
layout: Some(&invalidation_pipeline_layout),
|
||||
module: &invalidation_shader_module,
|
||||
entry_point: Some("invalidation"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let (raytrace_bind_group_layout, raytrace_bind_group) = create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
&[&pointers, request_handler.request_pages_buffer()],
|
||||
Some("FixedStructureTable::raytrace_bind_group"),
|
||||
);
|
||||
|
||||
// Insertion
|
||||
let insertion_bindings = [
|
||||
Some(&pointers_bind_group_layout),
|
||||
Some(&CacheInsertionData::<1>::create_bind_group_layout(
|
||||
device, layout,
|
||||
)),
|
||||
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
|
||||
];
|
||||
|
||||
let insertion_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("FixedStructureTable::insertion_pipeline_layout"),
|
||||
bind_group_layouts: &insertion_bindings,
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let insertion_shader_module = device
|
||||
.create_shader_module(include_table_wgsl!("./shaders/fixed_table/insertion.wgsl"));
|
||||
|
||||
let insertion_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("FixedStructureTable::insertion_pass"),
|
||||
layout: Some(&insertion_pipeline_layout),
|
||||
module: &insertion_shader_module,
|
||||
entry_point: Some("insertion"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
size,
|
||||
pointers,
|
||||
pointers_bind_group,
|
||||
common_ressources: CacheRessources::new(device, size),
|
||||
request_handler,
|
||||
indirect_buffer: IndirectBuffer1D::new(device),
|
||||
write_requests_pass,
|
||||
invalidation_pass,
|
||||
insertion_pass,
|
||||
|
||||
raytrace_bind_group,
|
||||
raytrace_bind_group_layout,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gather_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
)
|
||||
{
|
||||
self.request_handler
|
||||
.sort_requests(device, &self.common_ressources, encoder);
|
||||
|
||||
let workgroup_count_buffer = self.indirect_buffer.workgroup_count(
|
||||
device,
|
||||
encoder,
|
||||
self.request_handler.request_count_buffer(),
|
||||
256,
|
||||
);
|
||||
|
||||
// If there are no requests, there are no dispatched workgroups, so we must carry the 0
|
||||
// count over
|
||||
encoder.copy_buffer_to_buffer(
|
||||
self.request_handler.request_count_buffer(),
|
||||
0,
|
||||
&request_buffer.request_count,
|
||||
0,
|
||||
self.request_handler.request_count_buffer().size(),
|
||||
);
|
||||
|
||||
{
|
||||
let mut write_requests_pass =
|
||||
encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("FixedStructureTable::write_requests_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
write_requests_pass.set_bind_group(0, self.request_handler.bind_group(), &[]);
|
||||
write_requests_pass.set_bind_group(1, request_buffer.bind_group(), &[]);
|
||||
|
||||
write_requests_pass.set_pipeline(&self.write_requests_pass);
|
||||
write_requests_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
|
||||
}
|
||||
|
||||
self.request_handler.reset(encoder);
|
||||
}
|
||||
|
||||
/// After requests emited by this table, the user creates a [`CacheInsertionData`] struct that
|
||||
/// populates the cache. After the cache insertion operation, said [`CacheInsertionData`]
|
||||
/// contains location of written pages in the cache.
|
||||
/// This function takes this information and populates the structure so that it points into the
|
||||
/// cache
|
||||
pub fn insert<const N: usize>(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
|
||||
insertion: &CacheInsertionData<N>,
|
||||
request: &CacheRequestBuffer,
|
||||
) where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let workgroup_count_buffer = self.indirect_buffer.workgroup_count(
|
||||
device,
|
||||
encoder,
|
||||
insertion.page_count_buffer(),
|
||||
256,
|
||||
);
|
||||
|
||||
{
|
||||
let mut insertion_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("FixedStructureTable::insertion_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
insertion_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
|
||||
insertion_pass.set_bind_group(1, insertion.bind_group(), &[]);
|
||||
insertion_pass.set_bind_group(2, request.bind_group(), &[]);
|
||||
|
||||
insertion_pass.set_pipeline(&self.insertion_pass);
|
||||
insertion_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout
|
||||
{
|
||||
&self.raytrace_bind_group_layout
|
||||
}
|
||||
|
||||
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
&self.raytrace_bind_group
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheInvalidable for FixedStructureTable
|
||||
{
|
||||
fn invalidate(
|
||||
&mut self,
|
||||
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
invalid_timestamp: u32,
|
||||
)
|
||||
{
|
||||
let mut invalidate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("FixedStructureTable::invalidate_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
invalidate_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
|
||||
invalidate_pass.set_bind_group(1, cache_evictor.bind_group(), &[]);
|
||||
|
||||
invalidate_pass.set_pipeline(&self.invalidation_pass);
|
||||
invalidate_pass.set_immediates(0, bytemuck::bytes_of(&invalid_timestamp));
|
||||
invalidate_pass.dispatch_workgroups(self.size.div_ceil(256) as u32, 1, 1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user