diff --git a/shaders/Makefile b/shaders/Makefile index 9720ca0..435f780 100644 --- a/shaders/Makefile +++ b/shaders/Makefile @@ -4,4 +4,4 @@ clean: rm -f out/*.spv %.spv: %.slang - slangc $< -O3 -g0 -fp-mode fast -fvk-use-scalar-layout -emit-spirv-directly -fvk-use-entrypoint-name -target spirv -o out/$@ + slangc $< -O3 -g0 -fp-mode fast -emit-spirv-directly -fvk-use-entrypoint-name -target spirv -o out/$@ diff --git a/shaders/out/gi.spv b/shaders/out/gi.spv index c015590..4b93ff2 100644 Binary files a/shaders/out/gi.spv and b/shaders/out/gi.spv differ diff --git a/shaders/out/radix_reduce.spv b/shaders/out/radix_reduce.spv index 346f607..d9d8040 100644 Binary files a/shaders/out/radix_reduce.spv and b/shaders/out/radix_reduce.spv differ diff --git a/shaders/out/radix_sort.spv b/shaders/out/radix_sort.spv index 6f8e7b4..b662222 100644 Binary files a/shaders/out/radix_sort.spv and b/shaders/out/radix_sort.spv differ diff --git a/shaders/out/voxel.spv b/shaders/out/voxel.spv index 9fa7cd2..0bc44fe 100644 Binary files a/shaders/out/voxel.spv and b/shaders/out/voxel.spv differ diff --git a/shaders/toroidal_structure_table.slang b/shaders/toroidal_structure_table.slang new file mode 100644 index 0000000..c88bb99 --- /dev/null +++ b/shaders/toroidal_structure_table.slang @@ -0,0 +1,126 @@ +module toroidal_structure_table; + +import voxel_cache; +import voxel_tracing; + +/// Parameters for the fixed structure table +public struct ToroidalStructureTable +{ + RWStructuredBuffer structure_table_pointer; + RWStructuredBuffer> structure_table_request_buffer; +} + +public struct ToroidalStructureTableChunksCursor +{ + // Offset of the block of chuks + int32_t3 offset; + int32_t3 current_voxel; + float3 t_off; + float3 t; + + Ray r; +} + +int32_t imod(int32_t x, int32_t n) +{ + int32_t r = x % n; + return r < 0 ? r + n : r; +} + +/// Uses a fixed structure table as a dense array of chunks +public struct ToroidalStructureTableTracer : IStructure +{ + typedef ToroidalStructureTableChunksCursor Cursor; + + public ToroidalStructureTable structure_table; + public uint32_t3 extent; + + public ToroidalStructureTableChunksCursor begin(Ray worldRay, Span s) + { + ToroidalStructureTableChunksCursor cursor; + // Now march inside chunk bounds + let start_position = worldRay.origin; + + // FVT clamp to block + cursor.current_voxel = int32_t3(floor(start_position)); + cursor.offset = cursor.current_voxel - int32_t3(this.extent) / 2; + + cursor.t_off = abs(worldRay.invDirection); + + // Take t of next boundary + cursor.t = select( + worldRay.direction > 0., + cursor.current_voxel + int32_t3(1) - start_position, + start_position - cursor.current_voxel) * + cursor.t_off; + + // Add camera offset + cursor.r = worldRay; + return cursor; + } + + public bool next(inout Cursor c, out Cell cell) + { + while (all(c.current_voxel >= c.offset) && all(c.current_voxel < c.offset + int32_t3(extent))) + { + // Current hit + let off = c.t - c.t_off; + let t_adv = max(max(off.x, max(off.y, off.z)), 0.); + let local_voxel = + int32_t3( + imod(c.current_voxel.x, int32_t(this.extent.x)), + imod(c.current_voxel.y, int32_t(this.extent.y)), + imod(c.current_voxel.z, int32_t(this.extent.z))); + let chunk_index = local_voxel.x + local_voxel.z * this.extent.x + local_voxel.y * this.extent.x * this.extent.z; + let position = c.r.origin + c.r.direction * t_adv; + + var hit = false; + if (this.structure_table.structure_table_pointer[chunk_index].subdivided_valid()) + { + cell.cache_pointer = this.structure_table.structure_table_pointer[chunk_index].pointer(); + cell.local_ray.origin = position - float3(c.current_voxel); + cell.local_ray.direction = c.r.direction; + cell.local_ray.invDirection = c.r.invDirection; + cell.t = t_adv; + hit = true; + } + else if (this.structure_table.structure_table_pointer[chunk_index].subdivided()) + { + this.structure_table.structure_table_request_buffer[chunk_index].add(1); + hit = false; + } + + // Advance + let min_mask = min_mask(c.t); + c.t += select(min_mask, c.t_off, float3(0.)); + c.current_voxel += select(min_mask, int32_t3(sign(c.r.direction)), int32_t3(0)); + + if (hit) + { + return true; + } + } + + return false; + } +} + +bool3 min_mask(float3 val) +{ + let min_val = min(val.x, min(val.y, val.z)); + return val == min_val; +} + +float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max) +{ + let min_ts = (box_min - origin) / ray_direction; + let max_ts = (box_max - origin) / ray_direction; + + let far_ts = max(min_ts, max_ts); + let near_ts = min(min_ts, max_ts); + + let far_t = min(far_ts.x, min(far_ts.y, far_ts.z)); + let near_t = max(near_ts.x, max(near_ts.y, near_ts.z)); + return float2(near_t, far_t); +} + diff --git a/shaders/voxel.slang b/shaders/voxel.slang index c5f16e9..78a080d 100644 --- a/shaders/voxel.slang +++ b/shaders/voxel.slang @@ -1,6 +1,7 @@ // import ray_cast; import voxel_cache; import fixed_structure_table; +import toroidal_structure_table; import voxel_tracing; import lod_policies; @@ -38,7 +39,7 @@ public struct VertexOutput uniform PushConstants constants; ParameterBlock> cache_parameters; -ParameterBlock table_parameters; +ParameterBlock table_parameters; public struct ColorHit : IVoxelHit { @@ -134,7 +135,7 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_ cache_tracer.frame_timestamp = constants.frame_timestamp; cache_tracer.voxel_hit = ColorHit<2>(); - FixedStructureTableChunks table_tracer; + ToroidalStructureTableTracer table_tracer; table_tracer.structure_table = table_parameters; table_tracer.extent = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width); @@ -147,7 +148,7 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_ PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f); - Tracer>, PixelFootprintLod> tracer; + Tracer>, PixelFootprintLod> tracer; tracer.structure = table_tracer; tracer.cache = cache_tracer; tracer.lod = lod; @@ -156,8 +157,8 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_ Span s; bool hit = tracer.trace(stacks[stack_index], h, r, s); - FixedStructureTableChunks.Cursor cursor = table_tracer.begin(r, s); - Cell cell; + ToroidalStructureTableTracer.Cursor cursor = table_tracer.begin(r, s); + Cell cell; if (hit) { diff --git a/src/main.rs b/src/main.rs index fabbf57..724963c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -59,6 +59,7 @@ use crate::producers::ChunkedProducer; use crate::producers::SdfGenerator; use crate::producers::TerrainGenerator; use crate::sparse_tree::NTreeNodeLocator; +use crate::terrain::ToroidalStructureTable; use crate::voxel_cache::VoxelCache; use crate::voxel_cache::VoxelCacheInsertion; use crate::voxel_cache::insertion::CacheInsertionData; @@ -75,6 +76,7 @@ mod gpu; pub mod gpu_profiler; mod producers; mod sparse_tree; +mod terrain; mod voxel_cache; // @@ -114,7 +116,8 @@ struct State request_buffer: Arc, cache_insertion: Arc>, - structure_table: Arc>, + //structure_table: Arc>, + structure_table: Arc>, structure_table_request_buffer: Arc, structure_table_cache_insertion: Arc>, terrain_generator: Arc>, @@ -368,9 +371,9 @@ impl State let terrain_generator = SdfGenerator::<4>::new(5); // let terrain_generator = TerrainGenerator::<4>::new( // 5, - // "./pointe_percee/height.tif", + // "/home/albin/Documents/vxls_maps/pointe_percee/height.tif", // 0.2, - // "./pointe_percee/ortho.jpg", + // "/home/albin/Documents/vxls_maps/pointe_percee/ortho.jpg", // ); // let terrain_generator = TerrainGenerator::<4>::new( // 5, @@ -394,7 +397,12 @@ impl State let mut chunk_pos_map = HashMap::new(); let total_chunk_count = terrain_height * terrain_width * terrain_alt; - let structure_table = FixedStructureTable::new(&device, total_chunk_count, &layout); + //let structure_table = FixedStructureTable::new(&device, total_chunk_count); + let structure_table = ToroidalStructureTable::new( + &device, + (terrain_width, terrain_alt, terrain_height), + Vec3::ZERO, + ); let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128); let structure_table_insertion_data = CacheInsertionData::new(&device, 128, &layout); let chunk_instances = (0..terrain_alt) @@ -1005,6 +1013,12 @@ impl State let mut command_encoder = self.device.create_command_encoder(&Default::default()); let mut prof_command_encoder = ProfilingEncoder::new(&self.device, &mut command_encoder); + { + self.structure_table + .lock() + .move_position(&mut prof_command_encoder, self.camera.position); + } + { let mut encoder = prof_command_encoder.begin_frame(Some("Main frame")); @@ -1265,6 +1279,7 @@ impl State let request_buffer_done = Arc::new(AtomicBool::new(false)); let request_buffer_done_1 = request_buffer_done.clone(); let finshed_1 = finished.clone(); + let cloned_table_1 = self.structure_table.clone(); self.request_buffer.host_download_requests( &self.device, &self.queue, @@ -1294,6 +1309,7 @@ impl State cloned_generator.as_ref(), request, cloned_map.as_ref(), + &cloned_table_1, ) }) .collect::>() @@ -1346,6 +1362,7 @@ impl State 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(); + let cloned_table_2 = self.structure_table.clone(); self.structure_table_request_buffer.host_download_requests( &self.device, &self.queue, @@ -1377,6 +1394,7 @@ impl State cloned_generator.as_ref(), request, cloned_map.as_ref(), + &cloned_table_2, ) }) .collect::>() @@ -1736,6 +1754,7 @@ fn fullfill_request( generator: &dyn ChunkedProducer, request: &RequestInformation, map: &HashMap, + table: &Arc>, ) -> ( [u32; N * N * N], [[f32; 3]; N * N * N], @@ -1746,7 +1765,24 @@ where [(); N * N * N]:, { // Unpack structure id - let (chunk_x, chunk_y, chunk_z) = *map.get(&request.structure_id).unwrap(); + //let (chunk_x, chunk_y, chunk_z) = *map.get(&request.structure_id).unwrap(); + let (chunk_x, chunk_y, chunk_z) = table.lock().get_request_position(request.structure_id); + + // let (chunk_x, chunk_y, chunk_z) = ( + // (u32::MAX as isize + chunk_x) as usize, + // (u32::MAX as isize + chunk_y) as usize, + // (u32::MAX as isize + chunk_z) as usize, + // ); + let (chunk_x, chunk_y, chunk_z) = ( + (chunk_x + 5000) as usize, + (chunk_y).abs() as usize, + (chunk_z + 5000) as usize, + ); + // let (chunk_x, chunk_y, chunk_z) = ( + // (chunk_x.abs()) as usize, + // (chunk_y.abs()) as usize, + // (chunk_z.abs()) as usize, + // ); let location; let node; diff --git a/src/producers.rs b/src/producers.rs index c7329a8..249633d 100644 --- a/src/producers.rs +++ b/src/producers.rs @@ -3,6 +3,8 @@ use std::path::Path; use glam::Vec3; use itertools::Itertools; +use noise::Cylinders; +use noise::Fbm; use noise::NoiseFn; use noise::Simplex; use rand::random; @@ -478,8 +480,8 @@ where pub struct SdfGenerator { chunk_power: usize, - //perlin: Fbm, - perlin: Simplex, + perlin: Fbm, + //perlin: Cylinders, } impl SdfGenerator @@ -488,8 +490,8 @@ impl SdfGenerator { Self { chunk_power, - //perlin: Fbm::new(67), - perlin: Simplex::new(67), + perlin: Fbm::new(67), + //perlin: Cylinders::new(), } } } @@ -507,19 +509,36 @@ where chunk_pos: (usize, usize, usize), ) -> ProducedChunk { + fn hash(mut p: [f32; 3]) -> f32 + { + p[0] = (p[0] * 127.1 + p[1] * 311.7 + p[2] * 74.7).sin() * 43758.5453123; + p[0].fract() + } + + let col_r = hash([ + chunk_pos.0 as f32 * 93487., + 912873. + 348. * chunk_pos.1 as f32, + 0., + ]); + let col_g = hash([chunk_pos.1 as f32 * 12093., 92837. * chunk_pos.0 as f32, 0.]); + let col_b = hash([0., 981882. * chunk_pos.0 as f32, 9092. * chunk_pos.1 as f32]); + // let sdf = |x: f32, y: f32, z: f32| { // Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512. // }; - // let sdf = |x: f32, y: f32, z: f32| { - // let scale = 128.; + // let sdf = |mut x: f32, mut y: f32, mut z: f32| { + // // x = -5000. * 1024.; + // // z = -5000. * 1024.; + // y -= 1024.; + // let scale = 2048.; // let tx = x / scale; // let ty = y / scale; // let tz = z / scale; // - // let val = (self.perlin.get([tx as f64, ty as f64, tz as f64]) - 0.1) * 0.23; + // let val = (self.perlin.get([tx as f64, tz as f64, ty as f64]) + 0.5) * 0.23; // let dist = val * scale as f64; - // return dist as f32; + // return (dist as f32).max(ty); // }; // let sdf = |x: f32, y: f32, z: f32| { @@ -532,12 +551,6 @@ where // }; let sdf = |x: f32, y: f32, z: f32| { - fn hash(mut p: [f32; 3]) -> f32 - { - p[0] = (p[0] * 127.1 + p[1] * 311.7 + p[2] * 74.7).sin() * 43758.5453123; - p[0].fract() - } - let scale = 10. * 1024.; let height = 5000.; let tx = x / scale; @@ -663,7 +676,12 @@ where // alpha, // )); children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.)); - children_color.push(Color(color + random::() * 0.02, color, color, alpha)); + children_color.push(Color( + color + random::() * 0.02 + col_r, + color + col_g, + color + col_b, + alpha, + )); children_normals.push((normal.x, normal.y, normal.z)); //children_color.push(Color(normal.x, normal.y, normal.z, alpha)); } diff --git a/src/terrain.rs b/src/terrain.rs new file mode 100644 index 0000000..9a6986e --- /dev/null +++ b/src/terrain.rs @@ -0,0 +1,279 @@ +use std::iter::FusedIterator; + +use bytemuck::Pod; +use bytemuck::Zeroable; +use glam::Vec3; +use wgpu::CommandEncoder; +use wgpu::include_wgsl; + +use crate::gpu::create_multi_buffers_bind_group_layout; +use crate::voxel_cache; +use crate::voxel_cache::tables::FixedStructureTable; + +/// A torroidal structure table for "infinite" world purposes. +/// Allows rendering a X*Y*Z block of chunks arround a position, like for example arround a player. +/// +/// When the player moves, crossing a chunk boundary, chunks behind disapear, chunks in front +/// appear. The torroidal nature of the table (modulo on the coordinates) allows reusing the +/// disapearing chunks for the new chunks appearing in front. +pub struct ToroidalStructureTable +{ + /// Size of the torroidal structure : how many chunks in each direction can be rendered at once + extent: (usize, usize, usize), + + fixed_structure_table: FixedStructureTable, + position: Vec3, + current_offset: (isize, isize, isize), + + invalidation_pass: wgpu::ComputePipeline, +} + +#[derive(Debug, Clone, Copy, Zeroable, Pod)] +#[repr(C)] +struct ToroidalInvalidationImmediates +{ + extent: [u32; 3], + _pad1: u32, + previous_offset: [i32; 3], + _pad2: u32, + offset: [i32; 3], + _pad3: u32, +} + +impl ToroidalStructureTable +{ + pub fn new(device: &wgpu::Device, extent: (usize, usize, usize), initial_position: Vec3) + -> Self + { + let size = extent.0 * extent.1 * extent.2; + assert!(size <= (u32::MAX as usize)); + + let current_offset = Self::offset_from_center(extent, initial_position); + + let bind_group_layout = create_multi_buffers_bind_group_layout( + device, + 1, + Some("ToroidalStructureTable::bind_group_layout"), + ); + + let invalidation_pipeline_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("ToroidalStructureTable::invalidation_pipeline_layout"), + bind_group_layouts: &[Some(&bind_group_layout)], + immediate_size: size_of::() as u32, + }); + + let shader_module = + device.create_shader_module(include_wgsl!("./terrain/shaders/toroidal_structure.wgsl")); + + let invalidation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("ToroidalStructureTable::invalidation_pass"), + layout: Some(&invalidation_pipeline_layout), + module: &shader_module, + entry_point: Some("invalidate_new"), + compilation_options: Default::default(), + cache: None, + }); + + ToroidalStructureTable { + extent, + fixed_structure_table: FixedStructureTable::new(device, size), + position: initial_position, + current_offset, + invalidation_pass, + } + } + + /// Moves the center position to `new_position`. + /// This requires updating to structure table to remove disapearing chunks + pub fn move_position(&mut self, encoder: &mut CommandEncoder, new_position: Vec3) + { + let previous_offset = self.current_offset; + self.current_offset = Self::offset_from_center(self.extent, new_position); + self.position = new_position; + + let invalidation_parameters = ToroidalInvalidationImmediates { + extent: [ + self.extent.0 as u32, + self.extent.1 as u32, + self.extent.2 as u32, + ], + _pad1: 0, + previous_offset: [ + previous_offset.0 as i32, + previous_offset.1 as i32, + previous_offset.2 as i32, + ], + _pad2: 0, + offset: [ + self.current_offset.0 as i32, + self.current_offset.1 as i32, + self.current_offset.2 as i32, + ], + _pad3: 0, + }; + + let mut invalidation_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("ToroidalStructureTable::invalidation_pass"), + timestamp_writes: None, + }); + + invalidation_pass.set_pipeline(&self.invalidation_pass); + invalidation_pass.set_bind_group(0, self.fixed_structure_table.pointers_bind_group(), &[]); + invalidation_pass.set_immediates(0, bytemuck::bytes_of(&invalidation_parameters)); + invalidation_pass.dispatch_workgroups( + self.extent.0.div_ceil(4) as u32, + self.extent.1.div_ceil(4) as u32, + self.extent.2.div_ceil(4) as u32, + ); + } + + /// Given the structure id, returns the position of the requesting chunk + pub fn get_request_position(&self, structure_id: u32) -> (isize, isize, isize) + { + // Where the block offset lies in the tore + let offset_tore_x = self.current_offset.0.rem_euclid(self.extent.0 as isize); + let offset_tore_y = self.current_offset.1.rem_euclid(self.extent.1 as isize); + let offset_tore_z = self.current_offset.2.rem_euclid(self.extent.2 as isize); + + // Local coordinate within the fixed table + let x = structure_id as isize % self.extent.0 as isize; + let z = (structure_id as isize / self.extent.0 as isize) % self.extent.2 as isize; + let y = structure_id as isize / (self.extent.0 * self.extent.2) as isize; + + // Coordinates in the tore, centered on the offset + let x = (x - offset_tore_x).rem_euclid(self.extent.0 as isize); + let y = (y - offset_tore_y).rem_euclid(self.extent.1 as isize); + let z = (z - offset_tore_z).rem_euclid(self.extent.2 as isize); + + ( + x + self.current_offset.0, + y + self.current_offset.1, + z + self.current_offset.2, + ) + } + + fn offset_from_center(extent: (usize, usize, usize), position: Vec3) -> (isize, isize, isize) + { + ( + position.x as isize - (extent.0 as isize / 2), + position.y as isize - (extent.1 as isize / 2), + position.z as isize - (extent.2 as isize / 2), + ) + } + + // Function calls through to fixed_structure_table + + pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup + { + self.fixed_structure_table.raytrace_bind_group() + } + + pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout + { + self.fixed_structure_table.raytrace_bind_group_layout() + } + + pub fn insert( + &self, + device: &wgpu::Device, + encoder: &mut crate::gpu_profiler::ScopeEncoder, + insertion: &voxel_cache::insertion::CacheInsertionData, + request: &voxel_cache::requests::CacheRequestBuffer, + ) where + [(); N * N * N]:, + { + self.fixed_structure_table + .insert(device, encoder, insertion, request); + } + + pub fn gather_requests( + &self, + device: &wgpu::Device, + encoder: &mut crate::gpu_profiler::ScopeEncoder, + request_buffer: &voxel_cache::requests::CacheRequestBuffer, + ) + { + self.fixed_structure_table + .gather_requests(device, encoder, request_buffer); + } +} + +impl voxel_cache::CacheInvalidable for ToroidalStructureTable +{ + fn invalidate( + &mut self, + encoder: &mut crate::gpu_profiler::ScopeEncoder, + cache_evictor: &voxel_cache::eviction::CacheEvictor, + invalid_timestamp: u32, + ) + { + self.fixed_structure_table + .invalidate(encoder, cache_evictor, invalid_timestamp); + } +} + +pub struct CenterChunkIter +{ + center_chunk: (isize, isize, isize), + extent: (usize, usize, usize), + block_corner: (isize, isize, isize), + current: usize, + length: usize, +} + +impl CenterChunkIter +{ + pub fn new(center_chunk: (isize, isize, isize), extent: (usize, usize, usize)) -> Self + { + let half_extent = (extent.0 / 2, extent.1 / 2, extent.2 / 2); + let block_corner = ( + center_chunk.0 - half_extent.0 as isize, + center_chunk.1 - half_extent.1 as isize, + center_chunk.2 - half_extent.2 as isize, + ); + + Self { + center_chunk, + extent, + block_corner, + current: 0, + length: extent.0 * extent.1 * extent.2, + } + } +} + +impl FusedIterator for CenterChunkIter {} +impl ExactSizeIterator for CenterChunkIter {} + +impl Iterator for CenterChunkIter +{ + type Item = (isize, isize, isize); + + fn next(&mut self) -> Option + { + if self.current >= self.length + { + None + } + else + { + let x = self.current % self.extent.0; + let y = (self.current / self.extent.0) % self.extent.1; + let z = self.current / (self.extent.0 * self.extent.1); + self.current += 1; + + Some(( + x as isize + self.block_corner.0, + y as isize + self.block_corner.1, + z as isize + self.block_corner.2, + )) + } + } + + fn size_hint(&self) -> (usize, Option) + { + let remaining = self.length - self.current; + (remaining, Some(remaining)) + } +} diff --git a/src/terrain/shaders/toroidal_structure.wgsl b/src/terrain/shaders/toroidal_structure.wgsl new file mode 100644 index 0000000..6c243b0 --- /dev/null +++ b/src/terrain/shaders/toroidal_structure.wgsl @@ -0,0 +1,52 @@ +@group(0) @binding(0) var table_pointers: array; + +struct InvalidationImmediates +{ + extent: vec3, + pevious_offset: vec3, + offset: vec3, +} + +var immediates: InvalidationImmediates; + + +@compute +@workgroup_size(4, 4, 4) +fn invalidate_new(@builtin(global_invocation_id) gid: vec3) +{ + if(any(gid >= immediates.extent)) + { + return; + } + + // Check whether this invocation lies within a pointer to be renewed + let igid = vec3(gid); + let previous_pos = get_position(igid, immediates.pevious_offset); + let pos = get_position(igid, immediates.offset); + + if(any(previous_pos != pos)) + { + // Invalidate pointer + let index = gid.x + gid.z * immediates.extent.x + gid.y * immediates.extent.x * immediates.extent.z; + table_pointers[index] = u32(1) << 31; + } +} + +fn get_position(block_position: vec3, offset: vec3) -> vec3 +{ + // Tore origin within block + let origin = imodv(offset, vec3(immediates.extent)); + + // Position in tore coordinate + let tore_position = imodv((block_position - origin), vec3(immediates.extent)); + + return tore_position + offset; +} + +fn imod(x: i32, n: i32) -> i32 { + return ((x % n) + n) % n; +} + +fn imodv(x: vec3, n: vec3) -> vec3 { + return vec3(imod(x.x, n.x), imod(x.y, n.y), imod(x.z, n.z)); +} diff --git a/src/voxel_cache/insertion.rs b/src/voxel_cache/insertion.rs index a1af67e..18a1720 100644 --- a/src/voxel_cache/insertion.rs +++ b/src/voxel_cache/insertion.rs @@ -33,6 +33,7 @@ where bind_group_layout: wgpu::BindGroupLayout, bind_group: wgpu::BindGroup, + bind_group_no_attributes: wgpu::BindGroup, } impl CacheInsertionData @@ -87,32 +88,41 @@ where .map(|buffer| buffer.as_entire_buffer_binding()) .collect::>(); - let bind_group_layout = Self::create_bind_group_layout(device, layout); + let mut entries = vec![ + 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(), + }, + ]; + + let bind_group_layout_no_attributes = Self::create_bind_group_layout(device, None); + let bind_group_no_attributes = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("CacheInsertionData::bind_group_no_attributes"), + layout: &bind_group_layout_no_attributes, + entries: &entries, + }); + entries.push(wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::BufferArray(&bind_group_bindings), + }); + + let bind_group_layout = Self::create_bind_group_layout(device, Some(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), - }, - ], + entries: &entries, }); Self { @@ -125,66 +135,86 @@ where bind_group_layout, bind_group, + bind_group_no_attributes, } } - pub fn create_bind_group_layout(device: &wgpu::Device, layout: &CacheLayout) - -> BindGroupLayout + /// Creates a bindgroup layout to bind the insertion data : + /// - Page count buffer (u32) + /// - Insertion information + /// - Location pages + /// - Destination indicies + /// - (Optional) attributes + /// + /// An applcation that does not need the the attributes can pass `None` to layout. + /// It can then use [`CacheInsertionData::<_>::bind_group_no_attributes(...)`] to get the + /// corresponding bind group, otherwise use [`CacheInsertionData::<_>::bind_group(...)`] + /// + pub fn create_bind_group_layout( + device: &wgpu::Device, + layout: Option<&CacheLayout>, + ) -> BindGroupLayout { + let mut entries = vec![ + 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, + }, + ]; + + if let Some(layout) = layout + { + entries.push(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()), + }); + } + 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()), - }, - ], + entries: &entries, }) } @@ -193,6 +223,11 @@ where &self.bind_group } + pub fn bind_group_no_attributes(&self) -> &wgpu::BindGroup + { + &self.bind_group_no_attributes + } + pub fn page_count(&self) -> usize { self.max_page_count diff --git a/src/voxel_cache/pipelines.rs b/src/voxel_cache/pipelines.rs index 28c9b1e..ff52927 100644 --- a/src/voxel_cache/pipelines.rs +++ b/src/voxel_cache/pipelines.rs @@ -203,7 +203,8 @@ where Some(&CacheStructure::::create_bind_group_layout(device)), // New incoming attributes Some(&CacheInsertionData::::create_bind_group_layout( - device, layout, + device, + Some(layout), )), // To get recyclable pages, and mark pages dirty Some(&CacheEvictor::create_bind_group_layout(device)), @@ -399,7 +400,8 @@ where Some(&CacheRequestBuffer::create_bind_group_layout(device)), // To find where the request's response went Some(&CacheInsertionData::::create_bind_group_layout( - device, layout, + device, + Some(layout), )), ]; diff --git a/src/voxel_cache/tables.rs b/src/voxel_cache/tables.rs index d1ab43c..7e58fb0 100644 --- a/src/voxel_cache/tables.rs +++ b/src/voxel_cache/tables.rs @@ -60,7 +60,7 @@ pub struct FixedStructureTable impl FixedStructureTable { - pub fn new(device: &wgpu::Device, size: usize, layout: &CacheLayout) -> Self + pub fn new(device: &wgpu::Device, size: usize) -> Self { let pointer = CachePointer::new(Some(None)); let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { @@ -148,7 +148,7 @@ impl FixedStructureTable let insertion_bindings = [ Some(&pointers_bind_group_layout), Some(&CacheInsertionData::<1>::create_bind_group_layout( - device, layout, + device, None, )), Some(&CacheRequestBuffer::create_bind_group_layout(device)), ]; @@ -260,7 +260,7 @@ impl FixedStructureTable }); insertion_pass.set_bind_group(0, &self.pointers_bind_group, &[]); - insertion_pass.set_bind_group(1, insertion.bind_group(), &[]); + insertion_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]); insertion_pass.set_bind_group(2, request.bind_group(), &[]); insertion_pass.set_pipeline(&self.insertion_pass); @@ -277,6 +277,16 @@ impl FixedStructureTable { &self.raytrace_bind_group } + + pub fn pointers_buffer(&self) -> &wgpu::Buffer + { + &self.pointers + } + + pub fn pointers_bind_group(&self) -> &wgpu::BindGroup + { + &self.pointers_bind_group + } } impl CacheInvalidable for FixedStructureTable