W3: Chunked terrain mesh, collision and LOD

TerrainView draws the island as 16 x 16 chunks of 64 m, each at one of
four detail levels (2, 4, 8 and 16 m spacing) chosen by distance to the
camera. TerrainChunkBuilder builds chunk geometry on WorkerThreadPool
threads; the main thread only uploads finished meshes, within a 2 ms
per-frame budget, nearest chunks first.

- Seams: every chunk hangs skirts deeper than twice the most any level
  strays from the full-resolution edge, so neighbours at any two levels
  meet without a crack. Normals come from the full-resolution heightfield
  at every level, and back faces light like the ground above them.
- Splat material: a procedural shader blends sand, marsh, grass and rock
  with weights from the island's bands, averaged over 4 m so borders
  blend. Steep ground turns to rock and summits weather pale.
- Collision stays SimGround's heightfield, with no renderer involved.
- Capture scenarios terrain, terrain_lod (tinted by level) and
  terrain_cracks (magenta sky). tools/crack_check.gd counts sky pixels
  seen through the ground; make terrain-capture requires cracks in a
  skirtless control and none in the real terrain.

Tests: chunk vertices sit on the heightfield; skirts cover every pairing
of levels on sampled shared edges; detail falls with distance; flying
across the island at 30 m/s for 2,037 frames streams 661 chunk rebuilds
with the worst main-thread frame at 0.8 to 1.4 ms (headless, CPU only);
24 players over 900 ticks on two generated islands never sink into the
ground, and a player sprints up towards a summit unharmed.
make terrain-capture: control 437 crack pixels, terrain 0.

Closes #10

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 14:28:30 -05:00
co-authored by Claude Opus 5.5
parent c70d0c1c4f
commit 8b74485168
22 changed files with 840 additions and 1 deletions
+6
View File
@@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureTerrain" type="Node3D"]
script = ExtResource("1")
+11
View File
@@ -0,0 +1,11 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureTerrainCracks" type="Node3D"]
script = ExtResource("1")
eye = Vector2(520, 640)
lift = 160.0
target = Vector3(520, 20, 470)
crack_check = true
fov = 60.0
+12
View File
@@ -0,0 +1,12 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureTerrainCracksControl" type="Node3D"]
script = ExtResource("1")
eye = Vector2(520, 640)
lift = 160.0
target = Vector3(520, 20, 470)
crack_check = true
fov = 60.0
skirts = false
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureTerrainLod" type="Node3D"]
script = ExtResource("1")
eye = Vector2(560, 700)
lift = 140.0
target = Vector3(520, 20, 430)
show_lod = true
+71
View File
@@ -0,0 +1,71 @@
## Capture scenario for the streamed island terrain. The camera stands `lift` metres above
## the ground at `eye` (x, z) and looks at `target`. With `crack_check` the sky is a flat
## magenta that appears nowhere in the terrain, so any crack between chunks shows up as
## magenta pixels for tools/crack_check.gd to count.
extends Node3D
const CRACK_COLOUR: Color = Color(1.0, 0.0, 1.0)
@export var island_seed: int = 2
@export var eye: Vector2 = Vector2(700.0, 760.0)
@export var lift: float = 12.0
@export var target: Vector3 = Vector3(520.0, 35.0, 470.0)
@export var show_lod: bool = false
@export var crack_check: bool = false
@export var fov: float = 70.0
## Off only in terrain_cracks_control, which must show cracks.
@export var skirts: bool = true
func _ready() -> void:
var island: Island = Island.generate(island_seed)
var environment: Environment = Environment.new()
if crack_check:
environment.background_mode = Environment.BG_COLOR
environment.background_color = CRACK_COLOUR
environment.ambient_light_source = Environment.AMBIENT_SOURCE_COLOR
environment.ambient_light_color = Color(0.5, 0.5, 0.5)
environment.tonemap_mode = Environment.TONE_MAPPER_LINEAR
else:
var sky_material: ProceduralSkyMaterial = ProceduralSkyMaterial.new()
sky_material.sky_top_color = Color(0.32, 0.5, 0.68)
sky_material.sky_horizon_color = Color(0.82, 0.78, 0.68)
sky_material.ground_bottom_color = Color(0.18, 0.2, 0.2)
sky_material.ground_horizon_color = Color(0.82, 0.78, 0.68)
var sky: Sky = Sky.new()
sky.sky_material = sky_material
environment.background_mode = Environment.BG_SKY
environment.sky = sky
environment.ambient_light_source = Environment.AMBIENT_SOURCE_SKY
environment.ambient_light_energy = 0.45
environment.tonemap_mode = Environment.TONE_MAPPER_FILMIC
environment.fog_enabled = true
environment.fog_light_color = Color(0.78, 0.78, 0.74)
environment.fog_density = 0.0005
environment.fog_aerial_perspective = 0.4
var world: WorldEnvironment = WorldEnvironment.new()
world.environment = environment
add_child(world)
var sun: DirectionalLight3D = DirectionalLight3D.new()
sun.rotation_degrees = Vector3(-35.0, -130.0, 0.0)
sun.light_energy = 0.95
sun.shadow_enabled = not crack_check
sun.directional_shadow_max_distance = 600.0
add_child(sun)
var camera: Camera3D = Camera3D.new()
camera.fov = fov
camera.far = 2000.0
camera.position = Vector3(eye.x, island.ground.terrain_height(eye.x, eye.y) + lift, eye.y)
add_child(camera)
camera.look_at(target)
camera.make_current()
var terrain: TerrainView = TerrainView.new()
terrain.setup(island)
terrain.focus = camera.position
terrain.show_lod = show_lod
terrain.skirts = skirts
add_child(terrain)
terrain.build_all_now()
+1
View File
@@ -0,0 +1 @@
uid://bcc26uufsyxi8
+132
View File
@@ -0,0 +1,132 @@
extends TestCase
const SEED: int = 2
## The streaming budget from issue W3: no frame's terrain work may exceed this.
const FRAME_SPIKE_USEC: int = 8_000
var _island: Island
func before_each() -> void:
if _island == null:
_island = Island.generate(SEED)
func test_chunk_vertices_sit_on_the_heightfield() -> void:
var ground: SimGround = _island.ground
var chunk: Vector2i = Vector2i(7, 6)
var rect: Rect2 = TerrainChunkBuilder.chunk_rect(ground, chunk)
for lod: int in TerrainChunkBuilder.LOD_STEPS.size():
var arrays: Array = TerrainChunkBuilder.build(ground, _island.bands, chunk, lod)
var vertices: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
var per_side: int = TerrainChunkBuilder.CHUNK_CELLS / TerrainChunkBuilder.LOD_STEPS[lod] + 1
assert_eq(vertices.size(), per_side * per_side + 4 * per_side, "vertex count at level %d" % lod)
var triangles: int = 2 * (per_side - 1) * (per_side - 1) + 4 * 2 * (per_side - 1)
assert_eq((arrays[Mesh.ARRAY_INDEX] as PackedInt32Array).size(), triangles * 3)
for index: int in per_side * per_side:
var vertex: Vector3 = vertices[index]
assert_true(rect.grow(0.001).has_point(Vector2(vertex.x, vertex.z)), "vertex %s outside its chunk" % vertex)
assert_near(vertex.y, ground.terrain_height(vertex.x, vertex.z), 0.001)
for normal: Vector3 in arrays[Mesh.ARRAY_NORMAL] as PackedVector3Array:
assert_true(normal.is_normalized() and normal.y > 0.0, "bad normal %s" % normal)
for weights: Color in arrays[Mesh.ARRAY_COLOR] as PackedColorArray:
assert_near(weights.r + weights.g + weights.b + weights.a, 1.0, 0.001)
func test_world_is_covered_by_chunks() -> void:
var ground: SimGround = _island.ground
var count: int = TerrainChunkBuilder.chunks_per_side(ground)
var last: Rect2 = TerrainChunkBuilder.chunk_rect(ground, Vector2i(count - 1, count - 1))
assert_near(last.end.x, Tuning.WORLD_SIZE_METRES, 0.001)
assert_near(last.end.y, Tuning.WORLD_SIZE_METRES, 0.001)
func test_skirts_cover_every_level_pairing_on_shared_edges() -> void:
# Along every shared edge, two neighbours at any two detail levels may disagree on
# height. The skirt of each must hang further than that, or a crack opens.
var ground: SimGround = _island.ground
var count: int = TerrainChunkBuilder.chunks_per_side(ground)
var levels: int = TerrainChunkBuilder.LOD_STEPS.size()
var checked: int = 0
for z: int in range(2, count - 2, 3):
for x: int in range(2, count - 2, 3):
var a: Vector2i = Vector2i(x, z)
var b: Vector2i = Vector2i(x + 1, z)
var depth: float = minf(TerrainChunkBuilder.skirt_depth(ground, a), TerrainChunkBuilder.skirt_depth(ground, b))
for lod_a: int in levels:
var edge_a: PackedFloat32Array = _edge_profile(a, lod_a, 3)
for lod_b: int in levels:
var edge_b: PackedFloat32Array = _edge_profile(b, lod_b, 2)
for index: int in edge_a.size():
var gap: float = absf(edge_a[index] - edge_b[index])
assert_true(gap < depth - TerrainChunkBuilder.SKIRT_MARGIN * 0.5,
"chunks %s/%s levels %d/%d: gap %.2f m, skirt %.2f m" % [a, b, lod_a, lod_b, gap, depth])
checked += 1
assert_true(checked > 100, "checked only %d pairings" % checked)
func test_detail_falls_with_distance() -> void:
var view: TerrainView = TerrainView.new()
view.setup(_island)
view.focus = Vector3(500.0, 30.0, 500.0)
var here: Vector2i = Vector2i(7, 7)
assert_eq(view.wanted_lod(here), 0, "the focus chunk is full detail")
var previous: int = 0
for x: int in range(7, 16):
var lod: int = view.wanted_lod(Vector2i(x, 7))
assert_true(lod >= previous, "detail must not rise with distance")
previous = lod
assert_eq(previous, TerrainChunkBuilder.LOD_STEPS.size() - 1, "the far edge is coarsest")
view.free()
func test_streaming_across_the_island_stays_under_the_frame_budget() -> void:
# The profiler scenario: load the island around one end, then fly the focus across it
# at 30 m/s for a 60 fps frame rate (0.5 m per frame), measuring the main-thread time
# TerrainView spends each frame. Geometry is built on worker threads. Headless, so this
# measures CPU work only; GPU upload time needs a real-GPU playtest.
var tree: SceneTree = Engine.get_main_loop() as SceneTree
var view: TerrainView = TerrainView.new()
view.setup(_island)
view.focus = Vector3(150.0, 30.0, 150.0)
tree.root.add_child(view)
view.build_all_now()
var loaded: int = view.uploads
view.max_frame_usec = 0
var start: Vector3 = view.focus
var finish: Vector3 = Vector3(880.0, 30.0, 860.0)
var frames: int = ceili(start.distance_to(finish) / 0.5)
for frame: int in frames:
view.focus = start.lerp(finish, float(frame) / frames)
await tree.process_frame
for _frame: int in 600:
if view.settled():
break
await tree.process_frame
var streamed: int = view.uploads - loaded
print(" terrain streaming: %d frames, %d chunk rebuilds, worst frame %d us" % [frames, streamed, view.max_frame_usec])
assert_true(streamed > 50, "expected real streaming, got %d rebuilds" % streamed)
assert_true(view.settled(), "terrain never caught up with the focus")
assert_true(view.max_frame_usec < FRAME_SPIKE_USEC, "worst frame %d us" % view.max_frame_usec)
view.queue_free()
await tree.process_frame
## Heights along a chunk's edge at full-resolution spacing, as that chunk draws them at
## `lod`: each coarse span is a straight line between its end samples.
func _edge_profile(chunk: Vector2i, lod: int, edge_column_side: int) -> PackedFloat32Array:
var arrays: Array = TerrainChunkBuilder.build(_island.ground, _island.bands, chunk, lod)
var vertices: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
var step: int = TerrainChunkBuilder.LOD_STEPS[lod]
var per_side: int = TerrainChunkBuilder.CHUNK_CELLS / step + 1
# Side 3 is the east column, side 2 the west column; both run along z.
var column: int = per_side - 1 if edge_column_side == 3 else 0
var profile: PackedFloat32Array = PackedFloat32Array()
for position: int in TerrainChunkBuilder.CHUNK_CELLS + 1:
var low: int = position / step
var high: int = mini(low + 1, per_side - 1)
var t: float = float(position % step) / step
var a: float = vertices[low * per_side + column].y
var b: float = vertices[high * per_side + column].y
profile.append(lerpf(a, b, t))
return profile
+1
View File
@@ -0,0 +1 @@
uid://boq3wln8pjs5j
+60
View File
@@ -0,0 +1,60 @@
extends TestCase
## Character movement on generated islands, in the headless simulation with no renderer:
## the server's collision is SimGround's heightfield, never a render mesh.
const TICKS: int = 900
func test_players_never_sink_into_generated_terrain() -> void:
for seed_value: int in [11, 12]:
var sim: Simulation = Simulation.new(seed_value)
var random: RandomNumberGenerator = RandomNumberGenerator.new()
random.seed = seed_value
var ids: Array[int] = []
for _index: int in 12:
ids.append(sim.add_player())
var grounded: int = 0
var samples: int = 0
for _tick: int in TICKS:
for id: int in ids:
var move: Vector2 = Vector2(random.randf_range(-1.0, 1.0), random.randf_range(-1.0, 1.0))
var buttons: int = PlayerCommand.BUTTON_SPRINT if random.randf() < 0.5 else 0
if random.randf() < 0.004:
buttons |= PlayerCommand.BUTTON_JUMP
sim.submit_command(id, PlayerCommand.from_input(sim.tick, move, random.randf() * TAU, 0.0, buttons))
sim.step()
for id: int in ids:
var player: SimEntity = sim.entities.find(id)
var floor_height: float = sim.ground.terrain_height(player.position.x, player.position.z)
assert_true(player.position.y >= floor_height - 0.01,
"seed %d player %d sank to %.2f below ground at %s" % [seed_value, id, floor_height - player.position.y, player.position])
assert_false(is_nan(player.position.length()), "position became NaN")
samples += 1
if player.on_ground:
grounded += 1
assert_true(grounded > samples * 0.7, "seed %d: players grounded only %d of %d ticks" % [seed_value, grounded, samples])
func test_walking_up_to_a_summit_and_back_down() -> void:
# Head straight for the tallest summit from the plateau below it, then walk away.
var sim: Simulation = Simulation.new(21)
var id: int = sim.add_player()
var player: SimEntity = sim.entities.find(id)
var summit: Vector3 = sim.island.summits[0]
var start: Vector2 = Vector2(summit.x, summit.z) + Vector2(150.0, 0.0)
player.position = Vector3(start.x, sim.ground.terrain_height(start.x, start.y), start.y)
var lowest_start: float = player.position.y
var highest: float = player.position.y
for _tick: int in 60 * Tuning.TICK_RATE_HZ:
var towards: Vector2 = Vector2(summit.x - player.position.x, summit.z - player.position.z)
if towards.length() < 3.0:
break
var yaw: float = atan2(towards.x, towards.y)
sim.submit_command(id, PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), yaw, 0.0, PlayerCommand.BUTTON_SPRINT))
sim.step()
highest = maxf(highest, player.position.y)
assert_true(highest > lowest_start + 15.0,
"climbed only from %.1f to %.1f m towards a %.1f m summit" % [lowest_start, highest, summit.y])
assert_true(highest <= sim.island.max_height() + 0.01, "rose above the highest ground without jumping")
assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH, "walking the hills must not hurt")
+1
View File
@@ -0,0 +1 @@
uid://bcjg7fnxpwnju