#include "math/sdf_shapes" #include "math/sdf_utils" struct BVHNode { min: vec3, left_idx: i32, max: vec3, obj_idx_or_right: i32, }; @group(0) @binding(2) var bvh_nodes: array; fn get_dist(p: vec3, obj_params: vec4) -> f32 { let obj_type = obj_params.x; if (obj_type == 1.0) { return length(p) - 1.0; } // Unit Sphere if (obj_type == 2.0) { return sdBox(p, vec3(1.0)); } // Unit Box if (obj_type == 3.0) { return sdTorus(p, vec2(1.0, 0.4)); } // Unit Torus if (obj_type == 4.0) { return sdPlane(p, vec3(0.0, 1.0, 0.0), 0.0); } if (obj_type == 5.0) { return sdBox(p, obj_params.yzw); } // MESH AABB return 100.0; } fn map_scene(p: vec3, skip_idx: u32) -> f32 { var d = 1000.0; var stack: array; var stack_ptr = 0; if (arrayLength(&bvh_nodes) > 0u) { stack[stack_ptr] = 0; stack_ptr++; } while (stack_ptr > 0) { stack_ptr--; let node_idx = stack[stack_ptr]; let node = bvh_nodes[node_idx]; if (aabb_sdf(p, node.min, node.max) < d) { if (node.left_idx < 0) { // Leaf let obj_idx = u32(node.obj_idx_or_right); if (obj_idx == skip_idx) { continue; } let obj = object_data.objects[obj_idx]; let q = (obj.inv_model * vec4(p, 1.0)).xyz; let s = min(length(obj.model[0].xyz), min(length(obj.model[1].xyz), length(obj.model[2].xyz))); // IMPORTANT: Plane (type 4.0) and Mesh (type 5.0) should not be scaled by 's'. // The 's' factor is meant for unit primitives (sphere, box, torus) that are // scaled by the model matrix. Meshes already have correct local-space extents. if (obj.params.x != 4.0 && obj.params.x != 5.0) { // Not plane, not mesh d = min(d, get_dist(q, obj.params) * s); } else { d = min(d, get_dist(q, obj.params)); } } else { // Internal if (stack_ptr < 31) { stack[stack_ptr] = node.left_idx; stack_ptr++; stack[stack_ptr] = node.obj_idx_or_right; stack_ptr++; } } } } return d; }