diff --git a/shaders/bvh.slang b/shaders/bvh.slang index 831681a..a76ab0f 100644 --- a/shaders/bvh.slang +++ b/shaders/bvh.slang @@ -37,21 +37,38 @@ public struct BvhObject uint32_t _pad2; } +/// Traversal state for a single ray. +/// +/// The BVH is traversed with a restart trail instead of a stack: one bit per +/// tree level records what has already been processed, and every restart +/// re-walks from the root steered by that trail. [`BvhCursor::trail`] is the +/// only traversal state that survives between calls to [`Bvh::next`]. +/// +/// Trail invariant: bits `0 .. leaf_depth-1` encode the path to the current +/// leaf (`0` = near child, `1` = far child); all deeper bits are clear. +/// A 64 bit trail supports trees up to 64 levels deep. public struct BvhCursor { - Ray ray; - // One bit per level, bit 0 means left child unexplored, bit one, child explored - uint64_t bit_stack; + public Ray ray; - // Where to write the node when descending - uint32_t stack_head; - uint32_t stack_count; + /// Reciprocal of [`Ray::direction`]; computed once per ray and reused for + /// every node test. + public float3 inv_direction; - uint32_t current_object; - uint32_t current_node; + /// Restart trail, see the struct documentation. + public uint64_t trail; - uint32_t depth; - float t; + /// Objects of the leaf currently being drained. + public uint32_t leaf_first; + public uint32_t leaf_count; + public uint32_t leaf_next; + public uint32_t leaf_depth; + + /// True while [`Self::leaf_next`] still points into a valid leaf. + public bool have_leaf; + + /// Set once the whole tree has been processed. + public bool done; } public struct BvhParameters @@ -62,141 +79,288 @@ public struct BvhParameters RWStructuredBuffer> requests; } -static const uint32_t STACK_SIZE = 8; -static const uint32_t STACK_MASK = 7; -groupshared uint32_t stack[STACK_SIZE * 256]; -groupshared uint32_t stack_depth[STACK_SIZE * 256]; - public struct Bvh : IStructure { typedef BvhCursor Cursor; public BvhParameters parameters; - public uint32_t thread_index; + + /// Kept for compatibility with the existing call sites. The restart + /// traversal does not need per-thread storage, so this is unused. + public uint32_t thread_index; public BvhCursor begin(Ray world_ray) { BvhCursor c; c.ray = world_ray; - c.bit_stack = 0; - c.stack_head = 0; - c.stack_count = 0; - c.current_object = 0; - c.current_node = 0; - c.depth = 0; + c.inv_direction = safe_reciprocal(world_ray.direction); + c.trail = uint64_t(0); + c.leaf_first = 0; + c.leaf_count = 0; + c.leaf_next = 0; + c.leaf_depth = 0; + c.have_leaf = false; + + // Early out when the ray misses the whole scene. + let root = this.parameters.nodes[0]; + let root_t = intersect_aabb( + world_ray.origin, + c.inv_direction, + root.aabb.min, + root.aabb.max); + c.done = !(root_t.y >= max(root_t.x, 0.)); - this.push(0, c); return c; } public bool next(inout BvhCursor c, out Cell cell) { - uint32_t outer_bound = 0; - while (outer_bound < 300) + // The out parameter is only meaningful on a `true` return, but + // initialising it keeps the compiler's definite-assignment analysis + // happy on all early-outs. + cell.cache_pointer = 0; + cell.local_ray.origin = float3(0.); + cell.local_ray.direction = float3(0.); + cell.t = 0.; + + if (c.done) { - outer_bound++; + return false; + } - uint32_t inner_bound = 0; - if (parameters.nodes[c.current_node].is_internal() && inner_bound < 300) + [loop] + for (;;) + { + // 1. Drain the objects of the leaf we are currently in. + [loop] + while (c.leaf_next < c.leaf_count) { - inner_bound++; - let left_index = parameters.nodes[c.current_node].first_or_left; - float2 left = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left_index].aabb.min, parameters.nodes[left_index].aabb.max); - float2 right = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left_index + 1].aabb.min, parameters.nodes[left_index + 1].aabb.max); + let object_index = c.leaf_first + c.leaf_next; + c.leaf_next += 1; - bool left_hit = left.y >= left.x && left.y >= 0.; - bool right_hit = right.y >= right.x && right.y >= 0.; - - if (left_hit && right_hit) + Cell candidate; + if (this.object_hit(object_index, c.ray, candidate)) { - // Select closest - let go_left = left.y < right.y; - c.current_node = select(go_left, left_index, left_index + 1); - this.push(select(go_left, left_index + 1, left_index), c); - c.depth += 1; - } - else if (left_hit || right_hit) - { - c.current_node = select(left_hit, left_index, left_index + 1); - c.bit_stack |= 1 << c.depth; - c.depth += 1; - } - else - { - if (!this.pop(c.current_node, c)) - { - return false; - } + cell = candidate; + return true; } } - if (parameters.nodes[c.current_node].is_leaf()) + // 2. The leaf is exhausted: advance the trail past it. + if (c.have_leaf) { - // We are on a leaf - uint32_t offset = parameters.nodes[c.current_node].first_or_left; - uint32_t count = parameters.nodes[c.current_node].count; - while (c.current_object < count) + c.have_leaf = false; + if (!advance_trail(c, c.leaf_depth)) { - if (objectHit(offset + c.current_object, c.ray, cell)) - { - return true; - } - c.current_object += 1; + c.done = true; + return false; + } + } + + // 3. Restart: descend from the root, steered by the trail. + uint32_t node = 0; + uint32_t level = 0; + bool dead = false; + + [loop] + for (;;) + { + let n = this.parameters.nodes[node]; + if (n.is_leaf()) + { + c.leaf_first = n.first_or_left; + c.leaf_count = n.count; + c.leaf_next = 0; + c.leaf_depth = level; + c.have_leaf = true; + break; } - // Finisehd objects of this node - c.current_object = 0; - if (!this.pop(c.current_node, c)) + let left = n.first_or_left; + let right = left + 1; + + let t_left = intersect_aabb( + c.ray.origin, + c.inv_direction, + this.parameters.nodes[left].aabb.min, + this.parameters.nodes[left].aabb.max); + let t_right = intersect_aabb( + c.ray.origin, + c.inv_direction, + this.parameters.nodes[right].aabb.min, + this.parameters.nodes[right].aabb.max); + + let hit_left = t_left.y >= max(t_left.x, 0.); + let hit_right = t_right.y >= max(t_right.x, 0.); + + if (hit_left && hit_right) { + // Trail bit 0 means "near child first", 1 means "far". + // The near/far decision is deterministic for a fixed ray, + // so it stays consistent across restarts. + let left_is_near = t_left.x <= t_right.x; + let go_far = ((c.trail >> level) & uint64_t(1)) != uint64_t(0); + + if (left_is_near) + { + node = go_far ? right : left; + } + else + { + node = go_far ? left : right; + } + level += 1; + } + else if (hit_left) + { + // The far child has no work; mark this level processed so + // a later restart does not try to enter it. + c.trail |= (uint64_t(1) << level); + node = left; + level += 1; + } + else if (hit_right) + { + c.trail |= (uint64_t(1) << level); + node = right; + level += 1; + } + else + { + dead = true; + break; + } + + if (level >= 64) + { + // The trail cannot represent anything deeper. + c.done = true; + return false; + } + } + + if (dead) + { + // No child of this node is hit: move on to the next + // unprocessed part of the tree. + if (!advance_trail(c, level)) + { + c.done = true; return false; } } } - return true; } - bool objectHit(uint32_t object_index, Ray r, out Cell c) + /// Tests a leaf object and, if it can be traced, fills its cache cell. + bool object_hit(uint32_t object_index, Ray world_ray, out Cell cell) { - // Project direction and view in local space - let direction = mul(parameters.objects[object_index].world_to_local, float4(r.direction, 0)); - let origin = mul(parameters.objects[object_index].world_to_local, float4(r.origin, 1)); + cell.cache_pointer = 0; + cell.local_ray.origin = float3(0.); + cell.local_ray.direction = float3(0.); + cell.t = 0.; - float2 intersection = box_intersect(origin.xyz, direction.xyz, float3(0.), float3(1.)); - return intersection.y >= intersection.x && intersection.y >= 0.; - } + let object = this.parameters.objects[object_index]; - void push(uint32_t node, inout BvhCursor c) - { - stack[c.stack_head * 256 + this.thread_index] = node; - stack_depth[c.stack_head * 256 + this.thread_index] = c.depth; - c.stack_head += 1; - c.stack_count += 1; - } + // Transform the ray to the object's local space, where the voxel + // chunk is the unit cube. + let local_origin = mul(object.world_to_local, float4(world_ray.origin, 1.)).xyz; + let local_direction = mul(object.world_to_local, float4(world_ray.direction, 0.)).xyz; - bool pop(out uint32_t node, inout BvhCursor c) - { - if (c.stack_count == 0) + let t = intersect_aabb( + local_origin, + safe_reciprocal(local_direction), + float3(0.), + float3(1.)); + + if (t.y < max(t.x, 0.)) { return false; } - c.stack_head -= 1; - c.stack_count -= 1; - node = stack[c.stack_head * 256 + this.thread_index]; - c.depth = stack_depth[c.stack_head * 256 + this.thread_index]; - return true; + + let pointer = this.parameters.slots[object.table_slot]; + if (pointer.subdivided_valid()) + { + let entry_t = max(t.x, 0.); + cell.cache_pointer = pointer.pointer(); + cell.local_ray.origin = local_origin + local_direction * entry_t; + cell.local_ray.direction = local_direction; + cell.t = entry_t; + return true; + } + + if (pointer.subdivided()) + { + // The root of this object is requested but not available yet. + this.parameters.requests[object.table_slot].add(1); + } + + return false; } } -float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max) +/// Moves the trail to the next unprocessed part of the tree. +/// +/// Finds the nearest ancestor with a pending far child, marks it processed +/// and clears the path below it. Returns false when the whole tree has been +/// visited. +bool advance_trail(inout BvhCursor c, uint32_t depth) { - let min_ts = (box_min - origin) / ray_direction; - let max_ts = (box_max - origin) / ray_direction; + uint32_t level = depth; + uint64_t trail = (~c.trail) & ((1 << uint64_t(level)) - 1); + int32_t fbh = firstbithigh(trail); + if (trail == 0) + { + return false; + } - let far_ts = max(min_ts, max_ts); - let near_ts = min(min_ts, max_ts); + level = fbh; + c.trail |= (uint64_t(1) << level); + // Keep the path bits up to and including this level, drop the + // stale path below it. + c.trail &= (uint64_t(2) << level) - uint64_t(1); - 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)); + // [loop] + // while (level > 0) + // { + // level -= 1; + // if (((c.trail >> level) & uint64_t(1)) == uint64_t(0)) + // { + // c.trail |= (uint64_t(1) << level); + // // Keep the path bits up to and including this level, drop the + // // stale path below it. + // c.trail &= (uint64_t(2) << level) - uint64_t(1); + // return true; + // } + // } - return float2(near_t, far_t); + return true; +} + +/// Slab test against an axis aligned box, using a precomputed reciprocal. +/// +/// Returns `(t_near, t_far)`. A hit is `t_far >= max(t_near, 0)`. +float2 intersect_aabb(float3 origin, float3 inv_direction, float3 box_min, float3 box_max) +{ + let t0 = (box_min - origin) * inv_direction; + let t1 = (box_max - origin) * inv_direction; + + let t_near = min(t0, t1); + let t_far = max(t0, t1); + + return float2( + max(t_near.x, max(t_near.y, t_near.z)), + min(t_far.x, min(t_far.y, t_far.z))); +} + +/// Reciprocal that avoids `0 * inf = NaN` for rays parallel to a slab. +/// +/// A component that is (near) zero is replaced by a tiny positive value. The +/// slab test stays correct: the resulting huge `t` values either do not +/// constrain the interval or reject the box, depending on which side of the +/// slab the origin lies. +float3 safe_reciprocal(float3 direction) +{ + let tiny = abs(direction) < float3(1e-8); + return 1. / select(tiny, float3(1e-8), direction); } diff --git a/shaders/gi.slang b/shaders/gi.slang index d9d881a..658670c 100644 --- a/shaders/gi.slang +++ b/shaders/gi.slang @@ -75,6 +75,10 @@ void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_Gr let pos = gbuffer_position.Load(location.xy); let normal = gbuffer_normal.Load(location.xy); let albedo = gbuffer_albedo.Load(location.xy); + + // let floored_pos = floor(pos); + // let c = (floored_pos.x + floored_pos.y + floored_pos.z) % 2; + // target_texture.Store(location.xy, albedo * select(c == 0, 0.5, 1.)); target_texture.Store(location.xy, albedo); return; } diff --git a/shaders/out/voxel.spv b/shaders/out/voxel.spv index 26de802..e4f42e5 100644 Binary files a/shaders/out/voxel.spv and b/shaders/out/voxel.spv differ diff --git a/shaders/voxel.slang b/shaders/voxel.slang index dcedee8..fec6e05 100644 --- a/shaders/voxel.slang +++ b/shaders/voxel.slang @@ -147,63 +147,60 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_ Bvh bvh; bvh.parameters = table_parameters; bvh.thread_index = stack_index; - BvhCursor c = bvh.begin(r); - Cell cell; + // BvhCursor c = bvh.begin(r); + Cell cell; - // for (uint32_t i = 0; i < 100; i++) + // Setup for simple bvh traversal check + // if (bvh.next(c, cell)) // { - if (bvh.next(c, cell)) + // gbuffer_albedo.Store(location.xy, float4(0., 1., 0., 1.)); + // return; + // } + // gbuffer_albedo.Store(location.xy, float4(0.)); + + // ToroidalStructureTableTracer table_tracer; + // table_tracer.structure_table = table_parameters; + // table_tracer.extent = + // uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_height); + // table_tracer.base_slot = uint32_t3( + // constants.table_base_slot_x, + // constants.table_base_slot_y, + // constants.table_base_slot_z); + + PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f); + + Tracer>, PixelFootprintLod> tracer; + tracer.structure = bvh; + tracer.cache = cache_tracer; + tracer.lod = lod; + + Hit h; + // Closest hit at or past tMin. Re-trace past a hit with: + // t_min = h.t + 1e-4; + // hit = tracer.trace(stack_index, t_min, h, r); + bool hit = tracer.trace(stack_index, 0., h, r); + + // ToroidalStructureTableTracer.Cursor cursor = table_tracer.begin(r); + // Cell cell; + + if (hit) { - gbuffer_albedo.Store(location.xy, float4(0., 1., 0., 1.)); - return; + // Gather + let hit_pos = h.hit_location; + + let hit_normal = fetch_normal(h.node_index, h.child_index); + var hit_albedo = float4(0.); + hit_albedo = fetch_color(h.node_index, h.child_index).float_color; + // let hit_albedo = hit.color; + + gbuffer_position.Store(location.xy, float4(hit_pos, 1.)); + gbuffer_normal.Store(location.xy, float4(hit_normal, 1.)); + gbuffer_albedo.Store(location.xy, hit_albedo); + } + else + { + gbuffer_albedo.Store(location.xy, float4(0.)); } - //} - gbuffer_albedo.Store(location.xy, float4(0.)); - - /* - ToroidalStructureTableTracer table_tracer; - table_tracer.structure_table = table_parameters; - table_tracer.extent = - uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_height); - table_tracer.base_slot = uint32_t3( - constants.table_base_slot_x, - constants.table_base_slot_y, - constants.table_base_slot_z); - - - - PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f); - - Tracer>, PixelFootprintLod> tracer; - tracer.structure = table_tracer; - tracer.cache = cache_tracer; - tracer.lod = lod; - - Hit h; - bool hit = tracer.trace(stack_index, h, r); - - ToroidalStructureTableTracer.Cursor cursor = table_tracer.begin(r); - Cell cell; - - if (hit) - { - // Gather - let hit_pos = h.hit_location; - - let hit_normal = fetch_normal(h.node_index, h.child_index); - var hit_albedo = float4(0.); - hit_albedo = fetch_color(h.node_index, h.child_index).float_color; - // let hit_albedo = hit.color; - - gbuffer_position.Store(location.xy, float4(hit_pos, 1.)); - gbuffer_normal.Store(location.xy, float4(hit_normal, 1.)); - gbuffer_albedo.Store(location.xy, hit_albedo); - } - else - { - gbuffer_albedo.Store(location.xy, float4(0.)); - } - */ } float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max) diff --git a/shaders/voxel_cache.slang b/shaders/voxel_cache.slang index efc2769..cc269ab 100644 --- a/shaders/voxel_cache.slang +++ b/shaders/voxel_cache.slang @@ -142,6 +142,8 @@ public struct VoxelCacheTracer> : IVoxelCache public bool trace(uint32_t root, uint32_t thread_id, Ray r, L lod, float offset_t, out Hit v) { + v.t = 0.; + // Ray mirroring r.origin += float3(1.); r.origin = clamp(r.origin, float(1.), asfloat(0x3fffffff)); @@ -216,6 +218,7 @@ public struct VoxelCacheTracer> : IVoxelCache asfloat(asuint(pos) ^ 0x007fffff), pos) - float3(1.); + v.t = offset_t + t; return true; } diff --git a/shaders/voxel_tracing.slang b/shaders/voxel_tracing.slang index 58d3aa6..9387632 100644 --- a/shaders/voxel_tracing.slang +++ b/shaders/voxel_tracing.slang @@ -44,6 +44,10 @@ public struct Hit public uint32_t node_index; public uint32_t child_index; public float3 hit_location; + + /// Distance of the hit from the ray origin, in the units of the ray + /// direction. Used to order hits and to restart the traversal past a hit. + public float t; } public interface IVoxelCache @@ -60,23 +64,66 @@ public struct Tracer public C cache; public L lod; - public bool trace(uint32_t thread_id, out Hit h, Ray r) + /// Traces the closest hit at or past `t_min`. + /// + /// The structure may return cells in any order (the BVH restart trail is + /// not distance ordered). Instead of returning on the first cache hit, we + /// keep the closest hit found so far and skip cells that start beyond it: + /// every hit inside a cell is at least `cell.t` away, so a cell with + /// `entry >= best_t` cannot improve the result. + public bool trace(uint32_t thread_id, float t_min, out Hit h, Ray r) { - /* loop: next cell -> cache.trace -> early out */ - S.Cursor cursor = this.structure.begin(r); - Cell cell; - h.hit = false; h.hit_location = float3(0.f); h.child_index = 0; h.node_index = 0; + h.t = 0.f; + // Start just past the previous hit. + Ray adjusted = r; + adjusted.origin += r.direction * t_min; + + float best_t = asfloat(0x7f7fffff); // FLT_MAX + Hit best_hit = h; + bool found = false; + + S.Cursor cursor = this.structure.begin(adjusted); + Cell cell; + + [loop] while (this.structure.next(cursor, cell)) { - if (cache.trace(cell.cache_pointer, thread_id, cell.local_ray, lod, cell.t, h)) + // `cell.t` is relative to the advanced origin, `best_t` is not. + float cell_t = t_min + cell.t; + + // No hit inside this cell can be closer than the current best. + if (cell_t >= best_t) { - return true; + continue; } + + Hit candidate = h; + if (cache.trace( + cell.cache_pointer, + thread_id, + cell.local_ray, + lod, + cell_t, + candidate)) + { + if (candidate.t < best_t) + { + best_t = candidate.t; + best_hit = candidate; + found = true; + } + } + } + + if (found) + { + h = best_hit; + return true; } return false; diff --git a/src/bvh.rs b/src/bvh.rs index 0a171d3..60fb681 100644 --- a/src/bvh.rs +++ b/src/bvh.rs @@ -12,8 +12,13 @@ use crate::bvh::build::BvhPrimitive; use crate::bvh::build::build_bvh; use crate::bvh::gpu::GpuBvhNode; use crate::bvh::gpu::GpuObject; +use crate::gpu_profiler::ScopeEncoder; use crate::production::ProducerId; use crate::production::StructureAnchor; +use crate::voxel_cache::CacheInvalidable; +use crate::voxel_cache::eviction::CacheEvictor; +use crate::voxel_cache::insertion::CacheInsertionData; +use crate::voxel_cache::requests::CacheRequestBuffer; use crate::voxel_cache::tables::DynamicStructureTable; pub mod aabb; @@ -305,6 +310,69 @@ impl BvhStructureTable { &self.raytrace_bind_group } + + /// Gathers the root requests emitted by the inner structure table into + /// `request_buffer`. + pub fn gather_requests( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + request_buffer: &CacheRequestBuffer, + ) + { + self.structure_table + .gather_requests(device, encoder, request_buffer); + } + + /// Writes the cache page pointers produced by an external insertion into + /// the inner structure table. + pub fn insert( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ) where + [(); N * N * N]:, + { + self.structure_table.insert(device, encoder, insertion); + } + + pub fn get(&self, handle: &BvhHandle) -> Option<&BvhObject> + { + self.objects.get(handle) + } + + pub fn get_mut(&mut self, handle: &BvhHandle) -> Option<&mut BvhObject> + { + self.objects.get_mut(handle) + } +} + +impl CacheInvalidable for BvhStructureTable +where + [(); N * N * N]:, +{ + fn validate_insertion( + &mut self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ) + { + self.structure_table + .validate_insertion(device, encoder, insertion); + } + + fn invalidate( + &mut self, + encoder: &mut ScopeEncoder, + cache_evictor: &CacheEvictor, + invalid_timestamp: u32, + ) + { + self.structure_table + .invalidate(encoder, cache_evictor, invalid_timestamp); + } } fn create_bvh_buffer(device: &wgpu::Device, capacity: usize, label: &str) -> wgpu::Buffer diff --git a/src/main.rs b/src/main.rs index bb264a5..afe190b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -54,9 +54,11 @@ use winit::event_loop::OwnedDisplayHandle; use winit::window::Window; use winit::window::WindowId; +use crate::bvh::BvhHandle; use crate::bvh::BvhObject; use crate::bvh::BvhStructureTable; use crate::bvh::aabb::Aabb; +use crate::bvh::build::Bvh; use crate::bvh::debug::BvhDebugPipeline; use crate::camera::Camera; use crate::egui_renderer::EguiRenderer; @@ -148,8 +150,9 @@ struct State request_buffer: Arc, cache_insertion: Arc>, + structure_table: Arc>, //structure_table: Arc>, - structure_table: Arc>, + //structure_table: Arc>, structure_table_request_buffer: Arc, structure_table_cache_insertion: Arc>, usage_vec: Arc>>, @@ -170,8 +173,8 @@ struct State // Producers workers wakeup: Sender<()>, - bvh: BvhStructureTable, bvh_debug: BvhDebugPipeline, + bvh_objs: Vec<(BvhHandle, Vec3)>, } pub unsafe fn as_raw_bytes(slice: &[T]) -> &[u8] @@ -445,19 +448,74 @@ impl State let total_chunk_count = terrain_height * terrain_width * terrain_alt; let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128); + + let mut bvh = BvhStructureTable::new(&device, 128, 128); + let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE); + let mut bvh_objs = Vec::new(); + for _ in 0..1000 + { + let transform = Mat4::from_rotation_translation( + Quat::from_euler( + glam::EulerRot::XYZ, + random_range(-3.1..3.1), + random_range(-3.1..3.1), + random_range(-3.1..3.1), + ), + Vec3::new( + random_range(extent.min().x..extent.max().x), + random_range(extent.min().y..extent.max().y), + random_range(extent.min().z..extent.max().z), + ), + ); + + let handle = bvh.add( + &device, + &queue, + BvhObject { + anchor: StructureAnchor::zeroed(), + producer_id: ProducerId(0), + transform, + bounding_box: Aabb::CHUNK, + }, + ); + + bvh_objs.push(( + handle, + Vec3::new( + random_range(-1.0..1.0), + random_range(-1.0..1.0), + random_range(-1.0..1.0), + ) + .normalize(), + )); + } + + let now = Instant::now(); + bvh.rebuild(&device, &queue); + let time = Instant::now() - now; + + println!("Bvh build time : {}ms", time.as_millis()); + + let bvh_debug = BvhDebugPipeline::new( + &device, + surface_format.add_srgb_suffix(), + wgpu::TextureFormat::Depth24PlusStencil8, + ); + // let structure_table = FixedStructureTable::new( // &device, // total_chunk_count, // structure_table_request_buffer.max_requests, // 0, // ); - let structure_table = ToroidalStructureTable::new( - &device, - (terrain_width, terrain_alt, terrain_height), - Vec3::ZERO, - structure_table_request_buffer.max_requests, - 0, - ); + // let structure_table = ToroidalStructureTable::new( + // &device, + // (terrain_width, terrain_alt, terrain_height), + // Vec3::ZERO, + // structure_table_request_buffer.max_requests, + // 0, + // ); + let structure_table = bvh; let structure_table_insertion_data = CacheInsertionData::new(&device, 128, &layout); let chunk_instances = (0..terrain_alt) .cartesian_product(0..terrain_height) @@ -523,48 +581,6 @@ impl State // ) // }; - let mut bvh = BvhStructureTable::new(&device, 128, 128); - let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE); - for _ in 0..100 - { - let transform = Mat4::from_rotation_translation( - Quat::from_euler( - glam::EulerRot::XYZ, - random_range(-3.1..3.1), - random_range(-3.1..3.1), - random_range(-3.1..3.1), - ), - Vec3::new( - random_range(extent.min().x..extent.max().x), - random_range(extent.min().y..extent.max().y), - random_range(extent.min().z..extent.max().z), - ), - ); - - bvh.add( - &device, - &queue, - BvhObject { - anchor: StructureAnchor::zeroed(), - producer_id: ProducerId(0), - transform, - bounding_box: Aabb::CHUNK, - }, - ); - } - - let now = Instant::now(); - bvh.rebuild(&device, &queue); - let time = Instant::now() - now; - - println!("Bvh build time : {}ms", time.as_millis()); - - let bvh_debug = BvhDebugPipeline::new( - &device, - surface_format.add_srgb_suffix(), - wgpu::TextureFormat::Depth24PlusStencil8, - ); - let shader_module = unsafe { device.create_shader_module_passthrough({ wgpu::ShaderModuleDescriptorPassthrough { @@ -706,8 +722,7 @@ impl State bind_group_layouts: &[ Some(voxel_cache.raytrace_bind_group_layout()), - //Some(structure_table.raytrace_bind_group_layout()), - Some(bvh.raytrace_bind_group_layout()), + Some(structure_table.raytrace_bind_group_layout()), Some(&ray_march_bind_group_layout), ], immediate_size: size_of::() as u32, @@ -867,8 +882,8 @@ impl State insert_profile: Arc::new(Mutex::new(Profile::default())), cursor_grabed: true, wakeup: wakeup_tx, - bvh, bvh_debug, + bvh_objs, }; // Configure surface for the first time @@ -1070,6 +1085,28 @@ impl State { self.camera.update(); + let mut locked_table = self.structure_table.lock(); + for (hndl, dir) in self.bvh_objs.iter_mut() + { + let obj = locked_table.get_mut(hndl); + if let Some(obj) = obj + { + let (scale, mut rot, mut trans) = obj.transform.to_scale_rotation_translation(); + let speed = 0.01; + rot = rot.mul_quat(Quat::from_axis_angle(*dir, speed)); + trans += *dir * speed; + *dir += Vec3::new( + random_range(-speed..speed), + random_range(-speed..speed), + random_range(-speed..speed), + ); + obj.transform = Mat4::from_scale_rotation_translation(scale, rot, trans); + } + } + locked_table.mark_dirty(); + locked_table.rebuild_if_dirty(&self.device, &self.queue); + drop(locked_table); + // Create texture view. // NOTE: We must handle Timeout because the surface may be unavailable // (e.g., when the window is occluded on macOS). @@ -1170,22 +1207,6 @@ 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); - { - let retired = self.structure_table.lock().move_position( - &self.queue, - &mut prof_command_encoder, - self.camera.position, - ); - - // Cancellation is only an optimisation: stale insertions are - // rejected by the GPU because they no longer match the slot. - let mut request_queue = self.request_queue.lock(); - for anchor in retired - { - request_queue.invalidate_anchor(anchor); - } - } - { let mut encoder = prof_command_encoder.begin_frame(Some("Main frame")); @@ -1196,14 +1217,13 @@ impl State renderpass.set_pipeline(&self.pipeline); renderpass.set_bind_group(0, self.voxel_cache.lock().raytrace_bind_group(), &[]); - renderpass.set_bind_group(1, self.bvh.raytrace_bind_group(), &[]); - // renderpass.set_bind_group( - // 1, - // self.structure_table.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 table_base_slot = self.structure_table.lock().base_slot(); + let table_base_slot = [0; 3]; let imm = [Immediates { view_proj: self.camera.view_proj().inverse(), cam_pos: self.camera.position, @@ -1257,18 +1277,20 @@ impl State self.target_blitter .copy(&self.device, &mut encoder, target_view, &texture_view); - self.bvh_debug.render( - &self.device, - &self.queue, - &mut encoder, - &texture_view, - &self.depth_buffer.1, - self.camera.view_proj(), - self.bvh.bvh_nodes(), - self.bvh.bvh_objects(), - self.bvh.node_count(), - 2, - ); + let structure_table = self.structure_table.lock(); + // self.bvh_debug.render( + // &self.device, + // &self.queue, + // &mut encoder, + // &texture_view, + // &self.depth_buffer.1, + // self.camera.view_proj(), + // structure_table.bvh_nodes(), + // structure_table.bvh_objects(), + // structure_table.node_count(), + // 2, + // ); + drop(structure_table); // ~~ EGUI Render pass ~~ {