From e7fbeb7887463de7bcd2076c3e2f0c802128dab4 Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Thu, 12 Nov 2026 22:47:17 +0100 Subject: [PATCH] feat: Starting bvh raytracing --- shaders/bvh.slang | 305 ++++++++++++++++++++++++++++++++++++++++++ shaders/out/voxel.spv | Bin 15852 -> 8540 bytes shaders/voxel.slang | 98 ++++++++------ src/bvh/build.rs | 35 ++++- src/bvh/debug.rs | 177 ++++++++++++------------ src/bvh/debug.wgsl | 12 +- src/main.rs | 21 ++- 7 files changed, 501 insertions(+), 147 deletions(-) create mode 100644 shaders/bvh.slang diff --git a/shaders/bvh.slang b/shaders/bvh.slang new file mode 100644 index 0000000..53f93a7 --- /dev/null +++ b/shaders/bvh.slang @@ -0,0 +1,305 @@ +import voxel_tracing; +import voxel_cache; + +public struct Aabb +{ + public float min_x; + public float min_y; + public float min_z; + + uint32_t _pad0; + + public float max_x; + public float max_y; + public float max_z; + + uint32_t _pad1; + + public float3 min() + { + return float3(this.min_x, this.min_y, this.min_z); + } + + public float3 max() + { + return float3(this.max_x, this.max_y, this.max_z); + } +} + +public struct BvhNode +{ + public Aabb aabb; + public uint32_t count; + public uint32_t first_or_left; + + public bool is_leaf() + { + return this.count != 0; + } + + public bool is_internal() + { + return this.count == 0; + } +} + +public struct BvhObject +{ + public float4x4 local_to_world; + public float4x4 world_to_local; + public uint32_t table_slot; + uint32_t _pad0; + uint32_t _pad1; + uint32_t _pad2; +} + +public struct BvhCursor +{ + Ray ray; + // One bit per level, bit 0 means left child unexplored, bit one, child explored + uint64_t bit_stack; + + // Where to write the node when descending + uint32_t stack_head; + uint32_t stack_count; + + uint32_t current_object; + uint32_t current_node; + + uint32_t depth; +} + +public struct BvhParameters +{ + StructuredBuffer nodes; + StructuredBuffer objects; + RWStructuredBuffer slots; + RWStructuredBuffer> requests; +} + +static const uint32_t STACK_SIZE = 4; +static const uint32_t STACK_MASK = 0b11; +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; + + 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; + + this.push(0, c); + return c; + } + + public bool next(inout BvhCursor c, out Cell cell) + { + uint32_t node_index = 0; + uint64_t out_b = 0; + while (true && out_b < 80) + { + out_b += 1; + uint32_t b = 0; + while (parameters.nodes[node_index].is_internal() && b < 80) + { + b++; + uint32_t left = parameters.nodes[node_index].first_or_left; + float2 inter1 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left].aabb.min(), parameters.nodes[left].aabb.max()); + float2 inter2 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left + 1].aabb.min(), parameters.nodes[left + 1].aabb.max()); + + bool hit1 = inter1.x <= inter1.y && inter1.y >= 0; + bool hit2 = inter2.x <= inter2.y && inter2.y >= 0; + + if (hit1 && hit2) + { + let near = select(inter1.x < inter2.x, left, left + 1); + let far = select(inter1.x < inter2.x, left + 1, left); + + // Push far + this.push(far, c); + + // Go to near + c.depth += 1; + node_index = near; + } + else if (hit1 || hit2) + { + // Go to hit + c.depth += 1; + node_index = select(hit1, left, left + 1); + } + else + { + // none hit, go to next + if (!this.pop(node_index, c)) + { + return false; + } + } + } + + if (parameters.nodes[node_index].is_leaf()) + { + let first = parameters.nodes[node_index].first_or_left; + for (uint32_t i = first; i < first + parameters.nodes[node_index].count; i++) + { + if (this.objectHit(i, c.ray, cell)) + { + return true; + } + } + } + } + return false; + } + + bool objectHit(uint32_t object_index, Ray r, out Cell c) + { + // 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)); + + float2 inter = box_intersect(origin.xyz, direction.xyz, float3(0.), float3(1.)); + + return inter.x <= inter.y && inter.y >= 0.; + } + + void push(uint32_t node, inout BvhCursor c) + { + stack[(c.stack_head & STACK_MASK) * 256 + this.thread_index] = node; + stack_depth[(c.stack_head & STACK_MASK) * 256 + this.thread_index] = c.depth; + c.stack_head += 1; + c.stack_count = max(c.stack_count + 1, STACK_SIZE); + } + + bool pop(out uint32_t node, inout BvhCursor c) + { + if (c.stack_count > 0) + { + c.stack_head -= 1; + c.stack_count -= 1; + node = stack[(c.stack_head & STACK_MASK) * 256 + this.thread_index]; + c.depth = stack_depth[(c.stack_head & STACK_MASK) * 256 + this.thread_index]; + + // This node is done, mark it ok, remove bits of deeper levels, they're done + c.bit_stack = (c.bit_stack | 1 << c.depth) & ((2 << c.depth) - 1); + return true; + } + return false; + + // Stack is underflowed, we need to restart + uint64_t above = (~c.bit_stack) & ((1 << c.depth) - 1); + if (above == 0) + { + // Then all upper levels are one, meaning they've been popped once + // Meaning we were in a far->far->far... ->far path. + // so we have explored everything + return false; + } + + // Select the depth at which we want to go back down, which is the first 0 + // bit + uint32_t return_depth = firstbithigh(above); + + // Since we visited that level, we mark it visited + c.bit_stack = (c.bit_stack | 1 << return_depth) & ((2 << return_depth) - 1); + + // Reset stack + c.stack_head = 0; + c.stack_count = 0; + + // Travel back down to level using the bit stack + node = 0; + for (uint32_t l = 0; l < return_depth; l++) + { + bool go_far = ((c.bit_stack >> l) & 1) == 1; + + uint32_t left = parameters.nodes[node].first_or_left; + float2 inter1 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left].aabb.min(), parameters.nodes[left].aabb.max()); + float2 inter2 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left + 1].aabb.min(), parameters.nodes[left + 1].aabb.max()); + + bool hit1 = inter1.x <= inter1.y && inter1.y >= 0; + bool hit2 = inter2.x <= inter2.y && inter2.y >= 0; + + if (hit1 && hit2) + { + let near = select(inter1.x < inter2.x, left, left + 1); + let far = select(inter1.x < inter2.x, left + 1, left); + node = select(go_far, far, near); + if (!go_far) + { + this.push(far, c); + } + } + else if (hit1 || hit2) + { + // At this level, we must have chosen the one that hit + node = select(hit1, left, left + 1); + } + } + + // Hit the far node + { + uint32_t left = parameters.nodes[node].first_or_left; + float2 inter1 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left].aabb.min(), parameters.nodes[left].aabb.max()); + float2 inter2 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left + 1].aabb.min(), parameters.nodes[left + 1].aabb.max()); + + bool hit1 = inter1.x <= inter1.y && inter1.y >= 0; + bool hit2 = inter2.x <= inter2.y && inter2.y >= 0; + + if (hit1 && hit2) + { + node = select(inter1.x < inter2.x, left + 1, left); + } + else if (hit1 || hit2) + { + // At this level, we must have chosen the one that hit + node = select(hit1, left, left + 1); + } + else + { + // Not hit, we can pop + if (c.stack_count == 0) + { + return false; + } + else + { + c.stack_head -= 1; + c.stack_count -= 1; + node = stack[(c.stack_head & STACK_MASK) * 256 + this.thread_index]; + c.depth = stack_depth[(c.stack_head & STACK_MASK) * 256 + this.thread_index]; + + // This node is done, mark it ok, remove bits of deeper levels, they're done + c.bit_stack = (c.bit_stack | 1 << c.depth) & ((2 << c.depth) - 1); + } + } + } + return true; + } +} + +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/out/voxel.spv b/shaders/out/voxel.spv index a4054d7eaf3eff86864912180775755c9ff23952..3c776b0ddd7c0578ea04ac8f8cc0990d0671aa43 100644 GIT binary patch literal 8540 zcmai(2bi2y6^18SvKt@}LP$c(l1?B6kWd7HO%M|$l7%3mqQmU&Bw5(mS!ZSmO$ky& zM2(8QVHZ%qf}$e!-g{TdEU)tF}AMR&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0Y`%Hc}IODEPKCYkq?r`R%J$~=q18l9#Yb}26+dbi|skW&7Xt4dAyFQm==bxf3 z`fJzMwc87wcR6 zHkQ8$YPXj1`-0C-_V|992q*9NQ|$Li=!;*PzT`0~;3O7ts`xCbr-I~QB$vL@-?V=r@aoA+DDo5*@N z?=kOAb>|;G@1Xnd6ZP@EppSa^xbIw0|GlC<-kbWUhmZB24);v*@%KA@)N`L1aC3Y4 zsO#gJ9ZKutn(4cU@#LJRt@D&qw~hD6v-Fvc-MJf2U*jD{>tj594o8=>zu0(vQapL} z=kU{RtNwJ-^^5!V2z;$$8O|CTD{M2t)=!(Y4V!hGh0VHYv!-FQezUQyO*ZS7+m6KM zyzCb?=XVsmkMq;#39y{`+nT?ex^2|!Xl#zxhj_--*LZVieT=8iT;v$U{~<7kU<&IDUW>l5RY!H#1M6n$cxMPTjmEmH@UI~TwBZ;%$F z%g65r^`H0mBmdj%;LpRoWS*+#g@_DQ#boq$Y z43^7dwV)fzZ_b!cE4qC2YXi&KFa8^*73j{>{EVy5eC9dGv2 vi{0z`MW0TvYnJ!vLLZv?i0z|a#9RrE^CQ-7Uita)9I3Cz=6SM>{|@xOAKcKG diff --git a/shaders/voxel.slang b/shaders/voxel.slang index a27b73f..24ace8c 100644 --- a/shaders/voxel.slang +++ b/shaders/voxel.slang @@ -2,6 +2,7 @@ import voxel_cache; // import fixed_structure_table; import toroidal_structure_table; +import bvh; import voxel_tracing; import lod_policies; @@ -42,7 +43,8 @@ public struct VertexOutput uniform PushConstants constants; ParameterBlock> cache_parameters; -ParameterBlock table_parameters; +// ParameterBlock table_parameters; +ParameterBlock table_parameters; public struct ColorHit : IVoxelHit { @@ -136,52 +138,72 @@ 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>(); - 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); - let ray_direction = get_ray_direction(location.xy); Ray r; r.origin = constants.cam_pos; r.direction = ray_direction; - PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f); + Bvh bvh; + bvh.parameters = table_parameters; + bvh.thread_index = local_location.x; + BvhCursor c = bvh.begin(r); + Cell cell; - 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) + // for (uint32_t i = 0; i < 100; i++) + // { + if (bvh.next(c, cell)) { - // 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., 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 = 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/src/bvh/build.rs b/src/bvh/build.rs index d7a69b4..a2223b2 100644 --- a/src/bvh/build.rs +++ b/src/bvh/build.rs @@ -149,6 +149,7 @@ pub struct Bvh { /// List of the bvh's nodes pub nodes: Vec, + pub depth: usize, } pub fn build_bvh(primitives: &mut [BvhPrimitive], leaf_max: usize) -> Bvh @@ -160,6 +161,7 @@ pub fn build_bvh(primitives: &mut [BvhPrimitive], leaf_max: usize) -> Bvh { return Bvh { nodes, + depth: 1, //prim_indices, }; } @@ -174,9 +176,14 @@ pub fn build_bvh(primitives: &mut [BvhPrimitive], leaf_max: usize) -> Bvh 0, )); - build_node(0, primitives, &mut nodes, leaf_max); + let mut max_depth = 0usize; + build_node(0, primitives, &mut nodes, leaf_max, 0, &mut max_depth); + println!("Max depth {}", max_depth); - Bvh { nodes } + Bvh { + nodes, + depth: max_depth, + } } pub fn build_node( @@ -184,6 +191,8 @@ pub fn build_node( primitives: &mut [BvhPrimitive], nodes: &mut Vec, leaf_max: usize, + depth: usize, + max_depth: &mut usize, ) { // We only extend a leaf if necessary @@ -248,12 +257,30 @@ pub fn build_node( nodes[node_index] = BvhNode::internal(nodes[node_index].aabb, left_index as u32); // Build children - build_node(left_index, primitives, nodes, leaf_max); - build_node(left_index + 1, primitives, nodes, leaf_max); + build_node( + left_index, + primitives, + nodes, + leaf_max, + depth + 1, + max_depth, + ); + build_node( + left_index + 1, + primitives, + nodes, + leaf_max, + depth + 1, + max_depth, + ); } None => { // Sah says keep as leaf, do nothing + if depth > *max_depth + { + *max_depth = depth; + } } } } diff --git a/src/bvh/debug.rs b/src/bvh/debug.rs index 56348c3..4dda75c 100644 --- a/src/bvh/debug.rs +++ b/src/bvh/debug.rs @@ -1,6 +1,7 @@ //! Contains rendering code to display a debug overlay for the BVH. use glam::Mat4; +use wgpu::BlendState; // debug.wgsl mirrors the GPU structs manually. Keep the array strides in sync: // WGSL would otherwise round them up to 16-byte alignment. @@ -37,44 +38,41 @@ impl BvhDebugPipeline { let shader = device.create_shader_module(wgpu::include_wgsl!("debug.wgsl")); - let bind_group_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("bvh_debug_bind_group_layout"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("bvh_debug_bind_group_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::VERTEX, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, }, - wgpu::BindGroupLayoutEntry { - binding: 2, - visibility: wgpu::ShaderStages::VERTEX, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: wgpu::BufferSize::new( - size_of::() as u64 - ), - }, - count: None, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new(size_of::() as u64), }, - ], - }); + count: None, + }, + ], + }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("bvh_debug_pipeline_layout"), @@ -89,54 +87,56 @@ impl BvhDebugPipeline mapped_at_creation: false, }); - let create_pipeline = - |label: &str, - vertex_entry: &str, - fragment_entry: &str, - topology: wgpu::PrimitiveTopology, - depth_write_enabled: bool| - -> wgpu::RenderPipeline { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some(vertex_entry), - compilation_options: Default::default(), - buffers: &[], - }, - primitive: wgpu::PrimitiveState { - topology, - strip_index_format: None, - front_face: wgpu::FrontFace::Ccw, - // Boxes stay visible even when the camera is inside one. - cull_mode: None, - unclipped_depth: false, - polygon_mode: wgpu::PolygonMode::Fill, - conservative: false, - }, - depth_stencil: Some(wgpu::DepthStencilState { - format: depth_format, - depth_write_enabled: Some(depth_write_enabled), - depth_compare: Some(wgpu::CompareFunction::LessEqual), - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some(fragment_entry), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: color_format, - blend: None, - write_mask: wgpu::ColorWrites::ALL, - })], - }), - multiview_mask: None, - cache: None, - }) - }; + let create_pipeline = |label: &str, + vertex_entry: &str, + fragment_entry: &str, + topology: wgpu::PrimitiveTopology, + depth_write_enabled: bool| + -> wgpu::RenderPipeline { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some(vertex_entry), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: wgpu::PrimitiveState { + topology, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + // Boxes stay visible even when the camera is inside one. + cull_mode: None, + unclipped_depth: false, + polygon_mode: wgpu::PolygonMode::Fill, + conservative: false, + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: depth_format, + depth_write_enabled: Some(depth_write_enabled), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some(fragment_entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: color_format, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent::OVER, + alpha: wgpu::BlendComponent::OVER, + }), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }; let solid_pipeline = create_pipeline( "bvh_debug_solid_pipeline", @@ -189,11 +189,7 @@ impl BvhDebugPipeline return; } - queue.write_buffer( - &self.view_proj_buffer, - 0, - bytemuck::bytes_of(&view_proj), - ); + queue.write_buffer(&self.view_proj_buffer, 0, bytemuck::bytes_of(&view_proj)); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("bvh_debug_bind_group"), @@ -245,10 +241,7 @@ impl BvhDebugPipeline if max_objects_per_leaf > 0 { pass.set_pipeline(&self.solid_pipeline); - pass.draw( - 0..36 * max_objects_per_leaf, - 0..node_count, - ); + pass.draw(0..36 * max_objects_per_leaf, 0..node_count); } pass.set_pipeline(&self.line_pipeline); diff --git a/src/bvh/debug.wgsl b/src/bvh/debug.wgsl index e2416ed..cdc92cb 100644 --- a/src/bvh/debug.wgsl +++ b/src/bvh/debug.wgsl @@ -37,13 +37,13 @@ struct GpuObject struct VertexOutput { @builtin(position) clip_position: vec4, - @location(0) color: vec3, + @location(0) color: vec4, @location(1) normal: vec3, }; -const INTERNAL_NODE_COLOR = vec3(0.15, 0.70, 1.0); -const LEAF_NODE_COLOR = vec3(1.0, 0.85, 0.20); -const OBJECT_COLOR = vec3(1.0, 0.45, 0.12); +const INTERNAL_NODE_COLOR = vec4(0.15, 0.70, 1.0, 1.0); +const LEAF_NODE_COLOR = vec4(1.0, 0.85, 0.20, 1.0); +const OBJECT_COLOR = vec4(1.0, 0.45, 0.12, 0.5); // Pushed fully outside the clip volume so skipped nodes/objects produce no // fragments. @@ -188,7 +188,7 @@ fn vs_solids( @fragment fn fs_lines(input: VertexOutput) -> @location(0) vec4 { - return vec4(input.color, 1.0); + return input.color; } @fragment @@ -198,5 +198,5 @@ fn fs_solids(input: VertexOutput) -> @location(0) vec4 let light_direction = normalize(vec3(0.45, 0.80, 0.55)); let diffuse = max(dot(normal, light_direction), 0.0); - return vec4(input.color * (0.35 + 0.65 * diffuse), 1.0); + return vec4(input.color * (0.35 + 0.65 * diffuse)); } diff --git a/src/main.rs b/src/main.rs index 45af6b0..2c14beb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -525,7 +525,7 @@ impl State let mut bvh = BvhStructureTable::new(&device, 128, 128); let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE); - for _ in 0..200 + for _ in 0..100 { let transform = Mat4::from_rotation_translation( Quat::from_euler( @@ -706,7 +706,8 @@ impl State bind_group_layouts: &[ Some(voxel_cache.raytrace_bind_group_layout()), - Some(structure_table.raytrace_bind_group_layout()), + //Some(structure_table.raytrace_bind_group_layout()), + Some(bvh.raytrace_bind_group_layout()), Some(&ray_march_bind_group_layout), ], immediate_size: size_of::() as u32, @@ -1202,11 +1203,12 @@ 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.structure_table.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(2, Some(&surface_bg), &[]); let table_base_slot = self.structure_table.lock().base_slot(); let imm = [Immediates { @@ -1235,6 +1237,11 @@ impl State renderpass.set_pipeline(&self.gi_pipeline); renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) }); renderpass.set_bind_group(2, Some(&gi_surface_bg), &[]); + renderpass.set_bind_group( + 1, + self.structure_table.lock().raytrace_bind_group(), + &[], + ); renderpass.dispatch_workgroups( self.size.width.div_ceil(16), self.size.height.div_ceil(16),