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
+1
View File
@@ -24,6 +24,7 @@ continuity.
| `tools/godot.sh -- --server --seed=N --bots=N --ticks=N` | Runs a headless dedicated server. See `src/server/server_config.gd` for every option. Logs are JSON lines carrying the seed. Exit codes: 0 clean, 1 script error, 2 bad command line. | | `tools/godot.sh -- --server --seed=N --bots=N --ticks=N` | Runs a headless dedicated server. See `src/server/server_config.gd` for every option. Logs are JSON lines carrying the seed. Exit codes: 0 clean, 1 script error, 2 bad command line. |
| `tools/godot.sh ...` | Runs the pinned engine. Headless by default. | | `tools/godot.sh ...` | Runs the pinned engine. Headless by default. |
| `tools/capture.sh <scene-or-scenario> <out.png>` | Renders the real client offscreen in a throwaway `tidewall-capture-*` Docker container (Xvfb, Mesa software rendering) and saves a PNG. Fails on a blank frame or a renderer fallback. | | `tools/capture.sh <scene-or-scenario> <out.png>` | Renders the real client offscreen in a throwaway `tidewall-capture-*` Docker container (Xvfb, Mesa software rendering) and saves a PNG. Fails on a blank frame or a renderer fallback. |
| `tools/godot.sh --script res://tools/island_map.gd -- --seed=N --out=res://captures/island.png` | Draws a top-down map of a seed's island, with a contour at each tide level. |
| `make capture-test` | Proves the capture harness works and rejects a blank frame. Needs Docker, so it isn't part of `make check`. | | `make capture-test` | Proves the capture harness works and rejects a blank frame. Needs Docker, so it isn't part of `make check`. |
Run one group of tests with `tools/run_tests.sh --root=res://test/sim` or Run one group of tests with `tools/run_tests.sh --root=res://test/sim` or
+23
View File
@@ -43,6 +43,29 @@ name, so it can't drift from the game. To change a number, edit that file.
Bots fill empty slots. Offline play is a local server filled with bots, the same game Bots fill empty slots. Offline play is a local server filled with bots, the same game
code as online play. A downed duo partner can be revived, within `REVIVE_SECONDS`. code as online play. A downed duo partner can be revived, within `REVIVE_SECONDS`.
## The island
Every match is a new island, generated from the match seed by
[`src/sim/island.gd`](../src/sim/island.gd). The server and every client build it from the
seed alone, and compare `Island.heightmap_hash()`, so terrain is never sent.
- About a kilometre across (`ISLAND_RADIUS_METRES`), in the `WORLD_SIZE_METRES` square,
with open sea all round for the packet ship's approach.
- Elevation bands suit the tide: beach up to `ISLAND_BEACH_TOP`, wet flat marsh up to
`ISLAND_MARSH_TOP`, forest up to `ISLAND_FOREST_TOP`, then highland, and summit ground
from `ISLAND_SUMMIT_BAND`.
- Land rises from the coast over a broad dome, so each tide phase takes a ring of the
island rather than all the low ground at once.
- Two to four summits (`ISLAND_MIN_SUMMITS`, `ISLAND_MAX_SUMMITS`), at least
`ISLAND_SUMMIT_SPACING_METRES` apart and joined by lower ridges. The tallest stands
between `ISLAND_PEAK_MIN` and `ISLAND_PEAK_MAX`, always below `ISLAND_MAX_HEIGHT`, so the
last tide covers it. Late fights happen on several hills, not one.
- The worldgen test sweeps 100 seeds: land covers 30 to 70% of the world, at least two
distinct high points, 85% of land walkable, and no more than 3% of dry land cut off
from the main landmass at the first two sea levels.
`tools/island_map.gd` draws a top-down map of any seed, with a contour at each tide level.
## Tide phases ## Tide phases
`TIDE_PHASES` is an ordered list of phases. Each one sets: `TIDE_PHASES` is an ordered list of phases. Each one sets:
+1
View File
@@ -43,6 +43,7 @@ func _ready() -> void:
var started: Dictionary = config.to_dictionary() var started: Dictionary = config.to_dictionary()
started["engine"] = Engine.get_version_info()["string"] started["engine"] = Engine.get_version_info()["string"]
started["tick_rate_hz"] = Tuning.TICK_RATE_HZ started["tick_rate_hz"] = Tuning.TICK_RATE_HZ
started["world_hash"] = loop.sim.island.heightmap_hash()
started["listening"] = false started["listening"] = false
started["note"] = "networking arrives in v0.5; players join as idle slots until then" started["note"] = "networking arrives in v0.5; players join as idle slots until then"
_log("start", started) _log("start", started)
+250
View File
@@ -0,0 +1,250 @@
## The procedural island. One seed gives one island, on the server and on every client,
## so terrain is never sent over the network: both ends call `Island.generate(seed)`.
##
## The island is built in layers, each a pure function of the seed:
## 1. a warped coastline around the world centre, falling to the sea floor outside it;
## 2. a raised interior plateau that keeps land joined through the early tide;
## 3. two to four summits, joined by ridges, which become the last dry ground;
## 4. rolling detail, rocky highland detail, and flattened marsh in wet lowland.
## Then the land is scaled so the tallest summit lands in the tuned peak range.
##
## All randomness comes from the match seed's "worldgen" stream. FastNoiseLite is a
## seeded, pure function in the engine core with no rendering dependency.
class_name Island
extends RefCounted
enum Band { SEA, BEACH, MARSH, FOREST, HIGHLAND, SUMMIT }
## Height of the coastal shelf the land rises to, before detail and summits, in metres.
const PLATEAU_HEIGHT: float = 11.0
## Extra height of a broad dome over the interior, so each tide phase takes a ring of
## land rather than the whole plateau at once.
const DOME_HEIGHT: float = 16.0
## Fraction of the radius, measured inward from the coast, over which land rises to the plateau.
const COAST_RISE: float = 0.32
## How far the coastline is pushed in or out, as a fraction of the radius.
const COAST_WARP: float = 0.22
const DETAIL_METRES: float = 6.5
const ROCK_METRES: float = 7.0
const RIDGE_FRACTION: float = 0.55
const MARSH_LEVEL: float = 3.6
## Moisture above this turns wet lowland into marsh.
const MARSH_MOISTURE: float = 0.05
var match_seed: int = 0
var ground: SimGround
## Elevation band per heightfield sample, same layout as `ground.heights`.
var bands: PackedByteArray = PackedByteArray()
## The summit centres the generator placed, as (x, height, z), tallest first.
var summits: Array[Vector3] = []
## Wall-clock generation time is measured by callers; the island never reads a clock.
## Builds the island for `seed_value`.
static func generate(seed_value: int) -> Island:
var island: Island = Island.new()
island.match_seed = seed_value
island._build()
return island
## SHA-256 hex digest of the heightfield, heights rounded to millimetres. Two machines
## that agree on this agree on every walkable surface.
func heightmap_hash() -> String:
var buffer: StreamPeerBuffer = StreamPeerBuffer.new()
buffer.big_endian = false
buffer.put_32(ground.samples)
buffer.put_32(roundi(ground.cell * 1000.0))
for value: float in ground.heights:
buffer.put_32(roundi(value * 1000.0))
buffer.put_data(bands)
var hasher: HashingContext = HashingContext.new()
hasher.start(HashingContext.HASH_SHA256)
hasher.update(buffer.data_array)
return hasher.finish().hex_encode()
## The elevation band at world position (x, z), from the nearest sample.
func band_at(x: float, z: float) -> Band:
var limit: int = ground.samples - 1
var gx: int = clampi(roundi(x / ground.cell), 0, limit)
var gz: int = clampi(roundi(z / ground.cell), 0, limit)
return bands[gz * ground.samples + gx] as Band
## The highest terrain sample, in metres.
func max_height() -> float:
var best: float = -INF
for value: float in ground.heights:
best = maxf(best, value)
return best
func _build() -> void:
var rng: RandomNumberGenerator = SimRng.new(match_seed).stream("worldgen")
var size: float = Tuning.WORLD_SIZE_METRES
var cell: float = Tuning.ISLAND_GRID_METRES
var side: int = roundi(size / cell) + 1
var centre: Vector2 = Vector2(size, size) * 0.5
var radius: float = Tuning.ISLAND_RADIUS_METRES
var coast: FastNoiseLite = _noise(rng.randi(), 1.0 / 260.0, 3)
var detail: FastNoiseLite = _noise(rng.randi(), 1.0 / 170.0, 4)
var rock: FastNoiseLite = _noise(rng.randi(), 1.0 / 60.0, 3)
rock.fractal_type = FastNoiseLite.FRACTAL_RIDGED
var moisture: FastNoiseLite = _noise(rng.randi(), 1.0 / 200.0, 2)
var peaks: Array[Dictionary] = _place_summits(rng, centre, radius)
var ridges: Array[Dictionary] = _link_summits(peaks)
var heights: PackedFloat32Array = PackedFloat32Array()
heights.resize(side * side)
var wet: PackedFloat32Array = PackedFloat32Array()
wet.resize(side * side)
for gz: int in side:
var z: float = gz * cell
for gx: int in side:
var x: float = gx * cell
var index: int = gz * side + gx
var offset: Vector2 = Vector2(x, z) - centre
# Inland is 0 at the coast, 1 at the centre, negative out to sea.
var inland: float = 1.0 - offset.length() / radius + COAST_WARP * coast.get_noise_2d(x, z)
if inland <= 0.0:
heights[index] = -Tuning.ISLAND_SEA_DEPTH * clampf(-inland / 0.12, 0.0, 1.0) - 0.4
continue
var rise: float = _smooth(0.0, COAST_RISE, inland)
var height: float = PLATEAU_HEIGHT * rise + DOME_HEIGHT * _smooth(0.15, 1.1, inland) + 0.6
var raise: float = 0.0
for peak: Dictionary in peaks:
var reach: float = Vector2(x, z).distance_squared_to(peak["at"]) / pow(peak["radius"], 2.0)
raise = maxf(raise, peak["height"] * exp(-1.6 * reach))
for ridge: Dictionary in ridges:
var gap: float = _distance_to_segment(Vector2(x, z), ridge["from"], ridge["to"])
raise = maxf(raise, ridge["height"] * exp(-pow(gap / ridge["width"], 2.0)))
var inner: float = _smooth(0.08, 0.45, inland)
height += raise * inner
height += DETAIL_METRES * detail.get_noise_2d(x, z) * rise
# Rock grows with altitude, so highlands are craggy and lowlands rolling.
var altitude: float = clampf((height - PLATEAU_HEIGHT - DOME_HEIGHT) / 28.0, 0.0, 1.0)
height += ROCK_METRES * (rock.get_noise_2d(x, z) + 0.3) * altitude
heights[index] = height
wet[index] = moisture.get_noise_2d(x, z)
_scale_to_peak(heights, rng)
var band_data: PackedByteArray = PackedByteArray()
band_data.resize(side * side)
for index: int in heights.size():
var height: float = heights[index]
if height > 0.0 and height < Tuning.ISLAND_MARSH_TOP + 1.5 and wet[index] > MARSH_MOISTURE:
# Flatten wet lowland towards a marsh level just above the beach.
var weight: float = _smooth(MARSH_MOISTURE, MARSH_MOISTURE + 0.25, wet[index])
weight *= 1.0 - _smooth(Tuning.ISLAND_MARSH_TOP - 1.0, Tuning.ISLAND_MARSH_TOP + 1.5, height)
height = lerpf(height, maxf(MARSH_LEVEL, Tuning.ISLAND_BEACH_TOP + 0.3), weight)
heights[index] = height
band_data[index] = _classify(height, wet[index])
ground = SimGround.from_heights(heights, side, cell)
bands = band_data
for peak: Dictionary in peaks:
var at: Vector2 = peak["at"]
summits.append(Vector3(at.x, ground.terrain_height(at.x, at.y), at.y))
summits.sort_custom(func(a: Vector3, b: Vector3) -> bool: return a.y > b.y)
func _noise(noise_seed: int, frequency: float, octaves: int) -> FastNoiseLite:
var noise: FastNoiseLite = FastNoiseLite.new()
noise.noise_type = FastNoiseLite.TYPE_SIMPLEX_SMOOTH
noise.seed = noise_seed & 0x7FFFFFFF
noise.frequency = frequency
noise.fractal_type = FastNoiseLite.FRACTAL_FBM
noise.fractal_octaves = octaves
return noise
## Picks summit centres well inside the coast and far enough apart. The first is the
## tallest. Heights here are before scaling to the peak range.
func _place_summits(rng: RandomNumberGenerator, centre: Vector2, radius: float) -> Array[Dictionary]:
var count: int = rng.randi_range(Tuning.ISLAND_MIN_SUMMITS, Tuning.ISLAND_MAX_SUMMITS)
var peaks: Array[Dictionary] = []
var spacing: float = Tuning.ISLAND_SUMMIT_SPACING_METRES
var attempts: int = 0
while peaks.size() < count and attempts < 400:
attempts += 1
# Relax the spacing slowly if the island can't fit them all.
var needed: float = spacing * (1.0 - 0.3 * attempts / 400.0)
var angle: float = rng.randf() * TAU
var distance: float = radius * rng.randf_range(0.12, 0.55)
var at: Vector2 = centre + Vector2(cos(angle), sin(angle)) * distance
var clear: bool = true
for peak: Dictionary in peaks:
if at.distance_to(peak["at"]) < needed:
clear = false
break
if not clear:
continue
var height: float = 46.0 if peaks.is_empty() else rng.randf_range(30.0, 42.0)
peaks.append({"at": at, "height": height, "radius": rng.randf_range(95.0, 145.0)})
return peaks
## Joins each summit to its nearest neighbour with a lower ridge, giving highland spines.
func _link_summits(peaks: Array[Dictionary]) -> Array[Dictionary]:
var ridges: Array[Dictionary] = []
var linked: Dictionary = {}
for index: int in peaks.size():
var nearest: int = -1
var best: float = INF
for other: int in peaks.size():
var gap: float = (peaks[index]["at"] as Vector2).distance_to(peaks[other]["at"])
if other != index and gap < best:
best = gap
nearest = other
if nearest < 0:
continue
var key: Vector2i = Vector2i(mini(index, nearest), maxi(index, nearest))
if linked.has(key):
continue
linked[key] = true
var low: float = minf(peaks[index]["height"], peaks[nearest]["height"])
ridges.append({
"from": peaks[index]["at"], "to": peaks[nearest]["at"],
"height": low * RIDGE_FRACTION, "width": 50.0,
})
return ridges
## Scales land heights so the tallest point lands in the tuned peak range. The sea
## floor is left alone, so the coastline doesn't move.
func _scale_to_peak(heights: PackedFloat32Array, rng: RandomNumberGenerator) -> void:
var highest: float = 0.0
for value: float in heights:
highest = maxf(highest, value)
var target: float = rng.randf_range(Tuning.ISLAND_PEAK_MIN, Tuning.ISLAND_PEAK_MAX)
var factor: float = target / highest
for index: int in heights.size():
if heights[index] > 0.0:
heights[index] *= factor
func _classify(height: float, wetness: float) -> int:
if height <= 0.0:
return Band.SEA
if height < Tuning.ISLAND_BEACH_TOP:
return Band.BEACH
if height < Tuning.ISLAND_MARSH_TOP and wetness > MARSH_MOISTURE:
return Band.MARSH
if height < Tuning.ISLAND_FOREST_TOP:
return Band.FOREST
if height < Tuning.ISLAND_SUMMIT_BAND:
return Band.HIGHLAND
return Band.SUMMIT
static func _smooth(from: float, to: float, value: float) -> float:
return smoothstep(from, to, value)
static func _distance_to_segment(point: Vector2, from: Vector2, to: Vector2) -> float:
var span: Vector2 = to - from
var t: float = clampf((point - from).dot(span) / maxf(span.length_squared(), 0.0001), 0.0, 1.0)
return point.distance_to(from + span * t)
+1
View File
@@ -0,0 +1 @@
uid://kdm40yq5wyhl
+18 -3
View File
@@ -6,12 +6,15 @@ class_name Simulation
extends RefCounted extends RefCounted
const SECONDS_PER_TICK: float = 1.0 / Tuning.TICK_RATE_HZ const SECONDS_PER_TICK: float = 1.0 / Tuning.TICK_RATE_HZ
const SPAWN_ATTEMPTS: int = 64
var tick: int = 0 var tick: int = 0
var entities: EntityRegistry = EntityRegistry.new() var entities: EntityRegistry = EntityRegistry.new()
var rng: SimRng var rng: SimRng
## Terrain and solids. Flat until the island generator provides a heightfield. ## Terrain and solids. The island's heightfield unless a test supplied its own ground.
var ground: SimGround = SimGround.flat(0.0) var ground: SimGround
## The generated island, or null when a test supplied its own ground.
var island: Island
## Player entity ID -> { command tick -> PlayerCommand } ## Player entity ID -> { command tick -> PlayerCommand }
var _pending: Dictionary = {} var _pending: Dictionary = {}
@@ -19,8 +22,14 @@ var _pending: Dictionary = {}
var _players: Array[int] = [] var _players: Array[int] = []
func _init(match_seed: int) -> void: ## Generates the island from the seed, unless `world` is given. Tests that don't care
## about terrain pass `SimGround.flat()` to skip worldgen.
func _init(match_seed: int, world: SimGround = null) -> void:
rng = SimRng.new(match_seed) rng = SimRng.new(match_seed)
if world == null:
island = Island.generate(match_seed)
world = island.ground
ground = world
## Adds a player at a seeded spawn position and returns its entity ID. ## Adds a player at a seeded spawn position and returns its entity ID.
@@ -30,6 +39,12 @@ func add_player() -> int:
var size: float = Tuning.WORLD_SIZE_METRES var size: float = Tuning.WORLD_SIZE_METRES
var x: float = spawn.randf() * size var x: float = spawn.randf() * size
var z: float = spawn.randf() * size var z: float = spawn.randf() * size
# Until the drop arrives (W7), spawn on dry land above the beach when there is any.
for _attempt: int in SPAWN_ATTEMPTS:
if ground.terrain_height(x, z) > Tuning.ISLAND_BEACH_TOP:
break
x = spawn.randf() * size
z = spawn.randf() * size
player.position = Vector3(x, ground.terrain_height(x, z), z) player.position = Vector3(x, ground.terrain_height(x, z), z)
player.on_ground = true player.on_ground = true
player.health = Tuning.PLAYER_MAX_HEALTH player.health = Tuning.PLAYER_MAX_HEALTH
+23
View File
@@ -49,6 +49,29 @@ const CROUCH_HEIGHT: float = 1.2
const FALL_DAMAGE_SAFE_METRES: float = 6.0 const FALL_DAMAGE_SAFE_METRES: float = 6.0
const FALL_DAMAGE_PER_METRE: float = 8.0 const FALL_DAMAGE_PER_METRE: float = 8.0
# The island. Worldgen fills the whole world square; the island is about a kilometre
# across, sized for 24 players. Heights are metres above the starting sea level.
## Spacing of the terrain heightfield, in metres. The grid covers WORLD_SIZE_METRES.
const ISLAND_GRID_METRES: float = 2.0
## Mean distance from the world centre to the coast, before the coastline is warped.
const ISLAND_RADIUS_METRES: float = 400.0
const ISLAND_MIN_SUMMITS: int = 2
const ISLAND_MAX_SUMMITS: int = 4
## Summits are at least this far apart, so each one is a separate fight.
const ISLAND_SUMMIT_SPACING_METRES: float = 220.0
## The tallest summit lands between these heights. Both stay under ISLAND_MAX_HEIGHT.
const ISLAND_PEAK_MIN: float = 58.0
const ISLAND_PEAK_MAX: float = 67.0
## The open sea floor, in metres below the starting sea.
const ISLAND_SEA_DEPTH: float = 12.0
## Elevation bands, by height above the starting sea. Marsh is wet flat ground below
## ISLAND_MARSH_TOP; land from there up to ISLAND_FOREST_TOP is forest, then highland,
## and anything at or above ISLAND_SUMMIT_BAND is summit ground.
const ISLAND_BEACH_TOP: float = 2.5
const ISLAND_MARSH_TOP: float = 7.0
const ISLAND_FOREST_TOP: float = 32.0
const ISLAND_SUMMIT_BAND: float = 50.0
# The tide. `hold` and `rise` are seconds, `level` is metres above the starting sea, # The tide. `hold` and `rise` are seconds, `level` is metres above the starting sea,
# `drown_dps` is damage per second underwater once breath runs out. The last level # `drown_dps` is damage per second underwater once breath runs out. The last level
# must exceed ISLAND_MAX_HEIGHT, so that every match ends. # must exceed ISLAND_MAX_HEIGHT, so that every match ends.
+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: func _rough_simulation() -> Simulation:
var sim: Simulation = Simulation.new(4242) var sim: Simulation = Simulation.new(4242, SimGround.flat())
var side: int = 65 var side: int = 65
var values: PackedFloat32Array = PackedFloat32Array() var values: PackedFloat32Array = PackedFloat32Array()
values.resize(side * side) 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: 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: for _index: int in players:
sim.add_player() sim.add_player()
return sim return sim
+49
View File
@@ -0,0 +1,49 @@
## Writes a top-down map of an island: band colours with hillshading and a contour line
## at each tide phase's sea level. For eyeballing worldgen, not for the game.
##
## tools/godot.sh --script res://tools/island_map.gd -- --seed=N --out=path.png
extends SceneTree
const COLOURS: Dictionary = {
Island.Band.SEA: Color(0.16, 0.29, 0.36),
Island.Band.BEACH: Color(0.82, 0.74, 0.55),
Island.Band.MARSH: Color(0.42, 0.47, 0.30),
Island.Band.FOREST: Color(0.27, 0.40, 0.22),
Island.Band.HIGHLAND: Color(0.50, 0.46, 0.38),
Island.Band.SUMMIT: Color(0.80, 0.78, 0.74),
}
func _init() -> void:
var seed_value: int = 1
var out: String = "res://captures/island.png"
for arg: String in OS.get_cmdline_user_args():
if arg.begins_with("--seed="):
seed_value = arg.get_slice("=", 1).to_int()
elif arg.begins_with("--out="):
out = arg.get_slice("=", 1)
var island: Island = Island.generate(seed_value)
var ground: SimGround = island.ground
var side: int = ground.samples
var image: Image = Image.create(side, side, false, Image.FORMAT_RGB8)
var light: Vector3 = Vector3(-1.0, 1.4, -1.0).normalized()
for gz: int in side:
for gx: int in side:
var x: float = gx * ground.cell
var z: float = gz * ground.cell
var height: float = ground.heights[gz * side + gx]
var colour: Color = COLOURS[island.bands[gz * side + gx]]
if height > 0.0:
var shade: float = clampf(ground.terrain_normal(x, z).dot(light), 0.0, 1.0)
colour = colour * (0.55 + 0.6 * shade)
for phase: Dictionary in Tuning.TIDE_PHASES:
if absf(height - float(phase["level"])) < 0.25:
colour = colour.darkened(0.45)
else:
colour = colour.lightened(clampf((height + 3.0) / 3.0, 0.0, 0.5))
image.set_pixel(gx, gz, colour)
DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(out).get_base_dir())
image.save_png(out)
print("seed %d -> %s, max %.1f m, %d summits, hash %s" % [
seed_value, out, island.max_height(), island.summits.size(), island.heightmap_hash()])
quit()
+1
View File
@@ -0,0 +1 @@
uid://cs6ogqpabax4i