feat: Good bvh traversal
This commit is contained in:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user