chunks
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
extends Node3D
|
||||
const CENTER := Vector3.ZERO
|
||||
@export var threshold: float = 0.5
|
||||
|
||||
var generate_mesh_shader = preload("res://SurfaceNetsWorld/generate_mesh.tres")
|
||||
|
||||
@export var regenerate_mesh = false
|
||||
|
||||
|
||||
@export var chunk_size = 16
|
||||
@export var show_sample_points = false
|
||||
@export var show_surface_points = false
|
||||
@export var show_surface = true
|
||||
|
||||
var mesh
|
||||
|
||||
var color = Color.RED
|
||||
|
||||
var meshinstance = MeshInstance3D.new()
|
||||
var material = ShaderMaterial.new()
|
||||
|
||||
var gpu_sdf
|
||||
|
||||
func generate_chunk(pgpu_sdf) -> void:
|
||||
gpu_sdf = pgpu_sdf
|
||||
material.shader = generate_mesh_shader
|
||||
meshinstance.material_override = material
|
||||
add_child(meshinstance)
|
||||
meshinstance.mesh = gpu_sdf.compute_mesh(chunk_size, threshold, self.position)
|
||||
|
||||
func _input(event):
|
||||
if event is InputEventKey and event.is_action_released("RegenerateMesh"):
|
||||
if regenerate_mesh:
|
||||
regenerate_mesh = false
|
||||
else:
|
||||
regenerate_mesh = true
|
||||
|
||||
func _process(_delta: float) -> void:
|
||||
if show_surface && regenerate_mesh:
|
||||
regenerate_mesh = false
|
||||
clear()
|
||||
meshinstance.mesh = gpu_sdf.compute_mesh(chunk_size, threshold, self.position)
|
||||
if show_surface_points:
|
||||
var idx = 0
|
||||
var text_id = 0
|
||||
while idx < gpu_sdf.iout_surface_points.size()/ 2:
|
||||
text_id += 1
|
||||
var value = Vector3(gpu_sdf.iout_surface_points.get(idx), gpu_sdf.iout_surface_points.get(idx+1), gpu_sdf.iout_surface_points.get(idx+2)) - Vector3(chunk_size / 2, chunk_size / 2, chunk_size / 2)
|
||||
if gpu_sdf.iout_surface_points.get(idx) != -1.0:
|
||||
DebugDraw3D.draw_square(value, 0.2, color.from_rgba8(255, 128, 128, 255))
|
||||
if text_id % 1 == 0:
|
||||
DebugDraw3D.draw_text(value, str(value), 35)
|
||||
idx += 3
|
||||
else:
|
||||
idx += 1
|
||||
|
||||
|
||||
func clear():
|
||||
mesh = ArrayMesh.new()
|
||||
|
||||
|
||||
func get_index_from_coords(coords: Vector3i):
|
||||
return coords.x + coords.y * chunk_size + coords.z * chunk_size * chunk_size
|
||||
@@ -0,0 +1 @@
|
||||
uid://bdfq22we54eul
|
||||
@@ -0,0 +1,14 @@
|
||||
[gd_scene format=3 uid="uid://llggsd0qmn4p"]
|
||||
|
||||
[ext_resource type="Script" uid="uid://bdfq22we54eul" path="res://SurfaceNetsWorld/chunk.gd" id="1_oab2n"]
|
||||
[ext_resource type="Shader" uid="uid://bose286qacwdl" path="res://SurfaceNetsWorld/generate_mesh.tres" id="2_uq73c"]
|
||||
|
||||
[sub_resource type="ShaderMaterial" id="ShaderMaterial_iutkt"]
|
||||
render_priority = 0
|
||||
shader = ExtResource("2_uq73c")
|
||||
|
||||
[node name="Chunk" type="Node3D" unique_id=1592820568]
|
||||
script = ExtResource("1_oab2n")
|
||||
|
||||
[node name="MeshInstance3D" type="MeshInstance3D" parent="." unique_id=1739626442]
|
||||
material_override = SubResource("ShaderMaterial_iutkt")
|
||||
@@ -0,0 +1,272 @@
|
||||
extends Node3D
|
||||
var rd: RenderingDevice
|
||||
var shader_file1: Resource
|
||||
var shader_file2: Resource
|
||||
var shader_spirv1: RDShaderSPIRV
|
||||
var shader_spirv2: RDShaderSPIRV
|
||||
var shader_pass1: RID
|
||||
var shader_pass2: RID
|
||||
var start_time := Time.get_ticks_msec() / 1000.0
|
||||
var color = Color.CORAL
|
||||
@export var iout_surface_points = []
|
||||
|
||||
var pipeline1
|
||||
var pipeline2
|
||||
var buffer
|
||||
var surface_buffer
|
||||
var normal_buffer
|
||||
var uv_buffer
|
||||
var idx_buffer
|
||||
var counter_buffer
|
||||
var chunk_position_buffer
|
||||
var params_buffer
|
||||
|
||||
func create_device(world_size: int):
|
||||
|
||||
rd = RenderingServer.create_local_rendering_device()
|
||||
|
||||
# 1. Load Shaders
|
||||
shader_file1 = load("res://SurfaceNetsWorld/compute_surface_points.glsl")
|
||||
shader_pass1 = rd.shader_create_from_spirv(shader_file1.get_spirv())
|
||||
shader_file2 = load("res://SurfaceNetsWorld/sdf_mesh_generation.glsl")
|
||||
shader_pass2 = rd.shader_create_from_spirv(shader_file2.get_spirv())
|
||||
|
||||
# 2. Create Pipelines
|
||||
pipeline1 = rd.compute_pipeline_create(shader_pass1)
|
||||
pipeline2 = rd.compute_pipeline_create(shader_pass2)
|
||||
|
||||
# 3. Pre-allocate Buffers (assuming world_size is constant)
|
||||
var total = world_size ** 3
|
||||
|
||||
# We create them once with empty/zero data of the correct size
|
||||
buffer = rd.storage_buffer_create(total * 4)
|
||||
surface_buffer = rd.storage_buffer_create(total * 3 * 4)
|
||||
normal_buffer = rd.storage_buffer_create(total * 3 * 4)
|
||||
uv_buffer = rd.storage_buffer_create(total * 2 * 4)
|
||||
idx_buffer = rd.storage_buffer_create(total * 6 * 4)
|
||||
counter_buffer = rd.storage_buffer_create(4)
|
||||
chunk_position_buffer = rd.storage_buffer_create(16) # vec4
|
||||
params_buffer = rd.uniform_buffer_create(16) # world_size, threshold, time, etc
|
||||
|
||||
func compute_mesh(world_size: int, threshold: float, chunk_pos: Vector3) -> ArrayMesh:
|
||||
|
||||
# 1. Update existing buffers with NEW data for THIS chunk
|
||||
var chunk_pos_data = PackedFloat32Array([chunk_pos.x, chunk_pos.y, chunk_pos.z, 0.0]).to_byte_array()
|
||||
rd.buffer_update(chunk_position_buffer, 0, chunk_pos_data.size(), chunk_pos_data)
|
||||
|
||||
# Reset the counter to 0 for the new chunk
|
||||
var counter_reset = PackedInt32Array([0]).to_byte_array()
|
||||
rd.buffer_update(counter_buffer, 0, 4, counter_reset)
|
||||
|
||||
# Chunk position (offset)
|
||||
var chunk_position_peer := PackedFloat32Array()
|
||||
chunk_position_peer.resize(4)
|
||||
chunk_position_peer.set(0, chunk_pos.x)
|
||||
chunk_position_peer.set(1, chunk_pos.y)
|
||||
chunk_position_peer.set(2, chunk_pos.z)
|
||||
chunk_position_peer.set(3, 0.0)
|
||||
var chunk_position_bytes := chunk_position_peer.to_byte_array()
|
||||
rd.buffer_update(chunk_position_buffer, 0, chunk_position_bytes.size(), chunk_position_bytes)
|
||||
|
||||
var u_time := Time.get_ticks_msec() / 1000.0 - start_time
|
||||
var peer := StreamPeerBuffer.new()
|
||||
peer.put_32(world_size)
|
||||
peer.put_float(threshold)
|
||||
peer.put_float(u_time)
|
||||
peer.put_32(0)
|
||||
var uniform_params_bytes := peer.data_array
|
||||
rd.buffer_update(params_buffer, 0, uniform_params_bytes.size(), uniform_params_bytes)
|
||||
|
||||
# Create a uniform to assign the buffer to the rendering device
|
||||
var uniform_buf := RDUniform.new()
|
||||
uniform_buf.uniform_type = RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER
|
||||
uniform_buf.binding = 0 # this needs to match the "binding" in our shader file
|
||||
uniform_buf.add_id(buffer)
|
||||
|
||||
# Create a uniform to assign the buffer to the rendering device
|
||||
var surface_uniform_buf := RDUniform.new()
|
||||
surface_uniform_buf.uniform_type = RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER
|
||||
surface_uniform_buf.binding = 2
|
||||
surface_uniform_buf.add_id(surface_buffer)
|
||||
|
||||
var normal_uniform = RDUniform.new()
|
||||
normal_uniform.uniform_type = RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER
|
||||
normal_uniform.binding = 3
|
||||
normal_uniform.add_id(normal_buffer)
|
||||
|
||||
var uv_uniform = RDUniform.new()
|
||||
uv_uniform.uniform_type = RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER
|
||||
uv_uniform.binding = 4
|
||||
uv_uniform.add_id(uv_buffer)
|
||||
|
||||
var idx_uniform := RDUniform.new()
|
||||
idx_uniform.uniform_type = RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER
|
||||
idx_uniform.binding = 5
|
||||
idx_uniform.add_id(idx_buffer)
|
||||
|
||||
var counter_uniform := RDUniform.new()
|
||||
counter_uniform.uniform_type = RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER
|
||||
counter_uniform.binding = 6
|
||||
counter_uniform.add_id(counter_buffer)
|
||||
|
||||
var chunk_position_uniform := RDUniform.new()
|
||||
chunk_position_uniform.uniform_type = RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER
|
||||
chunk_position_uniform.binding = 7
|
||||
chunk_position_uniform.add_id(chunk_position_buffer)
|
||||
|
||||
|
||||
|
||||
var uniform_params := RDUniform.new()
|
||||
uniform_params.uniform_type = RenderingDevice.UNIFORM_TYPE_UNIFORM_BUFFER
|
||||
uniform_params.binding = 1
|
||||
uniform_params.add_id(params_buffer)
|
||||
|
||||
var uniform_set1 := rd.uniform_set_create([uniform_buf, uniform_params, surface_uniform_buf, normal_uniform, uv_uniform, idx_uniform, counter_uniform, chunk_position_uniform], shader_pass1, 0) # the last parameter (the 0) needs to match the "set" in our shader file
|
||||
var uniform_set2 := rd.uniform_set_create([uniform_buf, uniform_params, surface_uniform_buf, normal_uniform, uv_uniform, idx_uniform, counter_uniform], shader_pass2, 0)
|
||||
|
||||
var dispatch_count = int(ceil(world_size / 4.0))
|
||||
|
||||
# 1. Dispatch PASS 1 (Calculate Points)
|
||||
var pipeline1 := rd.compute_pipeline_create(shader_pass1) # Points only
|
||||
var compute_list = rd.compute_list_begin()
|
||||
rd.compute_list_bind_compute_pipeline(compute_list, pipeline1)
|
||||
rd.compute_list_bind_uniform_set(compute_list, uniform_set1, 0)
|
||||
rd.compute_list_dispatch(compute_list, dispatch_count, dispatch_count, dispatch_count)
|
||||
rd.compute_list_end()
|
||||
|
||||
# 2. Dispatch PASS 2 (Generate Indices)
|
||||
var pipeline2 := rd.compute_pipeline_create(shader_pass2) # Indices only
|
||||
compute_list = rd.compute_list_begin()
|
||||
rd.compute_list_bind_compute_pipeline(compute_list, pipeline2)
|
||||
rd.compute_list_bind_uniform_set(compute_list, uniform_set2, 0)
|
||||
rd.compute_list_dispatch(compute_list, dispatch_count, dispatch_count, dispatch_count)
|
||||
rd.compute_list_end()
|
||||
|
||||
# Submit to GPU and wait for sync
|
||||
rd.submit()
|
||||
rd.sync()
|
||||
# Read back the data from the buffer
|
||||
var out_verts = rd.buffer_get_data(surface_buffer).to_float32_array()
|
||||
var out_norms = rd.buffer_get_data(normal_buffer).to_float32_array()
|
||||
var out_indices = rd.buffer_get_data(idx_buffer).to_int32_array()
|
||||
var final_count = rd.buffer_get_data(counter_buffer).to_int32_array()[0]
|
||||
var out_surface_points = rd.buffer_get_data(surface_buffer).to_float32_array()
|
||||
|
||||
# 5. Build the Mesh
|
||||
var mesh = ArrayMesh.new()
|
||||
var arrays = []
|
||||
arrays.resize(Mesh.ARRAY_MAX)
|
||||
|
||||
# We need to reshape the flat float array into Vector3s
|
||||
var verts := PackedVector3Array()
|
||||
var normals := PackedVector3Array()
|
||||
# Instead of blindly appending every voxel, we check if the voxel was "active"
|
||||
# Or, even better, map the original voxel indices to new packed indices
|
||||
var active_map = {}
|
||||
var packed_verts := PackedVector3Array()
|
||||
var packed_normals := PackedVector3Array()
|
||||
var packed_indices := PackedInt32Array()
|
||||
|
||||
var offset = Vector3(world_size / 2.0, world_size / 2.0, world_size / 2.0)
|
||||
var final_indices = out_indices.slice(0, final_count)
|
||||
|
||||
for old_idx in final_indices:
|
||||
var v_base = old_idx * 3
|
||||
|
||||
# 1. Skip if the shader marked this as an empty voxel
|
||||
if out_verts[v_base] < -0.5:
|
||||
continue
|
||||
|
||||
if not active_map.has(old_idx):
|
||||
active_map[old_idx] = packed_verts.size()
|
||||
# 2. Re-center the vertex so the mesh isn't floating in the corner
|
||||
var pos = Vector3(out_verts[v_base], out_verts[v_base+1], out_verts[v_base+2]) - offset
|
||||
packed_verts.append(pos)
|
||||
packed_normals.append(Vector3(out_norms[v_base], out_norms[v_base+1], out_norms[v_base+2]))
|
||||
|
||||
packed_indices.append(active_map[old_idx])
|
||||
|
||||
iout_surface_points = out_surface_points
|
||||
if packed_verts.size() > 0:
|
||||
arrays[Mesh.ARRAY_VERTEX] = packed_verts
|
||||
arrays[Mesh.ARRAY_NORMAL] = packed_normals
|
||||
arrays[Mesh.ARRAY_INDEX] = packed_indices
|
||||
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
|
||||
|
||||
return mesh
|
||||
|
||||
func build_sample_dict(world_size: int, flat_buffer: PackedFloat32Array) -> Dictionary:
|
||||
var dict := {}
|
||||
var total = world_size * world_size * world_size
|
||||
|
||||
for idx in total:
|
||||
var voxel_x = idx % world_size
|
||||
var voxel_y = (idx / world_size) % world_size
|
||||
var voxel_z = idx / (world_size * world_size)
|
||||
|
||||
var voxel_id = Vector3i(voxel_x, voxel_y, voxel_z)
|
||||
var distance = flat_buffer[idx]
|
||||
|
||||
dict[voxel_id] = distance
|
||||
|
||||
return dict
|
||||
|
||||
func build_surface_dict(world_size: int, flat_buffer: PackedFloat32Array) -> Dictionary:
|
||||
var dict := {}
|
||||
var total = world_size * world_size * world_size
|
||||
|
||||
for idx in total:
|
||||
var base = idx * 3
|
||||
var x = flat_buffer[base]
|
||||
var y = flat_buffer[base + 1]
|
||||
var z = flat_buffer[base + 2]
|
||||
|
||||
var voxel_x = idx % world_size
|
||||
var voxel_y = (idx / world_size) % world_size
|
||||
var voxel_z = idx / (world_size * world_size)
|
||||
|
||||
var voxel_id = Vector3i(voxel_x, voxel_y, voxel_z)
|
||||
var surface_pos = Vector3(x, y, z)
|
||||
|
||||
dict[voxel_id] = surface_pos
|
||||
|
||||
return dict
|
||||
|
||||
func _exit_tree():
|
||||
# If the rendering device wasn't initialized, we have nothing to free
|
||||
if not rd:
|
||||
return
|
||||
|
||||
# 1. Free Shader and Pipeline RIDs
|
||||
# Pipelines depend on shaders, so free them first
|
||||
if pipeline1.is_valid():
|
||||
rd.free_rid(pipeline1)
|
||||
if pipeline2.is_valid():
|
||||
rd.free_rid(pipeline2)
|
||||
|
||||
if shader_pass1.is_valid():
|
||||
rd.free_rid(shader_pass1)
|
||||
if shader_pass2.is_valid():
|
||||
rd.free_rid(shader_pass2)
|
||||
|
||||
# 2. Free Buffer RIDs
|
||||
# These are the actual memory allocations on the VRAM
|
||||
var buffers_to_free = [
|
||||
buffer,
|
||||
surface_buffer,
|
||||
normal_buffer,
|
||||
uv_buffer,
|
||||
idx_buffer,
|
||||
counter_buffer,
|
||||
chunk_position_buffer,
|
||||
params_buffer
|
||||
]
|
||||
|
||||
for b_rid in buffers_to_free:
|
||||
if b_rid.is_valid():
|
||||
rd.free_rid(b_rid)
|
||||
|
||||
# 3. Finalize the Rendering Device
|
||||
# This tells Godot we are done with this local device entirely
|
||||
rd.free()
|
||||
rd = null
|
||||
@@ -0,0 +1 @@
|
||||
uid://du1xgjbvpa6dk
|
||||
@@ -0,0 +1,265 @@
|
||||
#[compute]
|
||||
#version 450
|
||||
|
||||
// Workgroup size
|
||||
layout(local_size_x = 4, local_size_y = 4, local_size_z = 4) in;
|
||||
|
||||
// Storage buffer
|
||||
layout(set = 0, binding = 0, std430) buffer DataBuffer {
|
||||
float sample_points[];
|
||||
} voxels;
|
||||
|
||||
layout(set = 0, binding = 1) uniform Params {
|
||||
int world_size;
|
||||
float threshold;
|
||||
float u_time;
|
||||
} params;
|
||||
|
||||
layout(set = 0, binding = 2, std430) buffer SurfaceBuffer {
|
||||
float surface_points[];
|
||||
} surface;
|
||||
|
||||
layout(set = 0, binding = 3, std430) buffer NormalsBuffer {
|
||||
float normals[];
|
||||
} normal;
|
||||
|
||||
layout(set = 0, binding = 4, std430) buffer UVBuffer {
|
||||
vec2 UVs[];
|
||||
} UV;
|
||||
|
||||
layout(set = 0, binding = 5, std430) buffer IndexBuffer {
|
||||
uint indices[];
|
||||
} mesh_indices;
|
||||
|
||||
layout(set = 0, binding = 6, std430) buffer Counter {
|
||||
uint count;
|
||||
} index_count;
|
||||
|
||||
layout(set = 0, binding = 7, std430) buffer ChunkPos {
|
||||
float position_array[];
|
||||
} chunk;
|
||||
|
||||
uint index3(uint x, uint y, uint z) {
|
||||
return x + y * params.world_size + z * params.world_size * params.world_size;
|
||||
}
|
||||
|
||||
void store_surface_point(uint idx, vec3 pos) {
|
||||
uint base = idx * 3u;
|
||||
surface.surface_points[base + 0u] = pos.x;
|
||||
surface.surface_points[base + 1u] = pos.y;
|
||||
surface.surface_points[base + 2u] = pos.z;
|
||||
}
|
||||
|
||||
//
|
||||
// Description : Array and textureless GLSL 2D/3D/4D simplex
|
||||
// noise functions.
|
||||
// Author : Ian McEwan, Ashima Arts.
|
||||
// Maintainer : stegu
|
||||
// Lastmod : 20201014 (stegu)
|
||||
// License : Copyright (C) 2011 Ashima Arts. All rights reserved.
|
||||
// Distributed under the MIT License. See LICENSE file.
|
||||
// https://github.com/ashima/webgl-noise
|
||||
// https://github.com/stegu/webgl-noise
|
||||
//
|
||||
|
||||
vec3 mod289(vec3 x) {
|
||||
return x - floor(x * (1.0 / 289.0)) * 289.0;
|
||||
}
|
||||
|
||||
vec4 mod289(vec4 x) {
|
||||
return x - floor(x * (1.0 / 289.0)) * 289.0;
|
||||
}
|
||||
|
||||
vec4 permute(vec4 x) {
|
||||
return mod289(((x*34.0)+10.0)*x);
|
||||
}
|
||||
|
||||
vec4 taylorInvSqrt(vec4 r)
|
||||
{
|
||||
return 1.79284291400159 - 0.85373472095314 * r;
|
||||
}
|
||||
|
||||
float snoise(vec3 v)
|
||||
{
|
||||
const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;
|
||||
const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
|
||||
|
||||
// First corner
|
||||
vec3 i = floor(v + dot(v, C.yyy) );
|
||||
vec3 x0 = v - i + dot(i, C.xxx) ;
|
||||
|
||||
// Other corners
|
||||
vec3 g = step(x0.yzx, x0.xyz);
|
||||
vec3 l = 1.0 - g;
|
||||
vec3 i1 = min( g.xyz, l.zxy );
|
||||
vec3 i2 = max( g.xyz, l.zxy );
|
||||
|
||||
// x0 = x0 - 0.0 + 0.0 * C.xxx;
|
||||
// x1 = x0 - i1 + 1.0 * C.xxx;
|
||||
// x2 = x0 - i2 + 2.0 * C.xxx;
|
||||
// x3 = x0 - 1.0 + 3.0 * C.xxx;
|
||||
vec3 x1 = x0 - i1 + C.xxx;
|
||||
vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y
|
||||
vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y
|
||||
|
||||
// Permutations
|
||||
i = mod289(i);
|
||||
vec4 p = permute( permute( permute(
|
||||
i.z + vec4(0.0, i1.z, i2.z, 1.0 ))
|
||||
+ i.y + vec4(0.0, i1.y, i2.y, 1.0 ))
|
||||
+ i.x + vec4(0.0, i1.x, i2.x, 1.0 ));
|
||||
|
||||
// Gradients: 7x7 points over a square, mapped onto an octahedron.
|
||||
// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
|
||||
float n_ = 0.142857142857; // 1.0/7.0
|
||||
vec3 ns = n_ * D.wyz - D.xzx;
|
||||
|
||||
vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)
|
||||
|
||||
vec4 x_ = floor(j * ns.z);
|
||||
vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)
|
||||
|
||||
vec4 x = x_ *ns.x + ns.yyyy;
|
||||
vec4 y = y_ *ns.x + ns.yyyy;
|
||||
vec4 h = 1.0 - abs(x) - abs(y);
|
||||
|
||||
vec4 b0 = vec4( x.xy, y.xy );
|
||||
vec4 b1 = vec4( x.zw, y.zw );
|
||||
|
||||
//vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0;
|
||||
//vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0;
|
||||
vec4 s0 = floor(b0)*2.0 + 1.0;
|
||||
vec4 s1 = floor(b1)*2.0 + 1.0;
|
||||
vec4 sh = -step(h, vec4(0.0));
|
||||
|
||||
vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
|
||||
vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;
|
||||
|
||||
vec3 p0 = vec3(a0.xy,h.x);
|
||||
vec3 p1 = vec3(a0.zw,h.y);
|
||||
vec3 p2 = vec3(a1.xy,h.z);
|
||||
vec3 p3 = vec3(a1.zw,h.w);
|
||||
|
||||
//Normalise gradients
|
||||
vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
|
||||
p0 *= norm.x;
|
||||
p1 *= norm.y;
|
||||
p2 *= norm.z;
|
||||
p3 *= norm.w;
|
||||
|
||||
// Mix final noise value
|
||||
vec4 m = max(0.5 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
|
||||
m = m * m;
|
||||
return 105.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
|
||||
dot(p2,x2), dot(p3,x3) ) ) + params.threshold;
|
||||
}
|
||||
|
||||
const ivec3 AXIS[3] = ivec3[](
|
||||
ivec3(1,0,0),
|
||||
ivec3(0,1,0),
|
||||
ivec3(0,0,1)
|
||||
);
|
||||
|
||||
const ivec3 SURFACE_AXIS[8] = ivec3[](
|
||||
ivec3(1,0,0),
|
||||
ivec3(0,1,0),
|
||||
ivec3(0,0,1),
|
||||
ivec3(1,0,1),
|
||||
ivec3(0,1,1),
|
||||
ivec3(1,1,0),
|
||||
ivec3(1,1,1),
|
||||
ivec3(0,0,0)
|
||||
);
|
||||
|
||||
// The 12 edges of a cube (pairs of corner indices 0-7)
|
||||
const ivec2 EDGE_CORNERS[12] = ivec2[](
|
||||
ivec2(0,1), ivec2(1,2), ivec2(2,3), ivec2(3,0), // Bottom face edges
|
||||
ivec2(4,5), ivec2(5,6), ivec2(6,7), ivec2(7,4), // Top face edges
|
||||
ivec2(0,4), ivec2(1,5), ivec2(2,6), ivec2(3,7) // Vertical edges
|
||||
);
|
||||
|
||||
// The 8 corners of a cube
|
||||
const ivec3 CORNERS[8] = ivec3[](
|
||||
ivec3(0,0,0), ivec3(1,0,0), ivec3(1,1,0), ivec3(0,1,0),
|
||||
ivec3(0,0,1), ivec3(1,0,1), ivec3(1,1,1), ivec3(0,1,1)
|
||||
);
|
||||
|
||||
float get_noise_at(vec3 p) {
|
||||
|
||||
float chunk_x = chunk.position_array[0] * -.5;
|
||||
float chunk_y = chunk.position_array[1] * -.5;
|
||||
float chunk_z = chunk.position_array[2] * -.5;
|
||||
p = p - vec3(chunk_x, chunk_y, chunk_z);
|
||||
p = p / 20.0;
|
||||
return snoise(p);
|
||||
}
|
||||
|
||||
// Calculate normal using central difference
|
||||
vec3 calculate_normal(vec3 p) {
|
||||
float e = 0.01; // Small epsilon
|
||||
float dx = get_noise_at(p + vec3(e, 0, 0)) - get_noise_at(p - vec3(e, 0, 0));
|
||||
float dy = get_noise_at(p + vec3(0, e, 0)) - get_noise_at(p - vec3(0, e, 0));
|
||||
float dz = get_noise_at(p + vec3(0, 0, e)) - get_noise_at(p - vec3(0, 0, e));
|
||||
return normalize(vec3(dx, dy, dz));
|
||||
}
|
||||
|
||||
vec3 grid_to_world(uvec3 grid_id) {
|
||||
return (vec3(grid_id) - params.world_size / 2.0) * 0.5;
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec3 id = ivec3(gl_GlobalInvocationID);
|
||||
if (any(greaterThanEqual(id, uvec3(params.world_size)))) return;
|
||||
|
||||
vec3 p = grid_to_world(id);
|
||||
uint idx = index3(id.x, id.y, id.z);
|
||||
voxels.sample_points[idx] = get_noise_at(p);
|
||||
|
||||
memoryBarrierBuffer();
|
||||
barrier();
|
||||
|
||||
|
||||
vec3 intersection_sum = vec3(0.0);
|
||||
uint count = 0;
|
||||
|
||||
// Dual Contouring requires checking all 12 edges of the voxel.
|
||||
// If ANY of these 12 edges has a sign change, this voxel MUST have a vertex.
|
||||
for (int i = 0; i < 12; i++) {
|
||||
ivec3 c1_off = CORNERS[EDGE_CORNERS[i].x];
|
||||
ivec3 c2_off = CORNERS[EDGE_CORNERS[i].y];
|
||||
|
||||
uvec3 c1 = id + uvec3(c1_off);
|
||||
uvec3 c2 = id + uvec3(c2_off);
|
||||
|
||||
// Bounds check to prevent sampling noise outside the allocated buffer
|
||||
if (any(greaterThanEqual(c1, uvec3(params.world_size))) ||
|
||||
any(greaterThanEqual(c2, uvec3(params.world_size)))) continue;
|
||||
|
||||
float d1 = get_noise_at(grid_to_world(c1));
|
||||
float d2 = get_noise_at(grid_to_world(c2));
|
||||
|
||||
// Standard sign-change test
|
||||
if ((d1 < 0.0) != (d2 < 0.0) && d1 != -d2) {
|
||||
// Linear interpolation to find the exact crossing point on the edge
|
||||
float t = d1 / (d1 - d2);
|
||||
intersection_sum += mix(vec3(c1), vec3(c2), t);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
if (count > 0) {
|
||||
vec3 avg_pos = intersection_sum / float(count);
|
||||
store_surface_point(idx, avg_pos);
|
||||
|
||||
// Normals should be calculated at the exact averaged surface point
|
||||
vec3 world_p = (avg_pos - params.world_size / 2.0) * vec3(0.5);
|
||||
vec3 n = calculate_normal(world_p);
|
||||
uint base = idx * 3u;
|
||||
normal.normals[base + 0] = n.x;
|
||||
normal.normals[base + 1] = n.y;
|
||||
normal.normals[base + 2] = n.z;
|
||||
} else {
|
||||
// Explicitly mark empty voxels to prevent them from being used in Pass 2
|
||||
store_surface_point(idx, vec3(-1.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[remap]
|
||||
|
||||
importer="glsl"
|
||||
type="RDShaderFile"
|
||||
uid="uid://dv4s7mmqwnsqr"
|
||||
path="res://.godot/imported/compute_surface_points.glsl-11430003a7d9b84dfd57d5dcf11b574d.res"
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://SurfaceNetsWorld/compute_surface_points.glsl"
|
||||
dest_files=["res://.godot/imported/compute_surface_points.glsl-11430003a7d9b84dfd57d5dcf11b574d.res"]
|
||||
|
||||
[params]
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[gd_resource type="VisualShader" format=3 uid="uid://bose286qacwdl"]
|
||||
|
||||
[sub_resource type="VisualShaderNodeColorConstant" id="VisualShaderNodeColorConstant_sxi40"]
|
||||
constant = Color(0.30202293, 0.6060653, 0.9109474, 1)
|
||||
|
||||
[resource]
|
||||
nodes/vertex/0/position = Vector2(360, 220)
|
||||
nodes/fragment/0/position = Vector2(660, 140)
|
||||
nodes/fragment/2/node = SubResource("VisualShaderNodeColorConstant_sxi40")
|
||||
nodes/fragment/2/position = Vector2(260, 220)
|
||||
nodes/fragment/connections = PackedInt32Array(2, 0, 0, 0)
|
||||
@@ -0,0 +1,86 @@
|
||||
#[compute]
|
||||
#version 450
|
||||
|
||||
layout(local_size_x = 4, local_size_y = 4, local_size_z = 4) in;
|
||||
|
||||
layout(set = 0, binding = 0, std430) buffer DataBuffer { float sample_points[]; } voxels;
|
||||
layout(set = 0, binding = 1) uniform Params { int world_size; float threshold; float u_time; } params;
|
||||
layout(set = 0, binding = 2, std430) buffer SurfaceBuffer { float surface_points[]; } surface;
|
||||
layout(set = 0, binding = 5, std430) buffer IndexBuffer { uint indices[]; } mesh_indices;
|
||||
layout(set = 0, binding = 6, std430) buffer Counter { uint count; } index_count;
|
||||
|
||||
uint index3(uint x, uint y, uint z) {
|
||||
return x + y * params.world_size + z * params.world_size * params.world_size;
|
||||
}
|
||||
|
||||
bool has_vertex(ivec3 p) {
|
||||
// Boundary check for the voxel itself
|
||||
if (any(lessThan(p, ivec3(0))) || any(greaterThanEqual(p, ivec3(params.world_size)))) return false;
|
||||
uint idx = index3(uint(p.x), uint(p.y), uint(p.z));
|
||||
float val = surface.surface_points[idx * 3u];
|
||||
return (val >= 0.0 && val <= float(params.world_size));
|
||||
}
|
||||
|
||||
// Translated QUAD_POINTS from your GDScript
|
||||
const ivec3 QUAD_OFFSETS[3][4] = ivec3[3][4](
|
||||
// X-Axis Edges
|
||||
ivec3[](ivec3(0,0,-1), ivec3(0,-1,-1), ivec3(0,-1,0), ivec3(0,0,0)),
|
||||
// Y-Axis Edges
|
||||
ivec3[](ivec3(0,0,-1), ivec3(0,0,0), ivec3(-1,0,0), ivec3(-1,0,-1)),
|
||||
// Z-Axis Edges
|
||||
ivec3[](ivec3(0,0,0), ivec3(0,-1,0), ivec3(-1,-1,0), ivec3(-1,0,0))
|
||||
);
|
||||
|
||||
const ivec3 AXIS[3] = ivec3[](ivec3(1,0,0), ivec3(0,1,0), ivec3(0,0,1));
|
||||
|
||||
|
||||
void main() {
|
||||
memoryBarrierBuffer();
|
||||
ivec3 id = ivec3(gl_GlobalInvocationID);
|
||||
if (any(greaterThanEqual(id, ivec3(params.world_size)))) return;
|
||||
|
||||
uint idx = index3(id.x, id.y, id.z);
|
||||
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
ivec3 neighbor_id = id + AXIS[i];
|
||||
|
||||
if (any(greaterThanEqual(neighbor_id, ivec3(params.world_size)))) continue;
|
||||
|
||||
float d1 = voxels.sample_points[idx];
|
||||
float d2 = voxels.sample_points[index3(neighbor_id.x, neighbor_id.y, neighbor_id.z)];
|
||||
|
||||
if ((d1 < 0.0) != (d2 < 0.0) && d1 != -d2) {
|
||||
ivec3 p0 = id + QUAD_OFFSETS[i][0];
|
||||
ivec3 p1 = id + QUAD_OFFSETS[i][1];
|
||||
ivec3 p2 = id + QUAD_OFFSETS[i][2];
|
||||
ivec3 p3 = id + QUAD_OFFSETS[i][3];
|
||||
|
||||
if (has_vertex(p0) && has_vertex(p1) && has_vertex(p2) && has_vertex(p3)) {
|
||||
uint v0 = index3(p0.x, p0.y, p0.z);
|
||||
uint v1 = index3(p1.x, p1.y, p1.z);
|
||||
uint v2 = index3(p2.x, p2.y, p2.z);
|
||||
uint v3 = index3(p3.x, p3.y, p3.z);
|
||||
|
||||
uint start = atomicAdd(index_count.count, 6);
|
||||
|
||||
if (d1 < 0.0) {
|
||||
mesh_indices.indices[start + 0] = v0;
|
||||
mesh_indices.indices[start + 1] = v1;
|
||||
mesh_indices.indices[start + 2] = v2;
|
||||
mesh_indices.indices[start + 3] = v0;
|
||||
mesh_indices.indices[start + 4] = v2;
|
||||
mesh_indices.indices[start + 5] = v3;
|
||||
} else {
|
||||
// Reverse the order for the other side of the surface
|
||||
mesh_indices.indices[start + 0] = v0;
|
||||
mesh_indices.indices[start + 1] = v3;
|
||||
mesh_indices.indices[start + 2] = v2;
|
||||
mesh_indices.indices[start + 3] = v0;
|
||||
mesh_indices.indices[start + 4] = v2;
|
||||
mesh_indices.indices[start + 5] = v1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[remap]
|
||||
|
||||
importer="glsl"
|
||||
type="RDShaderFile"
|
||||
uid="uid://d348vk1vnsbps"
|
||||
path="res://.godot/imported/sdf_mesh_generation.glsl-d7c76c8683be743d5aa10359d91ec159.res"
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://SurfaceNetsWorld/sdf_mesh_generation.glsl"
|
||||
dest_files=["res://.godot/imported/sdf_mesh_generation.glsl-d7c76c8683be743d5aa10359d91ec159.res"]
|
||||
|
||||
[params]
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
extends Node3D
|
||||
|
||||
@export var chunk_size = 16
|
||||
@export var world_size = 6
|
||||
@export var threshold = 0.2
|
||||
|
||||
var chunk_scene = preload("res://SurfaceNetsWorld/chunk.tscn")
|
||||
|
||||
var ComputeSdf = preload("res://SurfaceNetsWorld/compute_samples.gd")
|
||||
var gpu_sdf
|
||||
|
||||
# Called when the node enters the scene tree for the first time.
|
||||
func _ready() -> void:
|
||||
gpu_sdf = ComputeSdf.new()
|
||||
gpu_sdf.create_device(chunk_size)
|
||||
for x in range(world_size):
|
||||
for y in range(world_size):
|
||||
for z in range(world_size):
|
||||
var chunk: Node = chunk_scene.instantiate()
|
||||
chunk.chunk_size = chunk_size
|
||||
chunk.threshold = threshold
|
||||
chunk.position = Vector3(x * chunk_size, y * chunk_size, z * chunk_size)
|
||||
chunk.generate_chunk(gpu_sdf)
|
||||
await Engine.get_main_loop().process_frame
|
||||
add_child(chunk)
|
||||
|
||||
|
||||
|
||||
# Called every frame. 'delta' is the elapsed time since the previous frame.
|
||||
func _process(delta: float) -> void:
|
||||
pass
|
||||
@@ -0,0 +1 @@
|
||||
uid://cgf3kpllu4cv7
|
||||
@@ -0,0 +1,9 @@
|
||||
[gd_scene format=3 uid="uid://d13vfr2vhyq17"]
|
||||
|
||||
[ext_resource type="Script" uid="uid://cgf3kpllu4cv7" path="res://SurfaceNetsWorld/smooth_world.gd" id="1_4h467"]
|
||||
|
||||
[node name="SmoothWorld" type="Node3D" unique_id=113243680]
|
||||
script = ExtResource("1_4h467")
|
||||
chunk_size = 64
|
||||
world_size = 4
|
||||
threshold = 0.045
|
||||
Reference in New Issue
Block a user