feat: Good bvh traversal

This commit is contained in:
2026-11-15 12:00:08 +01:00
parent 4581538c66
commit dd32c772e5
8 changed files with 552 additions and 247 deletions
+262 -98
View File
@@ -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<Atomic<uint32_t>> 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);
}
+4
View File
@@ -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;
}
Binary file not shown.
+50 -53
View File
@@ -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<Bvh, VoxelCacheTracer<2, ColorHit<2>>, 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<ToroidalStructureTableTracer, VoxelCacheTracer<2, ColorHit<2>>, 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)
+3
View File
@@ -142,6 +142,8 @@ public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
public bool trace<L : ILodPolicy>(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<let N : int, H : IVoxelHit<N>> : IVoxelCache
asfloat(asuint(pos) ^ 0x007fffff),
pos) -
float3(1.);
v.t = offset_t + t;
return true;
}
+54 -7
View File
@@ -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<S : IStructure, C : IVoxelCache, L : ILodPolicy>
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;