diff --git a/Cargo.toml b/Cargo.toml index 7bf05f5..afccaf3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ glam = "0.33.5" image = "0.25.10" indicatif = "0.18.6" itertools = "0.15.0" +noise = "0.9.0" pollster = "1.0.1" rand = "0.10.2" rayon = "1.12.0" diff --git a/shaders/Makefile b/shaders/Makefile index 4d59aed..4ab55d4 100644 --- a/shaders/Makefile +++ b/shaders/Makefile @@ -1,4 +1,7 @@ -all: voxel.spv compaction.spv +all: clean voxel.spv compaction.spv gi.spv + +clean: + rm -f *.spv %.spv: %.slang slangc $< -O3 -fvk-use-entrypoint-name -target spirv -o $@ diff --git a/shaders/cache.wgsl b/shaders/cache.wgsl deleted file mode 100644 index 0550803..0000000 --- a/shaders/cache.wgsl +++ /dev/null @@ -1,334 +0,0 @@ -struct VoxelStructureNode -{ - pointers: array -} - -struct VoxelColorNode -{ - pointers: array, 64> -} - -struct CacheNodeRequest -{ - location_info: u32, - request_count: u32 -} - -struct CacheNodeUsageBuffer -{ - touch_time: u32, - parent: u32, -} - -// Rendering kernels -struct ChunkInfo -{ - mvp: mat4x4, - eye_pos: vec3, - root_color: vec4, - root_subdiv: u32, - frame_timestamp: u32, -} - -struct StructureNode -{ - pointers: array -} - -struct RequestElement -{ - pointers: array, 64> -} - -struct ColorNode -{ - colors: array, 64> -} - -struct VertexOutput -{ - @builtin(position) postion: vec4, - @location(0) world_loc: vec3, - @location(1) cam_pos: vec3, -} - -var constants: ChunkInfo; -//var constants: ChunkInfo; - -@vertex -fn chunk(@builtin(vertex_index) index: u32) -> VertexOutput -{ - let cube_vertices = array, 8>( - vec3(0., 0., 0.), - vec3(0., 0., 1.), - vec3(1., 0., 1.), - vec3(1., 0., 0.), - - vec3(0., 1., 0.), - vec3(0., 1., 1.), - vec3(1., 1., 1.), - vec3(1., 1., 0.), - ); - - let cube_faces = array( - // Bottom face - 1, 0, 2, 3, - - // Top face - 4, 5, 7, 6, - - // Side faces - 0, 1, 4, 5, - 1, 2, 5, 6, - 2, 3, 6, 7, - 3, 0, 7, 4, - ); - - let quad_index = index / (3 * 2); - let triangle_index = index % (3 * 2); - let triangle_map = array( - 0, 1, 2, 1, 3, 2 - ); - - let vertex = cube_vertices[cube_faces[quad_index * 4 + triangle_map[triangle_index]]]; - let output_vertex = constants.mvp * vec4(vertex, 1.0f); - - var output: VertexOutput; - output.postion = output_vertex; - output.world_loc = vertex; - output.cam_pos = constants.eye_pos; - - //let output = vec4(vertex, 1.0f); - return output; -} - -@group(0) @binding(0) var structure_buffer: array; -@group(0) @binding(1) var color_buffer: array; -@group(0) @binding(2) var request_buffer: array; -@group(0) @binding(3) var usage_buffer: array; - - -fn box_inter(pos: vec3, ray_dir: vec3, box_min: vec3, box_max: vec3) -> vec2 -{ - let box_min_t = (box_min - pos) / ray_dir; - let box_max_t = (box_max - pos) / ray_dir; - - let near_ts = min(box_min_t, box_max_t); - let far_ts = max(box_min_t, box_max_t); - - let far_t = min(min(far_ts.x, far_ts.y), far_ts.z); - let near_t = max(max(near_ts.x, near_ts.y), near_ts.z); - - return vec2(near_t, far_t); -} - -fn sdf(voxel: vec3) -> bool -{ - let len = length(vec3(voxel) - vec3(128)) / 128.; - return len <= 1.; -} - -fn min_vec(x: vec3) -> f32 -{ - return min(x.x, min(x.y, x.z)); -} - -fn min_mask(x: vec3) -> vec3 -{ - let min = min(x.x, min(x.y, x.z)); - - return vec3(min == x.x, min == x.y, min == x.z); -} - -fn node_subdivided(node: u32) -> bool -{ - return (node >> 31) != 0; -} - -fn node_pointer_valid(node: u32) -> bool -{ - return ((node >> 30) & 1) != 0; -} - -fn node_pointer(node: u32) -> u32 -{ - return node & 0x3FFFFFFF; -} - -fn voxel_from_wall(position: vec3, ray_dir: vec3) -> vec3 -{ - let integers = round(position); - let wall_mask = min_mask(abs(position - vec3(integers))); - let offsets = select(vec3(-0.5), vec3(0.5), ray_dir > vec3(0.)); - return vec3(floor(position + select(vec3(0.), offsets, wall_mask))); -} - -fn traverse(ray_dir: vec3, ray_origin: vec3, root_color: vec4, root_subdiv: bool) -> vec4 -{ - // Simple FVT - let t_off = abs(1. / ray_dir); - - // Start location - let voxel_dir = select(vec3(-1), vec3(1), ray_dir >= vec3(0.)); - var pos_origin = clamp(ray_origin * 256., vec3(0.), vec3(256. - 1.)); - var voxel = vec3(pos_origin); - var last_voxel = voxel; - - let wall_offset = select(vec3(0), vec3(1), ray_dir > vec3(0.)); - - var dfs_stack = array(0, 0, 0, 0, 0); - - // Current depth of the node we are exploring - var current_depth = 0; - - // Index of the current node's data - var current_node = u32(0); - - // Current node size - var node_size = 4 * 4 * 4 * 4; // 128 - - // Size of a child of this node - var child_size = node_size / 4; - - // Lut of the node_size per depth - var node_size_lut = array( - 4 * 4 * 4 * 4, - 4 * 4 * 4, - 4 * 4, - 4, - 1, - ); - - let depth_limit = 1; - for(var iter = 0; iter < 256; iter ++) - { - - // Our ray is currently touching a voxel. - // Descend to the lowest node that contains this voxel - - // Position of the child we are in - var child_pos = (vec3(voxel) >> vec3((4 - u32(current_depth + 1)) * 2)) & vec3(3); // Hardcode for 4-tree - var child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4; - - // Current node has been used. report - usage_buffer[current_node] = constants.frame_timestamp; - - while( - node_subdivided(structure_buffer[current_node].pointers[child_index]) - && current_depth < depth_limit) - { - if(!node_pointer_valid(structure_buffer[current_node].pointers[child_index])) - { - atomicAdd(&request_buffer[current_node].pointers[child_index], 1); - break; - } - // Child node is subdivided, we go in, save position in stack - current_node = node_pointer(structure_buffer[current_node].pointers[child_index]); - usage_buffer[current_node] = constants.frame_timestamp; - current_depth += 1; - dfs_stack[current_depth] = current_node; - node_size = node_size_lut[current_depth]; - - child_pos = (vec3(voxel) >> vec3((4 - u32(current_depth + 1)) * 2)) & vec3(3); // Hardcode for 4-tree - child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4; - child_size = node_size / 4; - } - - - // At this point current_depth is the depth of the node that contains the voxel - // child_pos and child_index relate to the specific child of the node that contains this voxel - // It is guaranteed that the child is leave - - // Check current leave's color - let color = color_buffer[current_node].colors[child_index]; - if(color.w != 0.) // Not transparent - { - let k = child_pos.x + child_pos.y + child_pos.z; - let x = select(0.5, 1., k % 2 == 0); - return x * color / f32(current_depth); - } - - // Voxel and whole child containing it is empty - - // Perform a step through the children of the node - let child_position = (voxel / child_size) * child_size; - let far_corner = child_position + wall_offset * child_size; - let far_ts = (vec3(far_corner) - pos_origin) / ray_dir; // TODO: Turn into fma - let far_t = min(min(far_ts.x, far_ts.y), far_ts.z); - - let next_child_min = select(child_position, child_position + wall_offset * child_size, vec3(far_t) == far_ts); - let next_child_max = next_child_min + vec3(child_size); - - // The ray (far_t) is now touching the new child to explore - // Find out which actual voxel we are touching - let previous_voxel = voxel; - let float_voxel = clamp(pos_origin + far_t * ray_dir, vec3(next_child_min), vec3(next_child_max)); - /* - voxel = vec3( - floor( - select( - float_voxel - vec3(0.5), - float_voxel + vec3(0.5), - ray_dir > vec3(0.) - )) - ); - */ - //voxel = vec3(round(float_voxel)); - voxel = voxel_from_wall(float_voxel, ray_dir); - if(any(voxel < vec3(0)) || any(voxel >= vec3(256))) - { - //return vec4(f32(iter) / 100.); - discard; - } - - // We touched a voxel as if we explored blocks sized by the child size of the current node. - // But we might have exited the current node. - - // If this is the case we have to walk back up the tree - // And then back down to the next node over - - // As such we find the lowest ancestor that can contain both the privous voxel (in node) and the new voxel (out of node) - let bit_diffs = voxel ^ previous_voxel; - let bit_diffs_lowest = bit_diffs.x | bit_diffs.y | bit_diffs.z; - - let flb = ((countLeadingZeros(bit_diffs_lowest) - 24) / 2); - let common_depth = flb; - - current_depth = common_depth; - node_size = node_size_lut[current_depth]; - child_size = node_size / 4; - current_node = dfs_stack[current_depth]; - - // Figure out current voxel position - //voxel = vec3(ray_origin + ray_dir * t); - - } - return vec4(1., 0., 1., 1.); - -} - -@fragment -fn fragment(in: VertexOutput) -> @location(0) vec4 -{ - let ray_dir = normalize(in.world_loc - in.cam_pos); - let interp = box_inter(in.cam_pos, ray_dir, vec3(0.), vec3(1)); - let ray_origin = in.cam_pos + ray_dir * (max(0., interp.x)); - - return traverse(ray_dir, ray_origin, constants.root_color, constants.root_subdiv != 0); - return vec4(interp.y / 10.); -} - -// Cache managment kernels - -// Request buffer managment -// Compaction -@workgroup_size(64) -fn main( - @builtin(global_invocation_id) gid: vec3 -) -{ - let cache_size = 1024; - let index = gid.x; - - for() -} diff --git a/shaders/example.slang b/shaders/example.slang deleted file mode 100644 index a191be2..0000000 --- a/shaders/example.slang +++ /dev/null @@ -1,2 +0,0 @@ -module example; - diff --git a/shaders/gi.slang b/shaders/gi.slang new file mode 100644 index 0000000..a70cc70 --- /dev/null +++ b/shaders/gi.slang @@ -0,0 +1,265 @@ +import ray_cast; + +struct PushConstants +{ + float4x4 view_proj; + float3 cam_pos; + uint32_t frame_timestamp; + uint32_t width; + uint32_t height; + + uint32_t chunk_width; + uint32_t chunk_height; + uint32_t chunk_alt; +} + +public struct VertexOutput +{ + public float4 position : SV_Position; + + [vk::location(0)] + public float3 world_position; + + [vk::location(1)] + public nointerpolation uint32_t structure_id; + + [vk::location(2)] + public float3 cam_position; + + [vk::location(3)] + public float3 chunk_position; +} + +[[vk::push_constant]] +uniform PushConstants constants; + +struct ByteColor +{ + uint32_t byte_color; + + property uint32_t byte_r + { + get { + return byte_color & 0xFF; + } + } + + property uint32_t byte_g + { + get { + return (byte_color >> 8) & 0xFF; + } + } + + property uint32_t byte_b + { + get { + return (byte_color >> 16) & 0xFF; + } + } + + property uint32_t byte_a + { + get { + return byte_color >> 24; + } + } + + property float4 float_color + { + get { + return float4( + float(byte_r) / 255., + float(byte_g) / 255., + float(byte_b) / 255., + float(byte_a) / 255.); + } + } +} + +[[vk::binding(0, 0)]] +RWStructuredBuffer structure_pool; +[[vk::binding(1, 0)]] +RWStructuredBuffer attributes_pool[2]; +[[vk::binding(2, 0)]] +RWStructuredBuffer location_pool; +[[vk::binding(3, 0)]] +RWStructuredBuffer request_buffer; +[[vk::binding(4, 0)]] +RWStructuredBuffer usage_buffer; +[[vk::binding(5, 0)]] +RWStructuredBuffer structure_table_pointer; +[[vk::binding(6, 0)]] +RWStructuredBuffer> structure_table_request_buffer; + +ByteColor fetch_color(uint32_t index, uint32_t child_index) +{ + return ByteColor(attributes_pool[0][index * 64 + child_index]); +} + +float3 fetch_normal(uint32_t index, uint32_t child_index) +{ + let a = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3]); + let b = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]); + let c = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]); + return float3(a, b, c); +} + +bool3 min_mask(float3 val) +{ + let min_val = min(val.x, min(val.y, val.z)); + return val == min_val; +} + +[[vk::binding(0, 1)]] +[[format("rgba32f")]] +WTexture2D target_texture; + +[[vk::binding(1, 1)]] +[[format("rgba32f")]] +RWTexture2D gbuffer_position; + +[[vk::binding(2, 1)]] +[[format("rgba32f")]] +RWTexture2D gbuffer_albedo; + +[[vk::binding(3, 1)]] +[[format("rgba32f")]] +RWTexture2D gbuffer_normal; + +float3 get_ray_direction(uint32_t2 pixel_loc) +{ + 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); +} + +[shader("compute")] +[numthreads(16, 16, 1)] +void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID) +{ + if (location.x >= constants.width || location.y >= constants.height) + { + return; + } + + if (gbuffer_albedo.Load(location.xy).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); + target_texture.Store(location.xy, albedo); + return; + let illumination = dot(float3(0., 1., 0.), normal.xyz); + + let view_dir = pos.xyz - constants.cam_pos; + // let ray_dir = normalize(reflect(view_dir, normal.xyz)); + let ray_dir = sampleHemisphere(normal.xyz, constants.frame_timestamp, 6767 + (location.x * 67) + (location.y * 91)); + if (any(isinf(ray_dir)) || any(isnan(ray_dir))) + { + target_texture.Store(location.xy, albedo); + return; + } + + let stack_index = local_location.x + local_location.y * 16; + + var voxel_cache : VoxelCache; + voxel_cache.structure_pool = structure_pool; + voxel_cache.attributes_pool = attributes_pool; + voxel_cache.location_pool = location_pool; + voxel_cache.request_buffer = request_buffer; + voxel_cache.usage_buffer = usage_buffer; + voxel_cache.structure_table_pointer = structure_table_pointer; + voxel_cache.structure_table_request_buffer = structure_table_request_buffer; + + var ray_cast_context : RayCastContext; + ray_cast_context.ray_direction = ray_dir; + ray_cast_context.ray_origin = pos.xyz + normal.xyz * 0.1; + ray_cast_context.bounds = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width); + ray_cast_context.frame_timestamp = constants.frame_timestamp; + ray_cast_context.cache_report = true; + + let hit = ray_cast(voxel_cache, ray_cast_context, stack_index); + + if (hit.hit) + { + // Gather + let smpl_albedo = fetch_color(hit.node_index, hit.child_index).float_color; + target_texture.Store(location.xy, albedo * smpl_albedo); + } + else + { + target_texture.Store(location.xy, float4(float3(illumination), 1.)); + } +} + +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); +} + +// Returns a cosine-weighted random direction in the hemisphere +// oriented around `normal`. +// +// `frame` should change every frame/sample sequence. +// `seed` can be a per-pixel or per-path identifier. +float3 sampleHemisphere(float3 normal, uint frame, uint seed) +{ + // Hash to get two uniform random numbers in [0, 1). + uint state = seed ^ (frame * 0x9E3779B9u); + + state ^= state >> 16; + state *= 0x7FEB352Du; + state ^= state >> 15; + state *= 0x846CA68Bu; + state ^= state >> 16; + + float u1 = float(state) * (1.0 / 4294967296.0); + + state ^= state >> 16; + state *= 0x7FEB352Du; + state ^= state >> 15; + state *= 0x846CA68Bu; + state ^= state >> 16; + + float u2 = float(state) * (1.0 / 4294967296.0); + + // Cosine-weighted hemisphere sampling. + float r = sqrt(u1); + float phi = 2.0 * 3.14159 * u2; + + float x = r * cos(phi); + float y = r * sin(phi); + float z = sqrt(max(0.0, 1.0 - u1)); + + // Build an orthonormal basis around the normal. + float3 tangent; + + if (abs(normal.z) < 0.999) + tangent = normalize(cross(float3(0.0, 0.0, 1.0), normal)); + else + tangent = normalize(cross(float3(0.0, 1.0, 0.0), normal)); + + float3 bitangent = cross(normal, tangent); + + // Transform from local hemisphere space to world space. + return normalize( + tangent * x + + bitangent * y + + normal * z); +} + diff --git a/shaders/gi.spv b/shaders/gi.spv new file mode 100644 index 0000000..795f929 Binary files /dev/null and b/shaders/gi.spv differ diff --git a/shaders/ray_cast.slang b/shaders/ray_cast.slang new file mode 100644 index 0000000..dd52c2d --- /dev/null +++ b/shaders/ray_cast.slang @@ -0,0 +1,394 @@ +module ray_cast; + +struct ByteColor +{ + uint32_t byte_color; + + property uint32_t byte_r + { + get { + return byte_color & 0xFF; + } + } + + property uint32_t byte_g + { + get { + return (byte_color >> 8) & 0xFF; + } + } + + property uint32_t byte_b + { + get { + return (byte_color >> 16) & 0xFF; + } + } + + property uint32_t byte_a + { + get { + return byte_color >> 24; + } + } + + property float4 float_color + { + get { + return float4( + float(byte_r) / 255., + float(byte_g) / 255., + float(byte_b) / 255., + float(byte_a) / 255.); + } + } +} + +public struct StructurePointer +{ + uint32_t value; + + bool subdivided() + { + return (this.value & 0x80000000) != 0; + } + + bool pointer_valid() + { + return (this.value & 0x40000000) != 0; + } + + bool subdivided_valid() + { + return (this.value & 0xC0000000) == 0xC0000000; + } + + uint32_t pointer() + { + return this.value & 0x3FFFFFFF; + } +} + +public struct StructurePoolElement +{ + public uint32_t occupancy_low; + public uint32_t occupancy_high; + public StructurePointer pointers[64]; +} + +public struct RequestBufferElement +{ + public Atomic requests[64]; +} + +public struct LocationPoolElement +{ + public uint32_t structure_id; + public uint32_t structure_locator; +} + +public struct VoxelCache +{ + public RWStructuredBuffer structure_pool; + public RWStructuredBuffer attributes_pool[2]; + public RWStructuredBuffer location_pool; + public RWStructuredBuffer request_buffer; + public RWStructuredBuffer usage_buffer; + public RWStructuredBuffer structure_table_pointer; + public RWStructuredBuffer> structure_table_request_buffer; +} + +ByteColor fetch_color(VoxelCache cache, uint32_t index, uint32_t child_index) +{ + return ByteColor(cache.attributes_pool[0][index * 64 + child_index]); +} + +uint32_t3 get_children_pos(float3 position, uint32_t scale_exp) +{ + return (asuint(position) >> scale_exp) & 3; +} + +uint32_t get_children_index(float3 position, uint32_t scale_exp) +{ + // Get mantissa bits for this scale exp an retain bits for the specific children + uint32_t3 cell_position = (asuint(position) >> scale_exp) & 3; + return cell_position.x + cell_position.y * 4 + cell_position.z * 4 * 4; +} + +uint64_t get_child_mask(uint32_t low, uint32_t high) +{ + return ((uint64_t)high << 32) | (uint64_t)low; +} + +float3 floor_scale(float3 position, uint32_t scale_exp) +{ + uint32_t mask = ~0u << scale_exp; + return asfloat(asuint(position) & mask); +} + +public struct HitInformation +{ + public bool hit; + public float3 hit_pos; + public uint32_t node_index; + public uint32_t child_index; + public float4 color; +} + +groupshared uint32_t stack[256 * 5]; + +HitInformation chunk_ray_march( + VoxelCache cache, + float3 real_ray_direction, + float3 ray_origin, + uint32_t root_id, + float dist_offset, + uint32_t stack_index, + uint32_t frame_timestamp, + bool report, ) +{ + // Cone tracing info + float fov_deg = 100. / 1920.; + float fov_rad = (float.getPi() * fov_deg) / 180.; + float cone_factor = tan(fov_rad / 2.) * 2; // Horizontal size of pixel + + let st_pointer = cache.structure_table_pointer[root_id]; + + if (!st_pointer.subdivided()) + { + var hit : HitInformation; + hit.hit = false; + return hit; + } + + if (!st_pointer.pointer_valid()) + { + // Record request + if (report) + { + cache.structure_table_request_buffer[root_id].add(1); + } + var hit : HitInformation; + hit.hit = false; + return hit; + } + + // Ray mirroring + ray_origin += float3(1.); + ray_origin = clamp(ray_origin, float(1.), asfloat(0x3fffffff)); + ray_origin = select(real_ray_direction > 0., asfloat(asuint(ray_origin) ^ 0x007fffff), ray_origin); + uint32_t child_mirror = 0; + if (real_ray_direction.x > 0.) + { + child_mirror |= 3; + } + if (real_ray_direction.y > 0.) + { + child_mirror |= 3 << 2; + } + if (real_ray_direction.z > 0.) + { + child_mirror |= 3 << 4; + } + let ray_direction = -abs(real_ray_direction); + + float3 pos = ray_origin; + uint32_t scale_exp = 23 - 2; + uint32_t current_node_index = cache.structure_table_pointer[root_id].pointer(); + if (report) + { + cache.usage_buffer[current_node_index] = frame_timestamp; + } + stack[stack_index * 5 + 10 - scale_exp / 2] = current_node_index; + + [loop] + for (uint32_t iter = 0; iter < 500; iter++) + { + uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror; + StructurePointer current_node = cache.structure_pool[current_node_index].pointers[child_index]; + + // Scale computations + let cone_size = (length(ray_origin - pos) + dist_offset) * cone_factor; + let exponent = + select( + cone_size == 0., + 0, + 23 - (127 - (asuint(cone_size) >> 23))); + + while ( + current_node.subdivided_valid() && + scale_exp - 2 > exponent) + { + scale_exp -= 2; + current_node_index = current_node.pointer(); + stack[stack_index * 5 + 10 - scale_exp / 2] = current_node_index; + child_index = get_children_index(pos, scale_exp) ^ child_mirror; + current_node = cache.structure_pool[current_node_index].pointers[child_index]; + // Write usage + if (report) + { + cache.usage_buffer[current_node_index] = frame_timestamp; + } + } + + // Request subdiv + if (report && current_node.subdivided() && !current_node.pointer_valid()) + { + cache.request_buffer[current_node_index].requests[child_index].add(1); + } + + uint64_t occupancy = get_child_mask(cache.structure_pool[current_node_index].occupancy_low, cache.structure_pool[current_node_index].occupancy_high); + let occupied = ((occupancy >> child_index) & 1) != 0; + // if (occupied) + if (fetch_color(cache, current_node_index, child_index).byte_a != 0) + { + var hit : HitInformation; + hit.hit = true; + hit.node_index = current_node_index; + hit.child_index = child_index; + hit.hit_pos = + select( + real_ray_direction > 0., + asfloat(asuint(pos) ^ 0x007fffff), + pos) - + float3(1.); + return hit; + } + + uint32_t adv_scale_exp = scale_exp; + if (((occupancy >> (child_index & 0b101010)) & 0x00330033) == 0) + { + adv_scale_exp++; + } + + // Perform dda + // Compute correct exponent, and shift it into the exponent part of floatt + let child_pos : float3 = floor_scale(pos, adv_scale_exp); + // Intersection t + let inter_ts : float3 = (child_pos - ray_origin) / ray_direction; + float inter_t = min(inter_ts.x, min(inter_ts.y, inter_ts.z)); + // return float4(inter_t); + + // Perform dda step + // let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1); + let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1); + pos = min(ray_origin + ray_direction * inter_t, asfloat(neighbor_max)); + + // Find most common ancestor + uint32_t3 diffs = asuint(child_pos) ^ asuint(pos); + uint32_t diff = (diffs.x | diffs.y | diffs.z); + + int32_t common_depth = (1 + (22 - firstbithigh(diff)) / 2) * 2; + if (common_depth <= 0) + { + break; + } + + scale_exp = 23 - common_depth; + current_node_index = stack[stack_index * 5 + 10 - scale_exp / 2]; + } + + var hit : HitInformation; + hit.hit = false; + return hit; +} + +public struct RayCastContext +{ + public float3 ray_direction; + public float3 ray_origin; + public uint32_t3 bounds; + public uint32_t frame_timestamp; + public bool cache_report; +} + +public HitInformation ray_cast( + VoxelCache cache, + RayCastContext context, + uint32_t thread_id) +{ + let stack_index = thread_id; + + // Intersect with bounds + var inter = box_intersect(context.ray_origin, context.ray_direction, float3(0.), float3(context.bounds.x, context.bounds.y, context.bounds.z)); + + // No hit if out of box + if (inter.y <= inter.x || inter.y <= 0.) + { + var hit : HitInformation; + hit.hit = false; + return hit; + } + inter.x = max(0., inter.x); + + // Now march inside chunk bounds + let start_position = inter.x * context.ray_direction + context.ray_origin; + // FVT + int32_t3 current_voxel = clamp( + int32_t3(floor(start_position)), + int32_t3(0), + int32_t3(context.bounds.x - 1, context.bounds.y - 1, context.bounds.z - 1)); + // int32_t3 offset = int32_t3(sign(ray_direction)); + // float3 delta = abs(1. / ray_direction); + float3 t = select( + context.ray_direction > 0., + current_voxel + int32_t3(1) - start_position, + start_position - current_voxel) / + abs(context.ray_direction); + t += inter.x; + + [loop] + while (true) + { + if (any(current_voxel < 0) || any(current_voxel >= int32_t3(context.bounds.x, context.bounds.y, context.bounds.z))) + { + var hit : HitInformation; + hit.hit = false; + return hit; + } + { + let off = t - abs(1. / context.ray_direction); + let t_adv = max(max(off.x, max(off.y, off.z)), 0.); + let chunk_index = current_voxel.y + current_voxel.z * context.bounds.y + current_voxel.x * context.bounds.y * context.bounds.z; + let position = context.ray_origin + context.ray_direction * t_adv; + var hit = chunk_ray_march( + cache, + context.ray_direction, + position - float3(current_voxel), + chunk_index, + t_adv, + stack_index, + context.frame_timestamp, + context.cache_report); + if (hit.hit) + { + hit.hit_pos += float3(current_voxel); + return hit; + } + } + + let min_mask = min_mask(t); + t += select(min_mask, abs(1. / context.ray_direction), float3(0.)); + current_voxel += select(min_mask, int32_t3(sign(context.ray_direction)), int32_t3(0)); + } +} + +bool3 min_mask(float3 val) +{ + let min_val = min(val.x, min(val.y, val.z)); + return val == min_val; +} + +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/voxel.slang b/shaders/voxel.slang index d6a31d3..18e4fdd 100644 --- a/shaders/voxel.slang +++ b/shaders/voxel.slang @@ -1,3 +1,5 @@ +import ray_cast; + struct PushConstants { float4x4 view_proj; @@ -31,348 +33,95 @@ public struct VertexOutput [[vk::push_constant]] uniform PushConstants constants; -[shader("vertex")] -VertexOutput chunk( - uint index: SV_VulkanVertexID, - [vk::location(0)] float3 chunk_position, - [vk::location(1)] uint id) -{ - let cube_vertices : float3[8] = - float3[]( - float3(0., 0., 0.), - float3(0., 0., 1.), - float3(1., 0., 1.), - float3(1., 0., 0.), - - float3(0., 1., 0.), - float3(0., 1., 1.), - float3(1., 1., 1.), - float3(1., 1., 0.), ); - // clang-format off - let cube_faces: int[24] = int[]( - // Bottom face - 1, 0, 2, 3, - - // Top face - 4, 5, 7, 6, - - // Side faces - 0, 1, 4, 5, - 1, 2, 5, 6, - 2, 3, 6, 7, - 3, 0, 7, 4, - ); - - let quad_index = index / (3 * 2); - let triangle_index = index % (3 * 2); - let triangle_map: int[6] = int[]( - 0, 1, 2, 1, 3, 2 - ); - - - let vertex = cube_vertices[cube_faces[quad_index * 4 + triangle_map[triangle_index]]]; - let output_vertex = mul(constants.view_proj, float4(vertex + chunk_position, 1.0f)); - - VertexOutput vertex_output; - vertex_output.position = output_vertex; - vertex_output.world_position = vertex + chunk_position; - vertex_output.structure_id = id; - vertex_output.cam_position = constants.cam_pos; - vertex_output.chunk_position = chunk_position; - - return vertex_output; -} - -struct StructurePointer -{ - uint32_t value; - bool subdivided() - { - return (this.value & 0x80000000) != 0; - } - - bool pointer_valid() - { - return (this.value & 0x40000000) != 0; - } - - bool subdivided_valid() - { - return (this.value & 0xC0000000) == 0xC0000000; - } - - uint32_t pointer() - { - return this.value & 0x3FFFFFFF; - } -} - struct ByteColor { uint32_t byte_color; - - property uint32_t byte_r { - get {return byte_color & 0xFF;} + + property uint32_t byte_r + { + get { + return byte_color & 0xFF; + } } - property uint32_t byte_g { - get {return (byte_color >> 8) & 0xFF;} + property uint32_t byte_g + { + get { + return (byte_color >> 8) & 0xFF; + } } - property uint32_t byte_b { - get {return (byte_color >> 16) & 0xFF;} + property uint32_t byte_b + { + get { + return (byte_color >> 16) & 0xFF; + } } - property uint32_t byte_a { - get {return byte_color >> 24;} + property uint32_t byte_a + { + get { + return byte_color >> 24; + } } - property float4 float_color { - get {return float4( + property float4 float_color + { + get { + return float4( float(byte_r) / 255., float(byte_g) / 255., float(byte_b) / 255., - float(byte_a) / 255. - ); } + float(byte_a) / 255.); + } } } -struct StructurePoolElement +[[vk::binding(0, 0)]] +RWStructuredBuffer structure_pool; +[[vk::binding(1, 0)]] +RWStructuredBuffer attributes_pool[2]; +[[vk::binding(2, 0)]] +RWStructuredBuffer location_pool; +[[vk::binding(3, 0)]] +RWStructuredBuffer request_buffer; +[[vk::binding(4, 0)]] +RWStructuredBuffer usage_buffer; +[[vk::binding(5, 0)]] +RWStructuredBuffer structure_table_pointer; +[[vk::binding(6, 0)]] +RWStructuredBuffer> structure_table_request_buffer; + +ByteColor fetch_color(uint32_t index, uint32_t child_index) { - uint32_t occupancy_low; - uint32_t occupancy_high; - StructurePointer pointers[64]; + return ByteColor(attributes_pool[0][index * 64 + child_index]); } -struct RequestBufferElement +float3 fetch_normal(uint32_t index, uint32_t child_index) { - Atomic requests[64]; + let a = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3]); + let b = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]); + let c = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]); + return float3(a, b, c); } -struct ColorPoolElement -{ - ByteColor colors[64]; -} - -struct LocationPoolElement -{ - uint32_t structure_id; - uint32_t structure_locator; -} - -[[vk::binding(0, 0)]] RWStructuredBuffer structure_pool; -[[vk::binding(1, 0)]] RWStructuredBuffer color_pool; -[[vk::binding(2, 0)]] RWStructuredBuffer location_pool; -[[vk::binding(3, 0)]] RWStructuredBuffer request_buffer; -[[vk::binding(4, 0)]] RWStructuredBuffer usage_buffer; -[[vk::binding(5, 0)]] RWStructuredBuffer structure_table_pointer; -[[vk::binding(6, 0)]] RWStructuredBuffer> structure_table_request_buffer; - -uint32_t3 get_children_pos(float3 position, uint32_t scale_exp) -{ - return (asuint(position) >> scale_exp) & 3; -} - -uint32_t get_children_index(float3 position, uint32_t scale_exp) -{ - // Get mantissa bits for this scale exp an retain bits for the specific children - uint32_t3 cell_position = (asuint(position) >> scale_exp) & 3; - return cell_position.x + cell_position.y * 4 + cell_position.z * 4 * 4; -} - -uint64_t get_child_mask(uint32_t low, uint32_t high) -{ - return ((uint64_t)high << 32) | (uint64_t)low; -} - -float3 floor_scale(float3 position, uint32_t scale_exp) -{ - uint32_t mask = ~0u << scale_exp; - return asfloat(asuint(position) & mask); -} - -struct HitInformation -{ - bool hit; - float3 hit_pos; - float4 color; -} - -// struct NodeStack -// { -// uint32_t node_stack[5]; -// } - -groupshared uint32_t stack[256 * 5]; - -HitInformation ray_march(float3 ray_direction, float3 ray_origin, uint32_t root_id, float dist_offset, uint32_t stack_index) -{ - float fov_deg = 100. / 1920.; - float fov_rad = (float.getPi() * fov_deg) / 180.; - float cone_factor = tan(fov_rad / 2.) * 2; // Horizontal size of pixel - - let st_pointer = structure_table_pointer[root_id]; - if(!st_pointer.subdivided()) - { - var hit: HitInformation; - hit.hit = false; - return hit; - } - - if(!st_pointer.pointer_valid()) - { - // Record request - structure_table_request_buffer[root_id].add(1); - var hit: HitInformation; - hit.hit = false; - return hit; - } - - ray_origin += float3(1.); - ray_origin = clamp(ray_origin , float(1.), asfloat(0x3fffffff)); - ray_origin = select(ray_direction > 0., asfloat(asuint(ray_origin) ^ 0x007fffff), ray_origin); - uint32_t child_mirror = 0; - if(ray_direction.x > 0.) {child_mirror |= 3;} - if(ray_direction.y > 0.) {child_mirror |= 3 << 2;} - if(ray_direction.z > 0.) {child_mirror |= 3 << 4;} - ray_direction = -abs(ray_direction); - - float3 pos = ray_origin; - - uint32_t scale_exp = 23 - 2; - uint32_t node_stack[5] = - { - 0 - }; - - uint32_t current_node_index = structure_table_pointer[root_id].pointer(); - usage_buffer[current_node_index] = constants.frame_timestamp; - stack[stack_index * 5 + 10 - scale_exp / 2] = current_node_index; - //node_stack[10 - scale_exp / 2] = current_node_index; - - [loop] - for(uint32_t iter = 0; iter < 500; iter ++) - { - uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror; - StructurePointer current_node = structure_pool[current_node_index].pointers[child_index]; - - // Scale computations - let cone_size = (length(ray_origin - pos) + dist_offset) * cone_factor; - let exponent = - select( - cone_size == 0., - 0, - 23 - (127 - (asuint(cone_size) >> 23)) - ); - - while( - current_node.subdivided_valid() && - scale_exp - 2 > exponent - ) - { - scale_exp -= 2; - current_node_index = current_node.pointer(); - stack[stack_index * 5 + 10 - scale_exp / 2] = current_node_index; - //node_stack[10 - scale_exp / 2] = current_node_index; - child_index = get_children_index(pos, scale_exp) ^ child_mirror; - current_node = structure_pool[current_node_index].pointers[child_index]; - // Write usage - usage_buffer[current_node_index] = constants.frame_timestamp; - } - - // Request subdiv - if(current_node.subdivided() && !current_node.pointer_valid()) - { - request_buffer[current_node_index].requests[child_index].add(1); - } - - if(color_pool[current_node_index].colors[child_index].byte_a != 0) - { - var hit: HitInformation; - hit.hit = true; - hit.hit_pos = pos - float3(1.); - hit.color = color_pool[current_node_index].colors[child_index].float_color; - return hit; - } - - uint64_t occupancy = get_child_mask(structure_pool[current_node_index].occupancy_low, structure_pool[current_node_index].occupancy_high); - uint32_t adv_scale_exp = scale_exp; - if(((occupancy >> (child_index & 0b101010)) & 0x00330033) == 0) - { - adv_scale_exp ++; - } - - // Perform dda - // Compute correct exponent, and shift it into the exponent part of floatt - let child_pos : float3 = floor_scale(pos, adv_scale_exp); - // Intersection t - let inter_ts : float3 = (child_pos - ray_origin) / ray_direction; - float inter_t = min(inter_ts.x, min(inter_ts.y, inter_ts.z)); - //return float4(inter_t); - - // Perform dda step - //let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1); - let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1); - pos = min(ray_origin + ray_direction * inter_t, asfloat(neighbor_max)); - - // Find most common ancestor - uint32_t3 diffs = asuint(child_pos) ^ asuint(pos); - uint32_t diff = (diffs.x | diffs.y | diffs.z); - - int32_t common_depth = (1 + (22 - firstbithigh(diff)) / 2) * 2; - if(common_depth <= 0) - { - break; - } - - scale_exp = 23 - common_depth; - current_node_index = stack[stack_index * 5 + 10 - scale_exp / 2]; - //current_node_index = node_stack[10 - scale_exp / 2]; - } - - - var hit: HitInformation; - hit.hit = false; - return hit; -} - -struct FragmentOutput -{ - float depth : SV_Depth; - float4 color : SV_Target<0>; -} - -/* -//[earlydepthstencil] -[shader("fragment")] -FragmentOutput fragment(VertexOutput vertex_out) -{ - let ray_direction = normalize(vertex_out.world_position - vertex_out.cam_position); - let intersection_t = box_intersect(vertex_out.cam_position, ray_direction, vertex_out.chunk_position, vertex_out.chunk_position + float3(1.)); - let local_ray_origin = max(intersection_t.x, 0.) * ray_direction + vertex_out.cam_position - vertex_out.chunk_position; - // Figure out intersection - let hit = ray_march(ray_direction, local_ray_origin, vertex_out.structure_id, max(0., intersection_t.x)); - let world_hit_pos = hit.hit_pos + vertex_out.chunk_position; - let clip = mul(constants.view_proj, float4(world_hit_pos, 1.)); - let depth = clip.z / clip.w; - - var frag_out : FragmentOutput; - frag_out.depth = depth; - frag_out.color = hit.color; - - return frag_out; -} -*/ - bool3 min_mask(float3 val) { let min_val = min(val.x, min(val.y, val.z)); return val == min_val; } -[[vk::binding(0, 1)]] +[[vk::binding(0, 1)]] [[format("rgba32f")]] -WTexture2D output_texture; +WTexture2D gbuffer_position; + +[[vk::binding(1, 1)]] +[[format("rgba32f")]] +WTexture2D gbuffer_albedo; + +[[vk::binding(2, 1)]] +[[format("rgba32f")]] +WTexture2D gbuffer_normal; float3 get_ray_direction(uint32_t2 pixel_loc) { @@ -385,75 +134,59 @@ float3 get_ray_direction(uint32_t2 pixel_loc) [shader("compute")] [numthreads(16, 16, 1)] -void ray_march_compute(uint32_t3 location : SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID) +void gi_march(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID) { - if(location.x >= constants.width || location.y >= constants.height) + if (location.x >= constants.width || location.y >= constants.height) + { + return; + } +} + +[shader("compute")] +[numthreads(16, 16, 1)] +void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID) +{ + if (location.x >= constants.width || location.y >= constants.height) { return; } let stack_index = local_location.x + local_location.y * 16; + + var voxel_cache : VoxelCache; + voxel_cache.structure_pool = structure_pool; + voxel_cache.attributes_pool = attributes_pool; + voxel_cache.location_pool = location_pool; + voxel_cache.request_buffer = request_buffer; + voxel_cache.usage_buffer = usage_buffer; + voxel_cache.structure_table_pointer = structure_table_pointer; + voxel_cache.structure_table_request_buffer = structure_table_request_buffer; + let ray_direction = get_ray_direction(location.xy); - var inter = box_intersect(constants.cam_pos, ray_direction, float3(0.), float3(constants.chunk_width, constants.chunk_alt, constants.chunk_height)); - // Clear if out of box - if(inter.y <= inter.x || inter.y <= 0.) + var ray_cast_context : RayCastContext; + ray_cast_context.ray_direction = ray_direction; + ray_cast_context.ray_origin = constants.cam_pos; + ray_cast_context.bounds = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width); + ray_cast_context.frame_timestamp = constants.frame_timestamp; + ray_cast_context.cache_report = true; + + let hit = ray_cast(voxel_cache, ray_cast_context, stack_index); + + if (hit.hit) { - output_texture.Store(location.xy, float4(0.)); - return; + // Gather + let hit_pos = hit.hit_pos; + let hit_normal = fetch_normal(hit.node_index, hit.child_index); + let hit_albedo = fetch_color(hit.node_index, hit.child_index).float_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); } - inter.x = max(0., inter.x); - // float3 position = constants.cam_pos + ray_direction * inter.x; - // int32_t3 current_voxel = clamp( - // int32_t3(floor(position)), - // int32_t3(0), - // int32_t3(constants.chunk_width - 1, constants.chunk_alt - 1, constants.chunk_height - 1) - // ); - // let chunk_index = current_voxel.y + current_voxel.z * constants.chunk_alt + current_voxel.x * constants.chunk_alt * constants.chunk_height; - // let hit = ray_march(ray_direction, position - float3(current_voxel), chunk_index, length(position - constants.cam_pos), stack_index); - // if(hit.hit) - // { - // output_texture.Store(location.xy, float4(hit.color)); - // } - - - let start_position = inter.x * ray_direction + constants.cam_pos; - // FVT - int32_t3 current_voxel = clamp( - int32_t3(floor(start_position)), - int32_t3(0), - int32_t3(constants.chunk_width - 1, constants.chunk_alt - 1, constants.chunk_height - 1) - ); - //int32_t3 offset = int32_t3(sign(ray_direction)); - //float3 delta = abs(1. / ray_direction); - float3 t = select(ray_direction > 0., current_voxel + int32_t3(1) - start_position, start_position - current_voxel) / abs(ray_direction); - t += inter.x; - - [loop] - while(true) + else { - { - let off = t - abs(1. / ray_direction); - let t_adv = max(max(off.x, max(off.y, off.z)), 0.); - let chunk_index = current_voxel.y + current_voxel.z * constants.chunk_alt + current_voxel.x * constants.chunk_alt * constants.chunk_height; - let position = constants.cam_pos + ray_direction * t_adv; - let hit = ray_march(ray_direction, position - float3(current_voxel), chunk_index, t_adv, stack_index); - if(hit.hit) - { - output_texture.Store(location.xy, hit.color); - return; - } - } - - let min_mask = min_mask(t); - t += select(min_mask, abs(1. / ray_direction), float3(0.)); - current_voxel += select(min_mask, int32_t3(sign(ray_direction)), int32_t3(0)); - - if(any(current_voxel < 0) || any(current_voxel >= int32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_height))) - { - output_texture.Store(location.xy, float4(0.)); - return; - } + gbuffer_albedo.Store(location.xy, float4(0.)); } } @@ -469,3 +202,4 @@ float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 let near_t = max(near_ts.x, max(near_ts.y, near_ts.z)); return float2(near_t, far_t); } + diff --git a/shaders/voxel.spv b/shaders/voxel.spv index 3da5f45..b2706f1 100644 Binary files a/shaders/voxel.spv and b/shaders/voxel.spv differ diff --git a/shaders/voxel.temp.wgsl b/shaders/voxel.temp.wgsl deleted file mode 100644 index e7cf900..0000000 --- a/shaders/voxel.temp.wgsl +++ /dev/null @@ -1,399 +0,0 @@ -struct VertexOutput -{ - @builtin(position) postion: vec4, - @location(0) @interpolate(flat) chunk_index: u32, - @location(1) color: vec4, - @location(2) cam_pos: vec3, - @location(3) world_pos: vec3, - @location(4) @interpolate(flat) structure_id: u32, - @location(5) chunk_position: vec3 -} - -struct ChunkImmediate -{ - view_proj: mat4x4, - cam_pos: vec3, - frame_timestamp: u32, -} - -var constants: ChunkImmediate; -//var constants: ChunkInfo; - -struct CacheChunkObject -{ - transform: mat4x4, - color: vec4, - id: u32, - pointer: u32 -} - - -struct StructurePoolElement -{ - pointers: array -} - -struct RequestBufferElement -{ - requests: array, 64> -} - -struct ColorPoolElement -{ - colors: array -} - -struct LocationPoolElement -{ - structure_id: u32, - structure_locator: u32 -} - -struct SortedRequestsElement -{ - node: u32, - child: u32 -} - -fn unpack_color(color: u32) -> vec4 -{ - return vec4( - f32(color & 0xFF) / 255., - f32((color >> 8) & 0xFF) / 255., - f32((color >> 16) & 0xFF) / 255., - f32((color >> 24) & 0xFF) / 255. - ); -} - -@group(0) @binding(0) var structure_pool: array; -@group(0) @binding(1) var color_pool: array; -@group(0) @binding(2) var location_pool: array; -@group(0) @binding(3) var request_buffer: array; -@group(0) @binding(4) var usage_buffer: array>; -@group(0) @binding(5) var structure_table_pointer: array; -@group(0) @binding(6) var structure_table_request_buffer: array>; - -struct FragmentOutput { - @location(0) color: vec4, - @builtin(frag_depth) depth: f32, // Equivalent to gl_FragDepth -} - -@vertex -fn chunk(@builtin(vertex_index) index: u32, @location(0) position: vec3, @location(1) id: u32) -> @builtin(position) vec4 -{ - let cube_vertices = array, 8>( - vec3(0., 0., 0.), - vec3(0., 0., 1.), - vec3(1., 0., 1.), - vec3(1., 0., 0.), - - vec3(0., 1., 0.), - vec3(0., 1., 1.), - vec3(1., 1., 1.), - vec3(1., 1., 0.), - ); - - let cube_faces = array( - // Bottom face - 1, 0, 2, 3, - - // Top face - 4, 5, 7, 6, - - // Side faces - 0, 1, 4, 5, - 1, 2, 5, 6, - 2, 3, 6, 7, - 3, 0, 7, 4, - ); - - let quad_index = index / (3 * 2); - let triangle_index = index % (3 * 2); - let triangle_map = array( - 0, 1, 2, 1, 3, 2 - ); - - - let vertex = cube_vertices[cube_faces[quad_index * 4 + triangle_map[triangle_index]]]; - let output_vertex = constants.view_proj * vec4(vertex + position, 1.0f); - - return output_vertex; -} - - -struct StructureElement -{ - children: array -} - -struct ColorElement -{ - children: array, 64> -} - -struct LocationElement -{ - children: array, 64> -} - -struct RequestElement -{ - children: array, 64> -} - -fn box_inter(pos: vec3, ray_dir: vec3, box_min: vec3, box_max: vec3) -> vec2 -{ - let box_min_t = (box_min - pos) / ray_dir; - let box_max_t = (box_max - pos) / ray_dir; - - let near_ts = min(box_min_t, box_max_t); - let far_ts = max(box_min_t, box_max_t); - - let far_t = min(min(far_ts.x, far_ts.y), far_ts.z); - let near_t = max(max(near_ts.x, near_ts.y), near_ts.z); - - return vec2(near_t, far_t); -} - -fn sdf(voxel: vec3) -> bool -{ - let len = length(vec3(voxel) - vec3(128)) / 128.; - return len <= 1.; -} - -fn min_vec(x: vec3) -> f32 -{ - return min(x.x, min(x.y, x.z)); -} - -fn min_mask(x: vec3) -> vec3 -{ - let min = min(x.x, min(x.y, x.z)); - - return vec3(min == x.x, min == x.y, min == x.z); -} - -fn node_subdivided(node: u32) -> bool -{ - return ((node >> 31) & 1) != 0; -} - -fn node_pointer_valid(node: u32) -> bool -{ - return ((node >> 30) & 1) != 0; -} - -fn node_pointer(node: u32) -> u32 -{ - return node & 0x3FFFFFFF; -} - -fn voxel_from_wall(position: vec3, ray_dir: vec3) -> vec3 -{ - let integers = round(position); - let wall_mask = min_mask(abs(position - vec3(integers))); - let offsets = select(vec3(-0.5), vec3(0.5), ray_dir > vec3(0.)); - return vec3(floor(position + select(vec3(0.), offsets, wall_mask))); -} - -struct HitResult -{ - color: vec4, - hit_pos: vec3 -} - -fn new_traverse(ray_dir: vec3, ray_origin: vec3, root_id: u32, dist_offset: f32) -> HitResult -{ - let max_depth = 5; - let dist_offset_voxel = dist_offset * f32(1 << u32(max_depth * 2)); - let fovy_deg = 100. / 1920.; - let fovy_rad = (fovy_deg * 3.14) / 180.; - let cone_factor = tan(fovy_rad / 2.) * 2.; - - let st_pointer = structure_table_pointer[root_id]; - - - if (!node_subdivided(st_pointer)) - { - discard; - var result: HitResult; - result.color = vec4(0., 1., 0., 1.); - result.hit_pos = ray_origin; - return result; - } - if(!node_pointer_valid(st_pointer)) - { - // Node is subdivided, but not valid - // Send request on structure table - atomicAdd(&structure_table_request_buffer[root_id], 1); - - discard; - var result: HitResult; - result.color = vec4(0., 1., 0., 1.); - result.hit_pos = ray_origin; - return result; - } - //var current_node = node_pointer(st_pointer); - - var dfs_stack = array(node_pointer(st_pointer), 0, 0, 0, 0, 0); - var current_depth = 0; - var current_node = dfs_stack[current_depth]; - - usage_buffer[current_node] = constants.frame_timestamp; - - // Start location - //let voxel_dir = select(vec3(-1), vec3(1), ray_dir >= vec3(0.)); - var node_shift = (max_depth - current_depth) * 2; - - var child_size = 1 << u32(node_shift - 2); - var node_size = 1 << u32(node_shift); - - var pos_origin = clamp(ray_origin * f32(1 << u32(max_depth * 2)), vec3(0.), vec3(f32(node_size) - 1.)); - var voxel = vec3(pos_origin); - var far_t = 0.; - var inv_ray_dir = 1. / ray_dir; - var ray_positive = ray_dir > vec3(0.); - var step_dir = select(vec3(-1), vec3(1), ray_positive); - - for(var iter = 0; iter < 400; iter ++) - { - // Shift into voxel position - node_shift = (max_depth - current_depth) * 2; - child_size = 1 << u32(node_shift - 2); - - // Compute child position position from voxel position - var child_pos = (voxel >> vec3(u32(node_shift - 2))) & vec3(3); - // Compute child index in pointers - var child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4; - // Candidate child pointer - var pointer = structure_pool[current_node].pointers[child_index]; - - // Descent loop - let min_child_size = (length(vec3(voxel) - pos_origin) + dist_offset_voxel) * cone_factor; - while(node_subdivided(pointer) && node_pointer_valid(pointer) && - f32(child_size / 4) >= min_child_size - ) - { - - // Descend - current_depth += 1; - - // Try to descend again - node_shift = (max_depth - current_depth) * 2; - child_size = 1 << u32(node_shift - 2); - child_pos = (voxel >> vec3(u32(node_shift - 2))) & vec3(3); - current_node = node_pointer(pointer); - dfs_stack[current_depth] = current_node; - child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4; - - pointer = structure_pool[current_node].pointers[child_index]; - - // Record usage in usage buffer - usage_buffer[current_node] = constants.frame_timestamp; - } - - // If we could not descencd, request the child - if(node_subdivided(pointer) && !node_pointer_valid(pointer) && - f32(child_size / 4) >= min_child_size) - { - // Record request - atomicAdd(&request_buffer[dfs_stack[current_depth]].requests[child_index], 1); - } - - // Check color - let color = color_pool[current_node].colors[child_index]; - if(((color >> 24) & 0xFF) != 0) - { - var result: HitResult; - result.color = unpack_color(color); - result.hit_pos = (far_t / f32(1 << u32(max_depth * 2))) * ray_dir + ray_origin; - return result; - } - - // Advance - child_pos = voxel & vec3(i32(0xFFFFFFFF << u32(node_shift - 2))); - let far_wall = child_pos + select(vec3(0), vec3(child_size), ray_positive); - let far_wall_inter = (vec3(far_wall) - pos_origin) * inv_ray_dir; - far_t = min(min(far_wall_inter.x, far_wall_inter.y), far_wall_inter.z); - - // Perform dda step on the children scale - let next_child = select(child_pos, child_pos + step_dir * vec3(child_size), vec3(far_t) == far_wall_inter); - - let previous_voxel = voxel; - voxel = clamp(vec3(pos_origin + far_t * ray_dir), next_child, next_child + vec3(child_size) - vec3(1)); - - if any(voxel < vec3(0)) || any(voxel >= vec3(1 << u32((max_depth * 2)))) - { - discard; - } - - // We touched a voxel as if we explored blocks sized by the child size of the current node. - // But we might have exited the current node. - - // If this is the case we have to walk back up the tree - // And then back down to the next node over - - // As such we find the lowest ancestor that can contain both the privous voxel (in node) and the new voxel (out of node) - let bit_diffs = voxel ^ previous_voxel; - let bit_diffs_lowest = bit_diffs.x | bit_diffs.y | bit_diffs.z; - - let common_depth = ((countLeadingZeros(bit_diffs_lowest) - i32(32 - max_depth * 2)) / 2); - - current_depth = common_depth; - current_node = dfs_stack[current_depth]; - } - - // Iter max color - var result: HitResult; - result.color = vec4(1., 0., 1., 1.); - result.hit_pos = (far_t / f32(1 << u32(max_depth * 2))) * ray_dir + ray_origin; - return result; -} - -@fragment -fn fragment() -> @location(0) vec4 -{ - return vec4(1., 0., 0., 1.) ; -} - -@early_depth_test(less_equal) -@fragment -fn _fragment(in: VertexOutput) -> FragmentOutput -{ - //frag_out.color = vec4(2 * 0.01 / (100. + 0.01 - depth * (100. - 0.01))); - let ray_dir = normalize(in.world_pos - in.cam_pos); - let interp = box_inter(in.cam_pos - in.chunk_position, ray_dir, vec3(0.), vec3(1)); - let ray_origin = (in.cam_pos - in.chunk_position) + ray_dir * (max(0., interp.x)); - - - let result = new_traverse(ray_dir, ray_origin, in.structure_id, length(in.cam_pos - (ray_origin + in.chunk_position))); - let clip_pos = constants.view_proj * vec4(result.hit_pos + in.chunk_position, 1.); - let depth = clip_pos.z / clip_pos.w; - var frag_out: FragmentOutput; - //frag_out.color = result.color; - frag_out.color = result.color; - frag_out.depth = depth; - return frag_out; - - //return vec4(ray_origin, 1.); - //return frag_out; - //return vec4(interp.y / 10.); -} - -/* -@fragment -fn fragment(in: VertexOutput) -> @location(0) vec4 -{ - let st = structure_table_pointer[0]; - let subdivided = ((st >> 31) & 1) != 0; - let pointer_valid = ((st >> 30) & 1) != 0; - // Request stuff - atomicAdd(&structure_table_request_buffer[0], 1); - if(subdivided && !pointer_valid) - { - return vec4(0., 1., 0., 1.); - } - return vec4(1., 0., 0., 1.); -} -*/ - diff --git a/shaders/voxel.wgsl b/shaders/voxel.wgsl deleted file mode 100644 index 78d3109..0000000 --- a/shaders/voxel.wgsl +++ /dev/null @@ -1,398 +0,0 @@ -struct VertexOutput -{ - @builtin(position) postion: vec4, - @location(0) @interpolate(flat) chunk_index: u32, - @location(1) color: vec4, - @location(2) cam_pos: vec3, - @location(3) world_pos: vec3, - @location(4) @interpolate(flat) structure_id: u32, - @location(5) chunk_position: vec3 -} - -struct ChunkImmediate -{ - view_proj: mat4x4, - cam_pos: vec3, - frame_timestamp: u32, -} - -var constants: ChunkImmediate; -//var constants: ChunkInfo; - -struct CacheChunkObject -{ - transform: mat4x4, - color: vec4, - id: u32, - pointer: u32 -} - - -struct StructurePoolElement -{ - pointers: array -} - -struct RequestBufferElement -{ - requests: array, 64> -} - -struct ColorPoolElement -{ - colors: array -} - -struct LocationPoolElement -{ - structure_id: u32, - structure_locator: u32 -} - -struct SortedRequestsElement -{ - node: u32, - child: u32 -} - -fn unpack_color(color: u32) -> vec4 -{ - return vec4( - f32(color & 0xFF) / 255., - f32((color >> 8) & 0xFF) / 255., - f32((color >> 16) & 0xFF) / 255., - f32((color >> 24) & 0xFF) / 255. - ); -} - -@group(0) @binding(0) var structure_pool: array; -@group(0) @binding(1) var color_pool: array; -@group(0) @binding(2) var location_pool: array; -@group(0) @binding(3) var request_buffer: array; -@group(0) @binding(4) var usage_buffer: array>; -@group(0) @binding(5) var structure_table_pointer: array; -@group(0) @binding(6) var structure_table_request_buffer: array>; - -struct FragmentOutput { - @location(0) color: vec4, - @builtin(frag_depth) depth: f32, // Equivalent to gl_FragDepth -} - -@vertex -fn chunk(@builtin(vertex_index) index: u32, @location(0) position: vec3, @location(1) id: u32) -> VertexOutput -{ - let cube_vertices = array, 8>( - vec3(0., 0., 0.), - vec3(0., 0., 1.), - vec3(1., 0., 1.), - vec3(1., 0., 0.), - - vec3(0., 1., 0.), - vec3(0., 1., 1.), - vec3(1., 1., 1.), - vec3(1., 1., 0.), - ); - - let cube_faces = array( - // Bottom face - 1, 0, 2, 3, - - // Top face - 4, 5, 7, 6, - - // Side faces - 0, 1, 4, 5, - 1, 2, 5, 6, - 2, 3, 6, 7, - 3, 0, 7, 4, - ); - - let quad_index = index / (3 * 2); - let triangle_index = index % (3 * 2); - let triangle_map = array( - 0, 1, 2, 1, 3, 2 - ); - - - let vertex = cube_vertices[cube_faces[quad_index * 4 + triangle_map[triangle_index]]]; - let output_vertex = constants.view_proj * vec4(vertex + position, 1.0f); - - var output: VertexOutput; - output.postion = output_vertex; - output.color = vec4(1.); - output.chunk_index = 0; - output.cam_pos = constants.cam_pos; - output.world_pos = vertex + position; - output.structure_id = id; - output.chunk_position = position; - - //let output = vec4(vertex, 1.0f); - return output; -} - - -struct StructureElement -{ - children: array -} - -struct ColorElement -{ - children: array, 64> -} - -struct LocationElement -{ - children: array, 64> -} - -struct RequestElement -{ - children: array, 64> -} - -fn box_inter(pos: vec3, ray_dir: vec3, box_min: vec3, box_max: vec3) -> vec2 -{ - let box_min_t = (box_min - pos) / ray_dir; - let box_max_t = (box_max - pos) / ray_dir; - - let near_ts = min(box_min_t, box_max_t); - let far_ts = max(box_min_t, box_max_t); - - let far_t = min(min(far_ts.x, far_ts.y), far_ts.z); - let near_t = max(max(near_ts.x, near_ts.y), near_ts.z); - - return vec2(near_t, far_t); -} - -fn sdf(voxel: vec3) -> bool -{ - let len = length(vec3(voxel) - vec3(128)) / 128.; - return len <= 1.; -} - -fn min_vec(x: vec3) -> f32 -{ - return min(x.x, min(x.y, x.z)); -} - -fn min_mask(x: vec3) -> vec3 -{ - let min = min(x.x, min(x.y, x.z)); - - return vec3(min == x.x, min == x.y, min == x.z); -} - -fn node_subdivided(node: u32) -> bool -{ - return ((node >> 31) & 1) != 0; -} - -fn node_pointer_valid(node: u32) -> bool -{ - return ((node >> 30) & 1) != 0; -} - -fn node_pointer(node: u32) -> u32 -{ - return node & 0x3FFFFFFF; -} - -fn voxel_from_wall(position: vec3, ray_dir: vec3) -> vec3 -{ - let integers = round(position); - let wall_mask = min_mask(abs(position - vec3(integers))); - let offsets = select(vec3(-0.5), vec3(0.5), ray_dir > vec3(0.)); - return vec3(floor(position + select(vec3(0.), offsets, wall_mask))); -} - -struct HitResult -{ - color: vec4, - hit_pos: vec3 -} - -fn new_traverse(ray_dir: vec3, ray_origin: vec3, root_id: u32, dist_offset: f32) -> HitResult -{ - let max_depth = 5; - let dist_offset_voxel = dist_offset * f32(1 << u32(max_depth * 2)); - let fovy_deg = 100. / 1920.; - let fovy_rad = (fovy_deg * 3.14) / 180.; - let cone_factor = tan(fovy_rad / 2.) * 2.; - - let st_pointer = structure_table_pointer[root_id]; - - - if (!node_subdivided(st_pointer)) - { - discard; - var result: HitResult; - result.color = vec4(0., 1., 0., 1.); - result.hit_pos = ray_origin; - return result; - } - if(!node_pointer_valid(st_pointer)) - { - // Node is subdivided, but not valid - // Send request on structure table - atomicAdd(&structure_table_request_buffer[root_id], 1); - - discard; - var result: HitResult; - result.color = vec4(0., 1., 0., 1.); - result.hit_pos = ray_origin; - return result; - } - //var current_node = node_pointer(st_pointer); - - var dfs_stack = array(node_pointer(st_pointer), 0, 0, 0, 0, 0); - var current_depth = 0; - var current_node = dfs_stack[current_depth]; - - usage_buffer[current_node] = constants.frame_timestamp; - - // Start location - //let voxel_dir = select(vec3(-1), vec3(1), ray_dir >= vec3(0.)); - var node_shift = (max_depth - current_depth) * 2; - - var child_size = 1 << u32(node_shift - 2); - var node_size = 1 << u32(node_shift); - - var pos_origin = clamp(ray_origin * f32(1 << u32(max_depth * 2)), vec3(0.), vec3(f32(node_size) - 1.)); - var voxel = vec3(pos_origin); - var far_t = 0.; - var inv_ray_dir = 1. / ray_dir; - var ray_positive = ray_dir > vec3(0.); - var step_dir = select(vec3(-1), vec3(1), ray_positive); - - for(var iter = 0; iter < 400; iter ++) - { - // Compute child position - node_shift = (max_depth - current_depth) * 2; - child_size = 1 << u32(node_shift - 2); - - var child_pos = (voxel >> vec3(u32(node_shift - 2))) & vec3(3); - var child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4; - var pointer = structure_pool[current_node].pointers[child_index]; - - let min_child_size = (length(vec3(voxel) - pos_origin) + dist_offset_voxel) * cone_factor; - while(node_subdivided(pointer) && - f32(child_size / 4) >= min_child_size - ) - { - if(!node_pointer_valid(pointer) && node_subdivided(pointer)) - { - // Record request - atomicAdd(&request_buffer[dfs_stack[current_depth]].requests[child_index], 1); - break; - } - - // Descend - current_depth += 1; - - node_shift = (max_depth - current_depth) * 2; - child_size = 1 << u32(node_shift - 2); - child_pos = (voxel >> vec3(u32(node_shift - 2))) & vec3(3); - current_node = node_pointer(pointer); - dfs_stack[current_depth] = current_node; - child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4; - - pointer = structure_pool[current_node].pointers[child_index]; - - // Record usage - usage_buffer[current_node] = constants.frame_timestamp; - } - - - // Check color - let color = color_pool[current_node].colors[child_index]; - if(((color >> 24) & 0xFF) != 0) - { - var result: HitResult; - result.color = unpack_color(color); - result.hit_pos = (far_t / f32(1 << u32(max_depth * 2))) * ray_dir + ray_origin; - return result; - } - - // Advance - child_pos = voxel & vec3(i32(0xFFFFFFFF << u32(node_shift - 2))); - let far_wall = child_pos + select(vec3(0), vec3(child_size), ray_positive); - let far_wall_inter = (vec3(far_wall) - pos_origin) * inv_ray_dir; - far_t = min(min(far_wall_inter.x, far_wall_inter.y), far_wall_inter.z); - - // Perform dda step on the children scale - //let next_child = select(child_pos, child_pos + select(vec3(-1), vec3(1), ray_dir > vec3(0.)) * vec3(child_size), vec3(far_t) == far_wall_inter); - let next_child = select(child_pos, child_pos + step_dir * vec3(child_size), vec3(far_t) == far_wall_inter); - - let previous_voxel = voxel; - voxel = clamp(vec3(pos_origin + far_t * ray_dir), next_child, next_child + vec3(child_size) - vec3(1)); - - if any(voxel < vec3(0)) || any(voxel >= vec3(1 << u32((max_depth * 2)))) - { - discard; - } - - // We touched a voxel as if we explored blocks sized by the child size of the current node. - // But we might have exited the current node. - - // If this is the case we have to walk back up the tree - // And then back down to the next node over - - // As such we find the lowest ancestor that can contain both the privous voxel (in node) and the new voxel (out of node) - let bit_diffs = voxel ^ previous_voxel; - let bit_diffs_lowest = bit_diffs.x | bit_diffs.y | bit_diffs.z; - - let common_depth = ((countLeadingZeros(bit_diffs_lowest) - i32(32 - max_depth * 2)) / 2); - - current_depth = common_depth; - current_node = dfs_stack[current_depth]; - } - - // Iter max color - var result: HitResult; - result.color = vec4(1., 0., 1., 1.); - result.hit_pos = (far_t / f32(1 << u32(max_depth * 2))) * ray_dir + ray_origin; - return result; -} - -@early_depth_test(less_equal) -@fragment -fn fragment(in: VertexOutput) -> FragmentOutput -{ - //frag_out.color = vec4(2 * 0.01 / (100. + 0.01 - depth * (100. - 0.01))); - let ray_dir = normalize(in.world_pos - in.cam_pos); - let interp = box_inter(in.cam_pos - in.chunk_position, ray_dir, vec3(0.), vec3(1)); - let ray_origin = (in.cam_pos - in.chunk_position) + ray_dir * (max(0., interp.x)); - - - let result = new_traverse(ray_dir, ray_origin, in.structure_id, length(in.cam_pos - (ray_origin + in.chunk_position))); - let clip_pos = constants.view_proj * vec4(result.hit_pos + in.chunk_position, 1.); - let depth = clip_pos.z / clip_pos.w; - var frag_out: FragmentOutput; - //frag_out.color = result.color; - frag_out.color = result.color; - frag_out.depth = depth; - return frag_out; - - //return vec4(ray_origin, 1.); - //return frag_out; - //return vec4(interp.y / 10.); -} - -/* -@fragment -fn fragment(in: VertexOutput) -> @location(0) vec4 -{ - let st = structure_table_pointer[0]; - let subdivided = ((st >> 31) & 1) != 0; - let pointer_valid = ((st >> 30) & 1) != 0; - // Request stuff - atomicAdd(&structure_table_request_buffer[0], 1); - if(subdivided && !pointer_valid) - { - return vec4(0., 1., 0., 1.); - } - return vec4(1., 0., 0., 1.); -} -*/ - diff --git a/shaders/wesl.toml b/shaders/wesl.toml deleted file mode 100644 index 59c4814..0000000 --- a/shaders/wesl.toml +++ /dev/null @@ -1 +0,0 @@ -root = "." diff --git a/src/egui_renderer.rs b/src/egui_renderer.rs index 68b7535..2c28777 100644 --- a/src/egui_renderer.rs +++ b/src/egui_renderer.rs @@ -15,7 +15,7 @@ use winit::window::Window; pub struct EguiRenderer { state: State, - renderer: Renderer, + pub renderer: Renderer, frame_started: bool, } diff --git a/src/main.rs b/src/main.rs index 7d56c7a..d76fc33 100644 --- a/src/main.rs +++ b/src/main.rs @@ -59,6 +59,7 @@ use winit::window::WindowId; use crate::camera::Camera; use crate::egui_renderer::EguiRenderer; use crate::producers::ChunkedProducer; +use crate::producers::SdfGenerator; use crate::producers::SineGenerator; use crate::producers::TerrainGenerator; use crate::sparse_tree::NTreeNodeLocator; @@ -82,6 +83,14 @@ mod sparse_tree; mod voxel_cache; // +enum DisplayTexture +{ + Target, + Normal, + Pos, + Albedo, +} + struct State { instance: wgpu::Instance, @@ -92,16 +101,23 @@ struct State surface: wgpu::Surface<'static>, depth_buffer: (wgpu::Texture, wgpu::TextureView), target_texture: (wgpu::Texture, wgpu::TextureView), + position_gbuffer: (wgpu::Texture, wgpu::TextureView), + normal_gbuffer: (wgpu::Texture, wgpu::TextureView), + albedo_gbuffer: (wgpu::Texture, wgpu::TextureView), surface_format: wgpu::TextureFormat, target_blitter: wgpu::util::TextureBlitter, egui_renderer: EguiRenderer, + display: DisplayTexture, //pipeline: RenderPipeline, pipeline: ComputePipeline, + gi_pipeline: ComputePipeline, surface_bg_layout: BindGroupLayout, + gi_bg_layout: BindGroupLayout, voxel_cache: Arc>>, cache_interface: Arc>, - terrain_generator: Arc>, + terrain_generator: Arc>, + //terrain_generator: Arc>, chunk_pos_map: Arc>, instance_buffer: Buffer, instance_count: usize, @@ -170,6 +186,7 @@ impl State | Features::TIMESTAMP_QUERY_INSIDE_ENCODERS | Features::STORAGE_RESOURCE_BINDING_ARRAY | Features::BUFFER_BINDING_ARRAY + | Features::PASSTHROUGH_SHADERS | Features::SHADER_INT64, required_limits: wgpu::Limits { max_immediate_size: 112, @@ -192,12 +209,16 @@ impl State let egui_renderer = EguiRenderer::new(&device, surface_format, &window); - let attributes = vec![VoxelAttribute { word_count: 1 }]; + let attributes = vec![ + VoxelAttribute { word_count: 1 }, + VoxelAttribute { word_count: 3 }, + ]; let mut voxel_cache = VoxelCache::<4>::new(100_000, device.clone(), queue.clone(), attributes.clone()); let cache_interface = CacheProducerInterface::new(1024, &device, attributes.clone()); - let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg"); + //let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg"); + let terrain_generator = SdfGenerator::<4>::new(5); // let terrain_generator = TerrainGenerator::<4>::new( // 5, // "./pointe_percee/height.tif", @@ -210,11 +231,12 @@ impl State // 0.2, // "/home/albin/Documents/vxls_maps/lapiz/ortho.jpg", // ); + // let mut chunk_pos_map = HashMap::new(); - let chunk_instances = (0..terrain_generator.chunk_width) - .cartesian_product(0..terrain_generator.chunk_height) - .cartesian_product(0..terrain_generator.chunk_alt) + let chunk_instances = (0..20) + .cartesian_product(0..20) + .cartesian_product(0..20) .map(|((x, z), y)| { let chunk_id = voxel_cache.structure_table.allocate_structure(true); //dbg!(chunk_id); @@ -258,38 +280,159 @@ impl State // }; //let shader_module = device.create_shader_module(include_wgsl!("../shaders/voxel.wgsl")); + // let shader_module = unsafe { + // device.create_shader_module_trusted( + // wgpu::ShaderModuleDescriptor { + // label: Some("../shaders/voxel.spv"), + // source: wgpu::ShaderSource::SpirV(wgpu::__macro_helpers::Cow::Borrowed( + // wgpu::include_spirv_source!("../shaders/voxel.spv"), + // )), + // }, + // wgpu::ShaderRuntimeChecks { + // bounds_checks: false, + // force_loop_bounding: false, + // ray_query_initialization_tracking: false, + // task_shader_dispatch_tracking: false, + // mesh_shader_primitive_indices_clamp: false, + // int_div_checks: false, + // }, + // ) + // }; + let shader_module = unsafe { - device.create_shader_module_trusted( - wgpu::ShaderModuleDescriptor { - label: Some("../shaders/voxel.spv"), - source: wgpu::ShaderSource::SpirV(wgpu::__macro_helpers::Cow::Borrowed( - wgpu::include_spirv_source!("../shaders/voxel.spv"), - )), - }, - wgpu::ShaderRuntimeChecks { - bounds_checks: false, - force_loop_bounding: false, - ray_query_initialization_tracking: false, - task_shader_dispatch_tracking: false, - mesh_shader_primitive_indices_clamp: false, - int_div_checks: false, - }, - ) + device.create_shader_module_passthrough({ + wgpu::ShaderModuleDescriptorPassthrough { + label: wgpu::__macro_helpers::Some("../shaders/voxel.spv"), + spirv: Some(std::borrow::Cow::Borrowed(wgpu::include_spirv_source!( + "../shaders/voxel.spv" + ))), + entry_points: std::borrow::Cow::Borrowed(&[ + wgpu::PassthroughShaderEntryPoint { + name: std::borrow::Cow::Borrowed("ray_march_compute"), + workgroup_size: (16, 16, 1), + }, + ]), + dxil: None, + metallib: None, + msl: None, + hlsl: None, + glsl: None, + wgsl: None, + } + }) }; - let surface_bind_group_layout = + let gi_shader_module = unsafe { + device.create_shader_module_passthrough({ + wgpu::ShaderModuleDescriptorPassthrough { + label: wgpu::__macro_helpers::Some("../shaders/gi.spv"), + spirv: Some(std::borrow::Cow::Borrowed(wgpu::include_spirv_source!( + "../shaders/gi.spv" + ))), + entry_points: std::borrow::Cow::Borrowed(&[ + wgpu::PassthroughShaderEntryPoint { + name: std::borrow::Cow::Borrowed("gi"), + workgroup_size: (16, 16, 1), + }, + ]), + dxil: None, + metallib: None, + msl: None, + hlsl: None, + glsl: None, + wgsl: None, + } + }) + }; + + let ray_march_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("surface_bg_layout"), - entries: &[wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::StorageTexture { - access: wgpu::StorageTextureAccess::WriteOnly, - format: wgpu::TextureFormat::Rgba32Float, - view_dimension: wgpu::TextureViewDimension::D2, + entries: &[ + // Pos gbuffer + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: wgpu::TextureFormat::Rgba32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, }, - count: None, - }], + // Albedo gbuffer + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: wgpu::TextureFormat::Rgba32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + // Normal gbuffer + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: wgpu::TextureFormat::Rgba32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + ], + }); + + let gi_bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("gi_bg_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: wgpu::TextureFormat::Rgba32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + // Pos gbuffer + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::ReadOnly, + format: wgpu::TextureFormat::Rgba32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + // Albedo gbuffer + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::ReadOnly, + format: wgpu::TextureFormat::Rgba32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + // Normal gbuffer + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::ReadOnly, + format: wgpu::TextureFormat::Rgba32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + ], }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -297,7 +440,7 @@ impl State bind_group_layouts: &[ Some(&voxel_cache.bind_group_layout()), - Some(&surface_bind_group_layout), + Some(&ray_march_bind_group_layout), ], immediate_size: size_of::() as u32, }); @@ -311,62 +454,24 @@ impl State cache: None, }); - /* - let chunk_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("Render pipeline"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module: &shader_module, - entry_point: Some("chunk"), - compilation_options: Default::default(), - buffers: &[Some(wgpu::VertexBufferLayout { - array_stride: (size_of::() * 3 + size_of::()) as u64, - step_mode: wgpu::VertexStepMode::Instance, - attributes: &[ - wgpu::VertexAttribute { - format: wgpu::VertexFormat::Float32x3, - offset: 0, - shader_location: 0, - }, - wgpu::VertexAttribute { - format: wgpu::VertexFormat::Uint32, - offset: (size_of::() * 3) as u64, - shader_location: 1, - }, - ], - })], - }, - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - strip_index_format: None, - front_face: wgpu::FrontFace::Ccw, - cull_mode: Some(wgpu::Face::Front), - unclipped_depth: false, - polygon_mode: wgpu::PolygonMode::Fill, - conservative: false, - }, - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth24PlusStencil8, - depth_write_enabled: Some(true), - depth_compare: Some(wgpu::CompareFunction::LessEqual), - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module: &shader_module, - entry_point: Some("fragment"), - compilation_options: wgpu::PipelineCompilationOptions::default(), - targets: &[Some(wgpu::ColorTargetState { - format: surface_format, - blend: None, - write_mask: wgpu::ColorWrites::default(), - })], - }), - multiview_mask: None, + let gi_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Gi pipeline layout"), + + bind_group_layouts: &[ + Some(&voxel_cache.bind_group_layout()), + Some(&gi_bind_group_layout), + ], + immediate_size: size_of::() as u32, + }); + + let gi_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("Compute render"), + layout: Some(&gi_pipeline_layout), + module: &gi_shader_module, + entry_point: Some("gi"), + compilation_options: wgpu::PipelineCompilationOptions::default(), cache: None, }); - */ let state = State { instance, @@ -376,13 +481,34 @@ impl State surface_format, egui_renderer, depth_buffer: Self::create_depth_buffer(&device, size.width, size.height), + position_gbuffer: Self::create_gbuffer_texture( + &device, + size.width, + size.height, + wgpu::TextureFormat::Rgba32Float, + ), + normal_gbuffer: Self::create_gbuffer_texture( + &device, + size.width, + size.height, + wgpu::TextureFormat::Rgba32Float, + ), + albedo_gbuffer: Self::create_gbuffer_texture( + &device, + size.width, + size.height, + wgpu::TextureFormat::Rgba32Float, + ), + gi_pipeline, + gi_bg_layout: gi_bind_group_layout, target_texture: Self::create_target_texture(&device, size.width, size.height), target_blitter: wgpu::util::TextureBlitterBuilder::new(&device, surface_format) .sample_type(wgpu::FilterMode::Nearest) .build(), + display: DisplayTexture::Target, queue, device, - surface_bg_layout: surface_bind_group_layout, + surface_bg_layout: ray_march_bind_group_layout, usage_vec: Arc::new(Mutex::new(vec![])), pipeline: chunk_pipeline, voxel_cache: Arc::new(Mutex::new(voxel_cache)), @@ -403,6 +529,32 @@ impl State state } + fn create_gbuffer_texture( + device: &Device, + width: u32, + height: u32, + format: wgpu::TextureFormat, + ) -> (Texture, TextureView) + { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Target texture"), + size: Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING, + view_formats: &[format.add_srgb_suffix()], + }); + + let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + (texture, texture_view) + } + fn create_target_texture(device: &Device, width: u32, height: u32) -> (Texture, TextureView) { let texture = device.create_texture(&wgpu::TextureDescriptor { @@ -420,7 +572,7 @@ impl State view_formats: &[], }); - let texture_view = texture.create_view(&wgpu::wgt::TextureViewDescriptor::default()); + let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default()); (texture, texture_view) } @@ -433,6 +585,38 @@ impl State { self.egui_renderer.handle_input(&self.window, event); self.camera.handle_input(event); + + if self + .camera + .pressed_keyset + .contains(&winit::keyboard::KeyCode::KeyT) + { + self.display = DisplayTexture::Target; + } + + if self + .camera + .pressed_keyset + .contains(&winit::keyboard::KeyCode::KeyN) + { + self.display = DisplayTexture::Normal; + } + + if self + .camera + .pressed_keyset + .contains(&winit::keyboard::KeyCode::KeyQ) + { + self.display = DisplayTexture::Albedo; + } + + if self + .camera + .pressed_keyset + .contains(&winit::keyboard::KeyCode::KeyP) + { + self.display = DisplayTexture::Pos; + } } fn handle_device_event(&mut self, event: &DeviceEvent) @@ -487,6 +671,7 @@ impl State desired_maximum_frame_latency: 2, present_mode: wgpu::PresentMode::AutoVsync, }; + println!("Surface conf"); self.surface.configure(&self.device, &surface_config); } @@ -494,13 +679,32 @@ impl State { self.size = new_size; self.camera.aspect = new_size.width as f32 / new_size.height as f32; + self.configure_surface(); // reconfigure the surface - self.configure_surface(); self.depth_buffer = Self::create_depth_buffer(&self.device, new_size.width, new_size.height); self.target_texture = Self::create_target_texture(&self.device, new_size.width, new_size.height); + + self.position_gbuffer = Self::create_gbuffer_texture( + &self.device, + self.size.width, + self.size.height, + wgpu::TextureFormat::Rgba32Float, + ); + self.normal_gbuffer = Self::create_gbuffer_texture( + &self.device, + self.size.width, + self.size.height, + wgpu::TextureFormat::Rgba32Float, + ); + self.albedo_gbuffer = Self::create_gbuffer_texture( + &self.device, + self.size.width, + self.size.height, + wgpu::TextureFormat::Rgba32Float, + ); } fn render(&mut self) @@ -551,10 +755,43 @@ impl State let surface_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("surface_bg"), layout: &self.surface_bg_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::TextureView(&self.target_texture.1), - }], + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&self.position_gbuffer.1), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&self.albedo_gbuffer.1), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(&self.normal_gbuffer.1), + }, + ], + }); + + let gi_surface_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("surface_bg"), + layout: &self.gi_bg_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&self.target_texture.1), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&self.position_gbuffer.1), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(&self.albedo_gbuffer.1), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&self.normal_gbuffer.1), + }, + ], }); // ~~ Ray-marching timestamp query setup ~~ @@ -594,9 +831,12 @@ impl State width: self.size.width, height: self.size.height, - chunk_width: self.terrain_generator.chunk_width as u32, - chunk_height: self.terrain_generator.chunk_height as u32, - chunk_alt: self.terrain_generator.chunk_alt as u32, + // chunk_width: self.terrain_generator.chunk_width as u32, + // chunk_height: self.terrain_generator.chunk_height as u32, + // chunk_alt: self.terrain_generator.chunk_alt as u32, + chunk_width: 20, + chunk_height: 20, + chunk_alt: 20, }]; renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) }); renderpass.dispatch_workgroups( @@ -604,15 +844,26 @@ impl State self.size.height.div_ceil(16), 1, ); + renderpass.set_pipeline(&self.gi_pipeline); + renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) }); + renderpass.set_bind_group(1, Some(&gi_surface_bg), &[]); + renderpass.dispatch_workgroups( + self.size.width.div_ceil(16), + self.size.height.div_ceil(16), + 1, + ); drop(renderpass); } - self.target_blitter.copy( - &self.device, - &mut encoder, - &self.target_texture.1, - &texture_view, - ); + let target_view = match self.display + { + DisplayTexture::Target => &self.target_texture.1, + DisplayTexture::Normal => &self.normal_gbuffer.1, + DisplayTexture::Pos => &self.position_gbuffer.1, + DisplayTexture::Albedo => &self.albedo_gbuffer.1, + }; + self.target_blitter + .copy(&self.device, &mut encoder, target_view, &texture_view); /* { let mut renderpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { @@ -692,18 +943,23 @@ impl State "Ray-marching time: {}", *self.rm_time.lock() / 1_000_000. )); - egui_plot::Plot::new("Plot").show(ui, |plot_ui| { - plot_ui.bar_chart(BarChart::new( - "histo", - self.usage_vec - .lock() - .iter() - .enumerate() - .map(|(i, x)| egui_plot::Bar::new(i as f64, *x as f64)) - .collect(), - )); - }); - ui.label("Hello !") + // ui.image(egui::ImageSource::Texture(egui::load::SizedTexture::new( + // position_id, + // [512., 512.], + // ))); + egui_plot::Plot::new("Plot") + .height(512.) + .show(ui, |plot_ui| { + plot_ui.bar_chart(BarChart::new( + "histo", + self.usage_vec + .lock() + .iter() + .enumerate() + .map(|(i, x)| egui_plot::Bar::new(i as f64, *x as f64)) + .collect(), + )); + }); }, ); @@ -815,6 +1071,7 @@ impl State let mut structure_nodes: Vec> = vec![]; let mut color_nodes: Vec<[ColorBytes; 64]> = vec![]; + let mut normal_nodes: Vec<[(f32, f32, f32); 64]> = vec![]; let mut location_nodes = vec![]; cache_node_requests @@ -879,6 +1136,7 @@ impl State pointers: node.structure, }, node.colors, + node.normals, location, ) }) @@ -887,7 +1145,8 @@ impl State .for_each(|data| { structure_nodes.push(data.0); color_nodes.push(std::array::from_fn(|i| data.1[i].into())); - location_nodes.push(data.2); + normal_nodes.push(data.2); + location_nodes.push(data.3); }); if structure_nodes.len() != 0 @@ -902,6 +1161,11 @@ impl State 0, unsafe { as_raw_bytes(color_nodes.as_slice()) }, ); + cloned_queue.write_buffer( + &cloned_cache_interface.attributes_buffers()[1], + 0, + unsafe { as_raw_bytes(normal_nodes.as_slice()) }, + ); cloned_queue.write_buffer( cloned_cache_interface.location_nodes_buffer(), 0, diff --git a/src/producers.rs b/src/producers.rs index 1ebf967..03e866a 100644 --- a/src/producers.rs +++ b/src/producers.rs @@ -1,8 +1,16 @@ +use std::f32::EPSILON; +use std::f32::INFINITY; use std::fs::File; use std::path::Path; use glam::Vec3; use itertools::Itertools; +use noise::Fbm; +use noise::NoiseFn; +use noise::Perlin; +use noise::Simplex; +use noise::Worley; +use rand::random; use crate::sparse_tree::Color; use crate::voxel_cache::data::ExplicitNTreeNode; @@ -53,6 +61,7 @@ where let mut children = vec![]; let mut children_color = vec![]; + let mut children_normal = vec![]; let gnx = nx * node_size; let gny = ny * node_size; @@ -95,6 +104,7 @@ where // let alpha = 1.; children.push(StructurePointer::new(subdivided, subdivided || alpha != 0.)); + children_normal.push((0., 0., 0.)); children_color.push(Color( gvx as f32 / global_size as f32, gvy as f32 / global_size as f32, @@ -106,6 +116,7 @@ where ExplicitNTreeNode { structure: std::array::from_fn(|i| children[i]), colors: std::array::from_fn(|i| children_color[i]), + normals: std::array::from_fn(|i| children_normal[i]), } } } @@ -136,6 +147,7 @@ where let global_size = N.pow(self.chunk_power as u32); let mut children = vec![]; + let mut children_normal = vec![]; let mut children_color = vec![]; let gnx = nx * node_size; @@ -210,6 +222,7 @@ where }; } + children_normal.push((0., 0., 0.)); children_color.push(Color( (gcx + child_size / 2) as f32 / global_size as f32, (gcy + child_size / 2) as f32 / global_size as f32, @@ -221,6 +234,7 @@ where ExplicitNTreeNode { structure: std::array::from_fn(|i| children[i]), colors: std::array::from_fn(|i| children_color[i]), + normals: std::array::from_fn(|i| children_normal[i]), } } } @@ -418,6 +432,7 @@ where let mut children = vec![StructurePointer(0); N * N * N]; let mut children_color = vec![Color(0., 0., 0., 0.); N * N * N]; + let mut children_normals = vec![(0., 0., 0.); N * N * N]; let gnx = chunk_pos.0 * global_size + nx * node_size; let gny = chunk_pos.1 * global_size + ny * node_size; @@ -549,13 +564,16 @@ where } children[index] = StructurePointer::new(subdivided, subdivided || alpha != 0.); - children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha); + children_normals[index] = (0., 0., 0.); + //children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha); + children_color[index] = Color(1., 1., 1., alpha); } } ExplicitNTreeNode { structure: std::array::from_fn(|i| children[i]), colors: std::array::from_fn(|i| children_color[i]), + normals: std::array::from_fn(|i| children_normals[i]), } } } @@ -573,3 +591,149 @@ where chunk_pos: (usize, usize, usize), ) -> ExplicitNTreeNode; } + +pub struct SdfGenerator +{ + chunk_power: usize, + perlin: Perlin, +} + +impl SdfGenerator +{ + pub fn new(chunk_power: usize) -> Self + { + Self { + chunk_power, + perlin: Perlin::new(67), + } + } +} + +impl ChunkedProducer for SdfGenerator +where + [(); N * N * N]:, +{ + fn produce_node( + &self, + depth: usize, + nx: usize, + ny: usize, + nz: usize, + chunk_pos: (usize, usize, usize), + ) -> ExplicitNTreeNode + { + // let sdf = |x: f32, y: f32, z: f32| { + // Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512. + // }; + + let sdf = |x: f32, y: f32, z: f32| { + let tx = x / 512.; + let ty = y / 512.; + let tz = z / 512.; + + let val = self.perlin.get([tx as f64, ty as f64, tz as f64]); + let dist = val * 128.; + return dist as f32; + }; + + let node_size = N.pow((self.chunk_power - depth) as u32); + let child_size = node_size / N; + let global_size = N.pow(self.chunk_power as u32); + + let mut children = vec![]; + let mut children_color = vec![]; + let mut children_normals = vec![]; + + let cx = chunk_pos.0 * global_size; + let cy = chunk_pos.1 * global_size; + let cz = chunk_pos.2 * global_size; + let gnx = nx * node_size + cx; + let gny = ny * node_size + cy; + let gnz = nz * node_size + cz; + // Iterate on children of this node + for ((cz, cy), cx) in (0..N).cartesian_product(0..N).cartesian_product(0..N) + { + let gvx = gnx + cx * child_size + (child_size / 2); + let gvy = gny + cy * child_size + (child_size / 2); + let gvz = gnz + cz * child_size + (child_size / 2); + + let dist = sdf(gvx as f32, gvy as f32, gvz as f32); + let child_diagonal_length = (child_size as f32 / 2.) * f32::sqrt(3.); + + let alpha; + let subdivided; + if dist.abs() < child_diagonal_length + { + //children.push(StructurePointer::new(depth <= 3, false, 0)); + subdivided = depth < (self.chunk_power - 1); + alpha = if dist >= 0. { 0. } else { 1. }; + //alpha = 0.; + } + else if dist >= 0. + { + subdivided = false; + alpha = 0.; + } + else + { + subdivided = false; + alpha = 1.; + } + + let offset = 1. * (child_size as f32 / 2.); + + let a = sdf( + gvx as f32 + offset, + gvy as f32 - offset, + gvz as f32 - offset, + ); + let b = sdf( + gvx as f32 - offset, + gvy as f32 - offset, + gvz as f32 + offset, + ); + let c = sdf( + gvx as f32 - offset, + gvy as f32 + offset, + gvz as f32 - offset, + ); + let d = sdf( + gvx as f32 + offset, + gvy as f32 + offset, + gvz as f32 + offset, + ); + + let normal = Vec3::new(a - b - c + d, -a - b + c + d, -a + b - c + d); + + let normal = if normal.length() <= f32::EPSILON + { + Vec3::new(1., 0., 0.) + } + else + { + normal.normalize() + }; + + let color = (normal.dot(Vec3::new(0., 1., 0.)) + 1.) * 0.5; + + // let alpha = 1.; + // children_color.push(Color( + // (gvx - cx) as f32 / global_size as f32, + // (gvy - cy) as f32 / global_size as f32, + // (gvz - cz) as f32 / global_size as f32, + // alpha, + // )); + children.push(StructurePointer::new(subdivided, subdivided || alpha != 0.)); + children_color.push(Color(color + random::() * 0.02, color, color, alpha)); + children_normals.push((normal.x, normal.y, normal.z)); + //children_color.push(Color(normal.x, normal.y, normal.z, alpha)); + } + + ExplicitNTreeNode { + structure: std::array::from_fn(|i| children[i]), + colors: std::array::from_fn(|i| children_color[i]), + normals: std::array::from_fn(|i| children_normals[i]), + //normals: std::array::from_fn(|i| (1., 0., 0.)), + } + } +} diff --git a/src/voxel_cache.rs b/src/voxel_cache.rs index 367fe32..0a97a66 100644 --- a/src/voxel_cache.rs +++ b/src/voxel_cache.rs @@ -620,14 +620,20 @@ where structure_pool[overwritten_element].pointers[i] = select(u32(0), u32(1)<<31, (structure_nodes[index].pointers[i] >> 31) != 0); + var bit = u32(1); + if(i % ({children_count} / 2) != 0) + {{ + bit = u32(u32(1) << u32(i % ({children_count} / 2))); + }} + let turn_on_bit = select( u32(0), - u32(u32(1) << u32(i % ({children_count} / 2))), + bit, ((structure_nodes[index].pointers[i] >> 30) & 1) != 0 ); - if(i > {children_count} / 2) + if(i >= {children_count} / 2) {{ occupancy_high |= turn_on_bit; }}else diff --git a/src/voxel_cache/data.rs b/src/voxel_cache/data.rs index 0eda5f6..2696ded 100644 --- a/src/voxel_cache/data.rs +++ b/src/voxel_cache/data.rs @@ -101,4 +101,5 @@ where { pub structure: [StructurePointer; N * N * N], pub colors: [Color; N * N * N], + pub normals: [(f32, f32, f32); N * N * N], }