W2: Procedural island generator

Island.generate(seed) builds a 513 x 513 heightfield (2 m spacing, the whole
1,024 m world) from the match seed's "worldgen" stream: a warped coastline,
a coastal shelf and interior dome, two to four summits joined by ridges,
rolling and rocky detail, and flattened marsh in wet lowland. Land is scaled
so the tallest summit lands between ISLAND_PEAK_MIN and ISLAND_PEAK_MAX,
under the last tide. Each sample gets an elevation band (sea, beach, marsh,
forest, highland, summit) for terrain materials.

- Simulation generates the island unless a test supplies its own ground,
  and spawns players on dry land until the drop arrives.
- The headless server logs world_hash in its start line.
- Island.heightmap_hash() is SHA-256 over millimetre heights and bands.
- tools/island_map.gd draws a top-down map with tide contours.
- New island constants in tuning.gd; GDD gains an island section.

Tests: a 100-seed sweep checks generation time (slowest 617 ms against
5 s), land area, at least two distinct high points, walkable land, bands,
and that no more than 3% of dry land is cut off at sea levels 0 and 8 m
(worst seen 0.87%). A separate server process given only the seed must
log the same heightmap hash.

Closes #9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 14:15:59 -05:00
co-authored by Claude Opus 5.5
parent f1ce780474
commit c70d0c1c4f
15 changed files with 658 additions and 5 deletions
+133
View File
@@ -0,0 +1,133 @@
## Measures a generated island for the worldgen tests: land area, how land splits up as
## the sea rises, and where the separate high points are. It reads every other
## heightfield sample (4 m apart), which is plenty for kilometre-scale questions.
class_name IslandSurvey
extends RefCounted
const STRIDE: int = 2
const NEIGHBOURS: Array[Vector2i] = [Vector2i(1, 0), Vector2i(-1, 0), Vector2i(0, 1), Vector2i(0, -1)]
var island: Island
var side: int = 0
var spacing: float = 0.0
var heights: PackedFloat32Array = PackedFloat32Array()
func _init(target: Island) -> void:
island = target
var ground: SimGround = target.ground
side = (ground.samples - 1) / STRIDE + 1
spacing = ground.cell * STRIDE
heights.resize(side * side)
for gz: int in side:
for gx: int in side:
heights[gz * side + gx] = ground.heights[gz * STRIDE * ground.samples + gx * STRIDE]
## Fraction of the world above `level`.
func land_fraction(level: float) -> float:
var count: int = 0
for value: float in heights:
if value > level:
count += 1
return float(count) / heights.size()
## How the land splits when the sea stands at `level`. Water floods inward from the
## world edge through every cell at or below the level; low ground the sea can't reach
## stays dry, as the GDD says. Returns the dry area, the largest connected dry piece,
## and the number of dry pieces.
func dry_land(level: float) -> Dictionary:
var flooded: PackedByteArray = PackedByteArray()
flooded.resize(side * side)
var queue: PackedInt32Array = PackedInt32Array()
for index: int in side:
for edge: int in [index, (side - 1) * side + index, index * side, index * side + side - 1]:
if heights[edge] <= level and flooded[edge] == 0:
flooded[edge] = 1
queue.append(edge)
_spread(queue, flooded, func(cell: int) -> bool: return heights[cell] <= level)
var seen: PackedByteArray = flooded.duplicate()
var total: int = 0
var largest: int = 0
var pieces: int = 0
for start: int in side * side:
if seen[start] != 0:
continue
seen[start] = 1
var piece: PackedInt32Array = PackedInt32Array([start])
var size: int = _spread(piece, seen, func(_cell: int) -> bool: return true)
total += size
largest = maxi(largest, size)
pieces += 1
return {"dry": total, "largest": largest, "pieces": pieces}
## Separate high points: cells that are the highest within `radius` metres and at least
## `min_height` high, each with a valley of at least `drop` metres between it and every
## higher peak (measured along the straight line between them).
func peaks(min_height: float, radius: float, drop: float) -> Array[Vector3]:
var reach: int = ceili(radius / spacing)
var found: Array[Vector3] = []
for gz: int in side:
for gx: int in side:
var height: float = heights[gz * side + gx]
if height < min_height or not _local_max(gx, gz, height, reach):
continue
found.append(Vector3(gx * spacing, height, gz * spacing))
found.sort_custom(func(a: Vector3, b: Vector3) -> bool: return a.y > b.y)
var distinct: Array[Vector3] = []
for peak: Vector3 in found:
var separate: bool = true
for higher: Vector3 in distinct:
if _lowest_between(peak, higher) > peak.y - drop:
separate = false
break
if separate:
distinct.append(peak)
return distinct
func _local_max(gx: int, gz: int, height: float, reach: int) -> bool:
for dz: int in range(-reach, reach + 1):
for dx: int in range(-reach, reach + 1):
var x: int = gx + dx
var z: int = gz + dz
if x < 0 or z < 0 or x >= side or z >= side or (dx == 0 and dz == 0):
continue
var other: float = heights[z * side + x]
# Ties go to the lower index, so a flat top yields one peak.
if other > height or (other == height and z * side + x < gz * side + gx):
return false
return true
func _lowest_between(a: Vector3, b: Vector3) -> float:
var lowest: float = INF
var steps: int = ceili(Vector2(a.x, a.z).distance_to(Vector2(b.x, b.z)) / spacing)
for step: int in steps + 1:
var point: Vector3 = a.lerp(b, float(step) / maxf(steps, 1))
lowest = minf(lowest, island.ground.terrain_height(point.x, point.z))
return lowest
## Flood fill from the cells in `queue`, marking `marks`, through cells `admit` accepts.
## Returns how many cells were reached, including the starting ones.
func _spread(queue: PackedInt32Array, marks: PackedByteArray, admit: Callable) -> int:
var head: int = 0
while head < queue.size():
var cell: int = queue[head]
head += 1
var x: int = cell % side
var z: int = cell / side
for step: Vector2i in NEIGHBOURS:
var nx: int = x + step.x
var nz: int = z + step.y
if nx < 0 or nz < 0 or nx >= side or nz >= side:
continue
var next: int = nz * side + nx
if marks[next] == 0 and admit.call(next):
marks[next] = 1
queue.append(next)
return queue.size()
+1
View File
@@ -0,0 +1 @@
uid://b82cq6vtir34x
+154
View File
@@ -0,0 +1,154 @@
extends TestCase
## The acceptance sweep from issue W2: every one of these seeds must make a good island.
const SWEEP_SEEDS: int = 100
const GENERATION_BUDGET_MSEC: int = 5000
## The sea level of the first flood line. Land must stay joined up to here.
const EARLY_TIDE_LEVELS: Array[float] = [0.0, 8.0]
## Dry land outside the main landmass may be at most this fraction: a few islets and
## sea stacks are fine, a second island is not.
const MAX_STRANDED_FRACTION: float = 0.03
const MIN_LAND_FRACTION: float = 0.30
const MAX_LAND_FRACTION: float = 0.70
## Distinct high points: at least this high, the highest within 80 m, and with a valley
## at least 6 m deep between each and any higher one.
const PEAK_MIN_HEIGHT: float = 35.0
const PEAK_RADIUS: float = 80.0
const PEAK_DROP: float = 6.0
const MIN_WALKABLE_LAND: float = 0.85
func test_same_seed_gives_the_same_heightmap() -> void:
var first: Island = Island.generate(777)
var second: Island = Island.generate(777)
assert_eq(first.heightmap_hash(), second.heightmap_hash())
assert_eq(first.heightmap_hash().length(), 64, "expected a SHA-256 hex digest")
assert_eq(first.summits, second.summits)
func test_different_seeds_give_different_islands() -> void:
assert_ne(Island.generate(777).heightmap_hash(), Island.generate(778).heightmap_hash())
func test_generation_does_not_touch_match_randomness() -> void:
# Worldgen uses its own copy of the "worldgen" stream, so generating the island on a
# client can never shift the server's gameplay rolls.
var sim: Simulation = Simulation.new(31337)
assert_eq(sim.rng.stream_names(), [] as Array[String])
assert_eq(sim.island.heightmap_hash(), Island.generate(31337).heightmap_hash())
func test_a_separate_server_process_builds_the_same_island() -> void:
# The same check a client makes on joining: an independent engine process given only
# the seed must arrive at the same heightmap.
var seed_value: int = 4_000_000_017
var output: Array = []
var args: PackedStringArray = PackedStringArray([
"--headless", "--path", ProjectSettings.globalize_path("res://"),
"--", "--server", "--seed=%d" % seed_value, "--ticks=1", "--unthrottled",
])
var code: int = OS.execute(OS.get_executable_path(), args, output, true)
assert_eq(code, 0, "server exited %d: %s" % [code, "\n".join(output)])
var world_hash: String = ""
for line: String in "\n".join(output).split("\n"):
if line.begins_with("{") and line.contains("\"event\":\"start\""):
world_hash = (JSON.parse_string(line) as Dictionary).get("world_hash", "")
assert_eq(world_hash, Island.generate(seed_value).heightmap_hash())
func test_bands_follow_height() -> void:
var island: Island = Island.generate(5)
var ground: SimGround = island.ground
for index: int in range(0, ground.heights.size(), 97):
var height: float = ground.heights[index]
var band: int = island.bands[index]
match band:
Island.Band.SEA:
assert_true(height <= 0.0, "sea at %.2f m" % height)
Island.Band.BEACH:
assert_true(height > 0.0 and height < Tuning.ISLAND_BEACH_TOP, "beach at %.2f m" % height)
Island.Band.MARSH:
assert_true(height < Tuning.ISLAND_MARSH_TOP, "marsh at %.2f m" % height)
Island.Band.FOREST:
assert_true(height < Tuning.ISLAND_FOREST_TOP, "forest at %.2f m" % height)
Island.Band.HIGHLAND:
assert_true(height >= Tuning.ISLAND_FOREST_TOP, "highland at %.2f m" % height)
Island.Band.SUMMIT:
assert_true(height >= Tuning.ISLAND_SUMMIT_BAND, "summit at %.2f m" % height)
assert_eq(island.band_at(-50.0, -50.0), Island.Band.SEA, "the world corner is open sea")
func test_players_spawn_on_dry_land() -> void:
var sim: Simulation = Simulation.new(2024)
for _index: int in Tuning.SOLO_PLAYERS:
var player: SimEntity = sim.entities.find(sim.add_player())
assert_true(player.position.y > Tuning.ISLAND_BEACH_TOP, "spawned at %s" % player.position)
func test_one_hundred_seeds_make_playable_islands() -> void:
var slowest: int = 0
var marsh_islands: int = 0
var worst_stranded: float = 0.0
var land_range: Vector2 = Vector2(INF, -INF)
var peak_counts: Dictionary = {}
for seed_value: int in range(1, SWEEP_SEEDS + 1):
var started: int = Time.get_ticks_msec()
var island: Island = Island.generate(seed_value)
var elapsed: int = Time.get_ticks_msec() - started
slowest = maxi(slowest, elapsed)
var label: String = "seed %d" % seed_value
assert_true(elapsed < GENERATION_BUDGET_MSEC, "%s took %d ms" % [label, elapsed])
var survey: IslandSurvey = IslandSurvey.new(island)
var land: float = survey.land_fraction(0.0)
assert_true(land >= MIN_LAND_FRACTION and land <= MAX_LAND_FRACTION,
"%s: land covers %.2f of the world" % [label, land])
var highest: float = island.max_height()
assert_true(highest >= Tuning.ISLAND_PEAK_MIN - 1.0 and highest < Tuning.ISLAND_MAX_HEIGHT,
"%s: highest ground %.1f m" % [label, highest])
var final_level: float = Tuning.TIDE_PHASES[-1]["level"]
assert_true(highest < final_level, "%s: the last tide must cover the island" % label)
for level: float in EARLY_TIDE_LEVELS:
var dry: Dictionary = survey.dry_land(level)
var stranded: float = 1.0 - float(dry["largest"]) / maxf(dry["dry"], 1.0)
worst_stranded = maxf(worst_stranded, stranded)
assert_true(stranded <= MAX_STRANDED_FRACTION,
"%s: at %.0f m, %.3f of dry land is cut off from the main landmass" % [label, level, stranded])
var peaks: Array[Vector3] = survey.peaks(PEAK_MIN_HEIGHT, PEAK_RADIUS, PEAK_DROP)
assert_true(peaks.size() >= 2, "%s: %d distinct high points" % [label, peaks.size()])
var walkable: float = _walkable_land(island)
assert_true(walkable >= MIN_WALKABLE_LAND, "%s: only %.2f of land is walkable" % [label, walkable])
var bands: Dictionary = {}
for band: int in island.bands:
bands[band] = true
for needed: int in [Island.Band.BEACH, Island.Band.FOREST, Island.Band.HIGHLAND, Island.Band.SUMMIT]:
assert_true(bands.has(needed), "%s lacks band %s" % [label, Island.Band.keys()[needed]])
if bands.has(Island.Band.MARSH):
marsh_islands += 1
land_range = Vector2(minf(land_range.x, land), maxf(land_range.y, land))
peak_counts[peaks.size()] = peak_counts.get(peaks.size(), 0) + 1
assert_true(marsh_islands >= SWEEP_SEEDS * 0.8, "only %d islands have marsh" % marsh_islands)
print(" island sweep: slowest %d ms, land %.2f to %.2f of the world, worst stranded %.4f," % [
slowest, land_range.x, land_range.y, worst_stranded])
print(" island sweep: islands by distinct high points %s, %d of %d with marsh" % [
peak_counts, marsh_islands, SWEEP_SEEDS])
func _walkable_land(island: Island) -> float:
var ground: SimGround = island.ground
var land: int = 0
var walkable: int = 0
for gz: int in range(0, ground.samples, 4):
for gx: int in range(0, ground.samples, 4):
var x: float = gx * ground.cell
var z: float = gz * ground.cell
if ground.terrain_height(x, z) <= 0.0:
continue
land += 1
if ground.walkable_terrain(x, z):
walkable += 1
return float(walkable) / maxf(land, 1.0)
+1
View File
@@ -0,0 +1 @@
uid://dgg1nqt68f2ei
+1 -1
View File
@@ -260,7 +260,7 @@ func test_same_commands_on_rough_ground_are_deterministic() -> void:
func _rough_simulation() -> Simulation:
var sim: Simulation = Simulation.new(4242)
var sim: Simulation = Simulation.new(4242, SimGround.flat())
var side: int = 65
var values: PackedFloat32Array = PackedFloat32Array()
values.resize(side * side)
+1 -1
View File
@@ -111,7 +111,7 @@ func test_simulation_needs_no_scene_tree() -> void:
func _simulation(match_seed: int, players: int) -> Simulation:
var sim: Simulation = Simulation.new(match_seed)
var sim: Simulation = Simulation.new(match_seed, SimGround.flat())
for _index: int in players:
sim.add_player()
return sim