refactor: cleaner request path + raytracing code

This commit is contained in:
2026-11-23 11:32:16 +01:00
parent dd0e102348
commit dd5fdc13b8
20 changed files with 1427 additions and 618 deletions
+17 -8
View File
@@ -84,9 +84,11 @@ public struct Bvh : IStructure
typedef BvhCursor Cursor;
public BvhParameters parameters;
/// 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;
/// Reject nodes/objects whose entry distance is beyond this value.
/// Set to FLT_MAX for unbounded primary rays. Distances are in the
/// object's local units, which equal world units for the rigid
/// rotation/translation transforms used here.
public float max_t;
public BvhCursor begin(Ray world_ray)
{
@@ -100,14 +102,15 @@ public struct Bvh : IStructure
c.leaf_depth = 0;
c.have_leaf = false;
// Early out when the ray misses the whole scene.
// Early out when the ray misses the whole scene or the root is beyond
// the requested range.
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.));
c.done = !(root_t.y >= max(root_t.x, 0.) && root_t.x <= this.max_t);
return c;
}
@@ -121,6 +124,8 @@ public struct Bvh : IStructure
cell.local_ray.origin = float3(0.);
cell.local_ray.direction = float3(0.);
cell.t = 0.;
cell.cube_to_world = mat3_identity();
cell.world_origin = float3(0.);
if (c.done)
{
@@ -189,8 +194,8 @@ public struct Bvh : IStructure
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.);
let hit_left = t_left.y >= max(t_left.x, 0.) && t_left.x <= this.max_t;
let hit_right = t_right.y >= max(t_right.x, 0.) && t_right.x <= this.max_t;
if (hit_left && hit_right)
{
@@ -258,6 +263,8 @@ public struct Bvh : IStructure
cell.local_ray.origin = float3(0.);
cell.local_ray.direction = float3(0.);
cell.t = 0.;
cell.cube_to_world = mat3_identity();
cell.world_origin = float3(0.);
let object = this.parameters.objects[object_index];
@@ -272,7 +279,7 @@ public struct Bvh : IStructure
float3(0.),
float3(1.));
if (t.y < max(t.x, 0.))
if (t.y < max(t.x, 0.) || t.x > this.max_t)
{
return false;
}
@@ -285,6 +292,8 @@ public struct Bvh : IStructure
cell.local_ray.origin = local_origin + local_direction * entry_t;
cell.local_ray.direction = local_direction;
cell.t = entry_t;
cell.cube_to_world = float3x3(object.local_to_world);
cell.world_origin = mul(object.local_to_world, float4(0., 0., 0., 1.)).xyz;
return true;
}
+120 -29
View File
@@ -1,3 +1,13 @@
import voxel_cache;
import bvh;
import voxel_tracing;
import lod_policies;
// Simple screen-space AO: reconstruct the world-space surface from the primary
// G-buffer and trace a few short, incoherent hemisphere rays per pixel through
// the same tracer the primary pass uses. This is the secondary-ray smoke test:
// short `t_max`, any-hit, usage feedback only, no detail requests.
struct PushConstants
{
float4x4 view_proj;
@@ -10,6 +20,7 @@ struct PushConstants
uint32_t chunk_height;
uint32_t chunk_alt;
// Canonical table slot of the visible block's minimum corner.
uint32_t table_base_slot_x;
uint32_t table_base_slot_y;
uint32_t table_base_slot_z;
@@ -18,19 +29,8 @@ struct PushConstants
[[vk::push_constant]]
uniform PushConstants constants;
[[vk::binding(0, 0)]]
RWStructuredBuffer<uint32_t> structure_pool;
[[vk::binding(1, 0)]]
RWStructuredBuffer<uint32_t> attributes_pool[2];
[[vk::binding(2, 0)]]
RWStructuredBuffer<uint32_t> request_buffer;
[[vk::binding(3, 0)]]
RWStructuredBuffer<uint32_t> usage_buffer;
[[vk::binding(0, 1)]]
RWStructuredBuffer<uint32_t> structure_table_pointer;
[[vk::binding(1, 1)]]
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
ParameterBlock<VoxelCacheParameters<2>> cache_parameters;
ParameterBlock<BvhParameters> table_parameters;
[[vk::binding(0, 2)]]
[[format("rgba32f")]]
@@ -48,38 +48,129 @@ RWTexture2D<float4> gbuffer_albedo;
[[format("rgba32f")]]
RWTexture2D<float4> gbuffer_normal;
float3 get_ray_direction(uint32_t2 pixel_loc)
static const uint32_t AO_SAMPLE_COUNT = 4;
static const float AO_RADIUS = 0.25;
static const float AO_EPSILON = 0.01;
float hash12(float2 p)
{
let ndc_loc_x = (float)pixel_loc.x / (float)constants.width * 2. - 1.;
let ndc_loc_y = 1. - (float)pixel_loc.y / (float)constants.height * 2.;
var world_loc = mul(constants.view_proj, float4(ndc_loc_x, ndc_loc_y, 1., 1.));
world_loc /= world_loc.w;
return normalize(world_loc.xyz - constants.cam_pos);
var p3 = frac(float3(p.xyx) * 0.1031);
p3 += dot(p3, p3.yzx + 33.33);
return frac((p3.x + p3.y) * p3.z);
}
float3 fetch_normal(uint32_t index, uint32_t child_index)
{
let a = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3]);
let b = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]);
let c = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]);
return float3(a, b, c);
}
/// Cosine-weighted hemisphere sample around `n`, rotated per pixel so the
/// fixed sample count does not band.
float3 hemisphere_sample(float3 n, uint32_t sample_index, float rotation)
{
let up = select(abs(n.z) < 0.999, float3(1., 0., 0.), float3(0., 0., 1.));
let tangent = normalize(cross(up, n));
let bitangent = cross(n, tangent);
let r = sqrt((float(sample_index) + 0.5) / float(AO_SAMPLE_COUNT));
let phi = 6.28318530718 * frac(rotation + float(sample_index) * 0.61803398875);
let disk = r * float2(cos(phi), sin(phi));
return normalize(tangent * disk.x + bitangent * disk.y + n * sqrt(max(0., 1. - r * r)));
}
[shader("compute")]
[numthreads(16, 16, 1)]
void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID)
void gi(uint32_t3 location: SV_DispatchThreadID)
{
if (location.x >= constants.width || location.y >= constants.height)
{
return;
}
if (gbuffer_albedo.Load(location.xy).w == 0.)
let albedo = gbuffer_albedo.Load(location.xy);
// Shunt albedo
target_texture.Store(location.xy, albedo);
return;
// AO Example
if (albedo.w == 0.)
{
target_texture.Store(location.xy, float4(0.));
return;
}
let pos = gbuffer_position.Load(location.xy);
let normal = gbuffer_normal.Load(location.xy);
let albedo = gbuffer_albedo.Load(location.xy);
let position = gbuffer_position.Load(location.xy).xyz;
let normal_raw = gbuffer_normal.Load(location.xy).xyz;
let normal_length = length(normal_raw);
if (normal_length < 1e-6)
{
target_texture.Store(location.xy, albedo);
return;
}
let normal = -normal_raw / normal_length;
// 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;
VoxelCacheTracer<2, ColorHit<2>> cache_tracer;
cache_tracer.parameters = cache_parameters;
cache_tracer.frame_timestamp = constants.frame_timestamp;
cache_tracer.voxel_hit = ColorHit<2>();
Bvh bvh;
bvh.parameters = table_parameters;
bvh.max_t = AO_RADIUS;
// Coarse LOD: AO does not need primary-ray detail.
// PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f, 0.05f);
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;
TraceSettings settings;
settings.t_min = AO_EPSILON;
settings.t_max = 100.;
settings.max_cells = 64;
settings.max_steps = 64;
settings.any_hit = false;
settings.report_usage = true;
settings.report_requests = false;
LocalTraceStack stack;
let rotation = hash12(float2(location.xy));
uint32_t occluded = 0;
// [loop]
// for (uint32_t sample_index = 0; sample_index < AO_SAMPLE_COUNT; sample_index++)
// {
Ray r;
r.origin = position + normal * (AO_EPSILON + 0.1);
r.direction = reflect(normalize(position - constants.cam_pos), normal);
// r.direction = hemisphere_sample(normal, sample_index, rotation);
Hit h;
if (tracer.trace(h, r, settings, stack))
{
occluded += 1;
let hit_normal = fetch_normal(h.node_index, h.child_index);
let shade = max(dot(hit_normal, float3(0., 1., 0.)), 0.1);
target_texture.Store(location.xy, float4(shade));
}
else
{
target_texture.Store(location.xy, float4(0.));
}
//}
// let ao = 1. - float(occluded) / float(AO_SAMPLE_COUNT);
// Soften the effect: a fully black crevice reads as a hole in this demo.
// let lit = lerp(1., ao, 0.7);
// target_texture.Store(location.xy, float4(albedo.rgb * lit, albedo.a));
}
Binary file not shown.
Binary file not shown.
+2
View File
@@ -97,6 +97,8 @@ public struct ToroidalStructureTableTracer : IStructure
cell.local_ray.origin = position - float3(c.current_voxel);
cell.local_ray.direction = c.r.direction;
cell.t = t_adv;
cell.cube_to_world = mat3_identity();
cell.world_origin = float3(c.current_voxel);
hit = true;
}
else if (this.structure_table.structure_table_pointer[chunk_index].subdivided())
+25 -20
View File
@@ -46,15 +46,8 @@ ParameterBlock<VoxelCacheParameters<2>> cache_parameters;
// ParameterBlock<ToroidalStructureTable> table_parameters;
ParameterBlock<BvhParameters> table_parameters;
public struct ColorHit<let N : uint32_t> : IVoxelHit<N>
{
public __init() {};
public bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index)
{
return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0;
}
}
// ColorHit<2> (the demo hit predicate) lives in voxel_cache.slang so the
// primary and secondary front-ends share one definition.
// [[vk::binding(0, 0)]]
// RWStructuredBuffer<StructurePoolElement> structure_pool;
@@ -122,22 +115,32 @@ void gi_march(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location:
[shader("compute")]
[numthreads(16, 16, 1)]
void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID)
void ray_march_compute(uint32_t3 location: SV_DispatchThreadID)
{
if (location.x >= constants.width || location.y >= constants.height)
{
return;
}
let stack_index = local_location.x + local_location.y * 16;
VoxelCacheTracer<2, ColorHit<2>> cache_tracer;
cache_tracer.parameters = cache_parameters;
cache_tracer.report_usage = true;
cache_tracer.report_requests = true;
cache_tracer.frame_timestamp = constants.frame_timestamp;
cache_tracer.voxel_hit = ColorHit<2>();
// Per-ray trace state. Local storage keeps the tracer independent of the
// workgroup shape; swap this for a groupshared-backed ITraceStack if the
// primary pass needs groupshared memory back.
LocalTraceStack stack;
TraceSettings settings;
settings.t_min = 0.;
settings.t_max = asfloat(0x7f7fffff); // FLT_MAX
settings.max_cells = 0xFFFFFFFF;
settings.max_steps = 500;
settings.any_hit = false;
settings.report_usage = true;
settings.report_requests = true;
let ray_direction = get_ray_direction(location.xy);
Ray r;
@@ -146,7 +149,7 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_
Bvh bvh;
bvh.parameters = table_parameters;
bvh.thread_index = stack_index;
bvh.max_t = asfloat(0x7f7fffff); // FLT_MAX: unbounded primary rays
// BvhCursor c = bvh.begin(r);
Cell cell;
@@ -176,19 +179,21 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_
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);
// settings.t_min = h.t + 1e-4;
// hit = tracer.trace(h, r, settings, stack);
bool hit = tracer.trace(h, r, settings, stack);
// ToroidalStructureTableTracer.Cursor cursor = table_tracer.begin(r);
// Cell cell;
if (hit)
{
// Gather
// `Hit` is already in world space; only the local attribute normal
// still needs rotating into world space.
let hit_pos = h.hit_location;
let hit_normal = fetch_normal(h.node_index, h.child_index);
let local_normal = mul(h.normal_to_world, fetch_normal(h.node_index, h.child_index));
let hit_normal = local_normal / max(length(local_normal), 1e-6);
var hit_albedo = float4(0.);
hit_albedo = fetch_color(h.node_index, h.child_index).float_color;
// let hit_albedo = hit.color;
+30 -12
View File
@@ -129,18 +129,31 @@ public interface IVoxelHit<let N : uint32_t>
public bool shouldHit(VoxelCacheParameters<N> parameters, uint32_t node_index, uint32_t child_index);
}
static const uint32_t WG_COUNT = 256;
groupshared uint32_t stack[5 * WG_COUNT];
/// Default hit test for the demo layout: alpha != 0 means solid.
public struct ColorHit<let N : uint32_t> : IVoxelHit<N>
{
public __init() {};
public bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index)
{
return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0;
}
}
public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
{
public bool report_usage;
public bool report_requests;
public uint32_t frame_timestamp;
public H voxel_hit;
public VoxelCacheParameters<N> parameters;
public bool trace<L : ILodPolicy>(uint32_t root, uint32_t thread_id, Ray r, L lod, float offset_t, out Hit v)
public bool trace<L : ILodPolicy, St : ITraceStack>(
uint32_t root,
Ray r,
L lod,
TraceSettings settings,
float offset_t,
inout St stack,
out Hit v)
{
v.t = 0.;
@@ -168,15 +181,20 @@ public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
float3 pos = r.origin;
uint32_t scale_exp = 23 - 2;
uint32_t current_node_index = root;
if (this.report_usage)
if (settings.report_usage)
{
this.parameters.usage_buffer[current_node_index] = this.frame_timestamp;
}
stack[thread_id + WG_COUNT * (10 - scale_exp / 2)] = current_node_index;
stack.set(10 - scale_exp / 2, current_node_index);
[loop]
for (uint32_t iter = 0; iter < 500; iter++)
for (uint32_t iter = 0; iter < settings.max_steps; iter++)
{
if (offset_t + t >= settings.t_max)
{
break;
}
uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror;
StructurePointer current_node = this.parameters.structure_pool[current_node_index].pointers[child_index];
@@ -184,18 +202,18 @@ public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
{
scale_exp -= 2;
current_node_index = current_node.pointer();
stack[thread_id + WG_COUNT * (10 - scale_exp / 2)] = current_node_index;
stack.set(10 - scale_exp / 2, current_node_index);
child_index = get_children_index(pos, scale_exp) ^ child_mirror;
current_node = this.parameters.structure_pool[current_node_index].pointers[child_index];
// Write usage
if (this.report_usage)
if (settings.report_usage)
{
this.parameters.usage_buffer[current_node_index] = frame_timestamp;
}
}
// Request subdiv
if (this.report_requests && !lod.shouldStop(t + offset_t, node_size(scale_exp)) && current_node.subdivided() && !current_node.pointer_valid())
if (settings.report_requests && !lod.shouldStop(t + offset_t, node_size(scale_exp)) && current_node.subdivided() && !current_node.pointer_valid())
{
this.parameters.request_buffer[current_node_index].requests[child_index].add(1);
}
@@ -253,7 +271,7 @@ public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
}
scale_exp = 23 - common_depth;
current_node_index = stack[thread_id + WG_COUNT * (10 - scale_exp / 2)];
current_node_index = stack.get(10 - scale_exp / 2);
}
v.hit = false;
+139 -13
View File
@@ -16,6 +16,13 @@ public struct Cell
/// How much distance from the camera
public float t;
/// Rotation/scale from the cell's unit-cube space to world space.
/// Identity for axis-aligned chunks.
public float3x3 cube_to_world;
/// World-space position of the cell's unit-cube origin.
public float3 world_origin;
}
public interface IStructure
@@ -43,18 +50,99 @@ public struct Hit
// Cache location
public uint32_t node_index;
public uint32_t child_index;
public float3 hit_location;
public float3 hit_location; // world space
/// Rotation applied to the hit's local attribute normals.
public float3x3 normal_to_world;
/// 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;
}
/// Identity matrix helper (scalar-to-matrix casts splat instead of making an
/// identity in Slang).
public float3x3 mat3_identity()
{
return float3x3(
1., 0., 0.,
0., 1., 0.,
0., 0., 1.);
}
/// Per-ray parameters for a trace call.
///
/// Primary and secondary rays use the same tracer; only these values differ.
/// `t_min`/`t_max` are world-space distances along the (normalised) ray
/// direction. A hit at exactly `t_max` is excluded, so `t_max` is an open
/// interval end.
public struct TraceSettings
{
/// Start of the search interval. Re-traces set this just past the
/// previous hit.
public float t_min;
/// End of the search interval. Use FLT_MAX for unbounded traces.
public float t_max;
/// Maximum number of structure cells to visit.
public uint32_t max_cells;
/// Maximum number of DDA iterations inside one cache cell.
public uint32_t max_steps;
/// Stop at the first acceptable hit instead of accumulating the nearest
/// one. Meant for shadow/visibility rays.
public bool any_hit;
/// Refresh the LRU timestamp of every node the ray touches.
public bool report_usage;
/// Emit cache detail requests for nodes the ray reaches at the LOD.
public bool report_requests;
}
/// Per-ray stack access owned by the caller.
///
/// The trace core never stores the stack itself, so a front-end chooses where
/// it lives. [`LocalTraceStack`] keeps it in per-thread storage. A primary pass
/// that wants groupshared memory implements this interface over a module-scope
/// `groupshared` array plus a thread slot instead; no trace-core code changes.
///
/// The depth index (`10 - scale_exp / 2`) assumes branching 4 and
/// `chunk_power = 5`, so implementations store five entries.
public interface ITraceStack
{
public uint32_t get(uint32_t depth);
[mutating] public void set(uint32_t depth, uint32_t node);
}
public struct LocalTraceStack : ITraceStack
{
public uint32_t entries[5];
public uint32_t get(uint32_t depth)
{
return this.entries[depth];
}
[mutating]
public void set(uint32_t depth, uint32_t node)
{
this.entries[depth] = node;
}
}
public interface IVoxelCache
{
// The voxel cache tracer needs to store a small stack.
// Keeping it in registers is wastefull thus using groupshared memory is the best option
public bool trace<L : ILodPolicy>(uint32_t root, uint32_t thread_id, Ray r, L lod, float offset_t, out Hit v);
public bool trace<L : ILodPolicy, St : ITraceStack>(
uint32_t root,
Ray r,
L lod,
TraceSettings settings,
float offset_t,
inout St stack,
out Hit v);
}
public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy>
@@ -64,40 +152,56 @@ public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy>
public C cache;
public L lod;
/// Traces the closest hit at or past `t_min`.
/// Traces the closest hit (or the first acceptable hit when
/// `settings.any_hit`) at or past `settings.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)
/// `entry >= best_t` cannot improve the result. Because the cells are not
/// ordered, such cells are skipped and never used to break the loop.
///
/// `stack` is caller-owned trace state. Keeping it out of the cache tracer
/// lets primary and secondary front-ends choose their own storage.
public bool trace<St : ITraceStack>(
out Hit h,
Ray r,
TraceSettings settings,
inout St stack)
{
h.hit = false;
h.hit_location = float3(0.f);
h.child_index = 0;
h.node_index = 0;
h.normal_to_world = mat3_identity();
h.t = 0.f;
// Start just past the previous hit.
Ray adjusted = r;
adjusted.origin += r.direction * t_min;
adjusted.origin += r.direction * settings.t_min;
float best_t = asfloat(0x7f7fffff); // FLT_MAX
float best_t = settings.t_max;
Hit best_hit = h;
bool found = false;
S.Cursor cursor = this.structure.begin(adjusted);
Cell cell;
uint32_t visited = 0;
[loop]
while (this.structure.next(cursor, cell))
while (visited++ < settings.max_cells && this.structure.next(cursor, cell))
{
// `cell.t` is relative to the advanced origin, `best_t` is not.
float cell_t = t_min + cell.t;
float cell_t = settings.t_min + cell.t;
// No hit inside this cell can be closer than the current best.
if (cell_t >= best_t)
// Cells are not ordered, so skip instead of breaking.
if (cell_t >= settings.t_max)
{
continue;
}
if (!settings.any_hit && cell_t >= best_t)
{
continue;
}
@@ -105,12 +209,34 @@ public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy>
Hit candidate = h;
if (cache.trace(
cell.cache_pointer,
thread_id,
cell.local_ray,
lod,
settings,
cell_t,
stack,
candidate))
{
// The cache enforces `t_max`; the guard keeps a misbehaving
// implementation from accepting an out-of-range hit.
if (candidate.t >= settings.t_max)
{
continue;
}
// The cache reports hits in its unit-cube space. Bring the
// position and the local attribute normal into world space so
// front-ends can use the hit directly, including as the origin
// of secondary rays.
candidate.hit_location =
cell.world_origin + mul(cell.cube_to_world, candidate.hit_location);
candidate.normal_to_world = cell.cube_to_world;
if (settings.any_hit)
{
h = candidate;
return true;
}
if (candidate.t < best_t)
{
best_t = candidate.t;