diff --git a/docs/GDD.md b/docs/GDD.md index 2e024ed..fc7f12f 100644 --- a/docs/GDD.md +++ b/docs/GDD.md @@ -143,6 +143,32 @@ sky barge or the packet ship and mortar of the core loop above, are open in #72. - `level`: the sea height in metres at the end of the rise; - `drown_dps`: damage per second to anyone in water above their head. +The tide starts with the drop. Each island plans its own levels from its terrain +(`SafeGround`): a phase's table level is lowered, if it must be, to +`TIDE_SAFE_MARGIN_METRES` under the top of the largest piece of land still dry when the +phase begins, while every phase still rises at least `TIDE_MIN_RISE_METRES`. So safe +ground never vanishes from under the main landmass early. The island sweep checks, over +100 seeds, that every phase that leaves land leaves it within reach of the whole main +landmass on foot within the phase's hold and rise. + +**Flooding.** Water only reaches ground it can flow to ([`src/sim/flood.gd`](../src/sim/flood.gd)): +from the world's edge, across 4 m cells whose lowest ground is under the sea, and over +cell edges no breakwater seals. Low ground cut off by higher land or a breakwater ring +stays dry until the sea overtops what holds it back or a breakwater breaks. Then the +water pours in and the cut-off ground fills at `BREACH_FLOW_METRES_PER_SECOND` until it +is level with the sea. Water never drains. Players, drowning and the wear on pieces all +use the water where they are, not the sea level. + +**Storm surges.** When a phase's rise begins, its `surge` damage hits once every built +piece whose base is less than `TIDE_SURGE_HEIGHT_METRES` above the water that reaches it. + +**Sudden death.** When the last rise ends, everyone still standing loses +`TIDE_SUDDEN_DEATH_DPS` health a second, armor or not. After +`TIDE_SUDDEN_DEATH_SECONDS` the match ends whatever happens. If several players are still +standing then, or the last ones fall on the same tick, the winner is the one with the most +health, then the highest feet, then the earliest to join. So every match has a winner +within the tide's total time plus sudden death. + The last phase raises the sea above the highest ground, so every match ends. Players standing in shallow water wade and slow down. Underwater, they lose breath over `BREATH_SECONDS`, and then take the phase's `drown_dps`. Swimming is slow and leaves a diff --git a/src/sim/flood.gd b/src/sim/flood.gd new file mode 100644 index 0000000..8602100 --- /dev/null +++ b/src/sim/flood.gd @@ -0,0 +1,281 @@ +## Where the sea actually is. The tide sets one sea level, but water only reaches ground +## it can flow to: from the world's edge, through cells whose lowest ground is under the +## sea, and across cell edges that no breakwater seals. Low ground cut off by higher +## land or by a breakwater ring stays dry until the sea overtops what holds it back, or +## a breakwater breaks. Then the water pours in, and the newly reached cells fill at +## Tuning.BREACH_FLOW_METRES_PER_SECOND until they stand level with the sea. +## +## The grid's cells are Tuning.FLOOD_CELL_METRES square and line up with the building +## grid, so breakwaters stand exactly on cell edges. A cell's floor is the lowest terrain +## in it. Water never drains: once a cell is flooded it stays flooded. +## +## Updating is incremental. The flood remembers every edge where it was stopped, and +## re-tests only those when the sea rises or breakwaters change. +class_name Flood +extends RefCounted + +## level_at() for a cell the sea doesn't reach. +const NO_WATER: float = -1000.0 +## No breakwater stack yet on an edge, while reading barriers. +const NO_STACK: int = -1000000 +## Neighbour steps by direction: +x, -x, +z, -z. +const STEPS: Array[Vector2i] = [Vector2i(1, 0), Vector2i(-1, 0), Vector2i(0, 1), Vector2i(0, -1)] + +var side: int = 0 +var cell: float = Tuning.FLOOD_CELL_METRES +## Per cell: lowest terrain, flooded (1) or not, and the filling group it belongs to (-1 +## once it stands level with the sea). +var floors: PackedFloat32Array = PackedFloat32Array() +var flooded: PackedByteArray = PackedByteArray() +var fill_group: PackedInt32Array = PackedInt32Array() +## The sea level the flood was last spread for. +var sea_level: float = Tuning.SEA_LEVEL_START + +## Filling groups: group ID -> {"level": float, "cells": PackedInt32Array}. +var _groups: Dictionary = {} +var _next_group: int = 0 +## Edges the water was stopped at, as cell * 4 + direction, in the order found. +var _blocked: Dictionary = {} +## Sealed edges: edge key -> height of the breakwater top. See edge_key(). +var _barriers: Dictionary = {} +## StructureSet next ID and piece count when barriers were last read. +var _structures_seen: Vector2i = Vector2i(-1, -1) + + +## Builds the flood grid over `ground` and floods everything the starting sea reaches. +static func create(ground: SimGround, level: float = Tuning.SEA_LEVEL_START) -> Flood: + var flood: Flood = Flood.new() + flood.side = ceili(Tuning.WORLD_SIZE_METRES / flood.cell) + var count: int = flood.side * flood.side + flood.floors.resize(count) + flood.flooded.resize(count) + flood.fill_group.resize(count) + flood.fill_group.fill(-1) + var per_cell: int = roundi(flood.cell / ground.cell) + var direct: bool = is_equal_approx(per_cell * ground.cell, flood.cell) and (flood.side * per_cell) < ground.samples + for cz: int in flood.side: + for cx: int in flood.side: + var lowest: float = INF + if direct: + # Read the heightfield samples in and around the cell straight from the array. + for gz: int in range(cz * per_cell, cz * per_cell + per_cell + 1): + var row: int = gz * ground.samples + for gx: int in range(cx * per_cell, cx * per_cell + per_cell + 1): + lowest = minf(lowest, ground.heights[row + gx]) + else: + for sz: int in 3: + for sx: int in 3: + lowest = minf(lowest, ground.terrain_height((cx + sx * 0.5) * flood.cell, (cz + sz * 0.5) * flood.cell)) + flood.floors[cz * flood.side + cx] = lowest + flood.sea_level = level + # The open sea: every border cell under the starting level, filled at once. + var start: PackedInt32Array = PackedInt32Array() + for index: int in flood.side: + for border: int in [index, (flood.side - 1) * flood.side + index, index * flood.side, index * flood.side + flood.side - 1]: + if flood.flooded[border] == 0 and flood.floors[border] < level: + flood.flooded[border] = 1 + start.append(border) + flood._spread(start) + return flood + + +## The flood cell under a world point. +func cell_of(x: float, z: float) -> int: + var cx: int = clampi(floori(x / cell), 0, side - 1) + var cz: int = clampi(floori(z / cell), 0, side - 1) + return cz * side + cx + + +## Height of the water surface over the cell at a world point, or NO_WATER if the sea +## doesn't reach it. May be below the ground while a breached basin is still filling. +func level_at(x: float, z: float) -> float: + return level_of_cell(cell_of(x, z)) + + +func level_of_cell(index: int) -> float: + if flooded[index] == 0: + return NO_WATER + var group: int = fill_group[index] + if group >= 0: + return minf(float(_groups[group]["level"]), sea_level) + return sea_level + + +func is_flooded(x: float, z: float) -> bool: + return flooded[cell_of(x, z)] != 0 + + +## Number of flooded cells. +func flooded_count() -> int: + return flooded.count(1) + + +## Key of the edge between cell (cx - 1, cz) and (cx, cz) for axis 0, or (cx, cz - 1) and +## (cx, cz) for axis 1. The same numbering as StructureSet's wall slots. +func edge_key(cx: int, cz: int, axis: int) -> int: + return (cz * side + cx) * 2 + axis + + +## The top of the breakwater sealing the edge between neighbouring cells, or -INF. +func barrier_between(a: int, b: int) -> float: + var ax: int = a % side + var bx: int = b % side + var key: int + if ax != bx: + key = edge_key(maxi(ax, bx), a / side, 0) + else: + key = edge_key(ax, maxi(a / side, b / side), 1) + return float(_barriers.get(key, -INF)) + + +## Reads breakwaters from `structures` if it changed since last time. Returns true if +## it did. +func refresh_barriers(structures: StructureSet) -> bool: + var seen: Vector2i = Vector2i(structures.next_id(), structures.count()) + if seen == _structures_seen: + return false + _structures_seen = seen + # Breakwater levels by edge, then each edge's sealed height: a stack of breakwaters + # from the ground up (the lowest may hang one level over lower ground, as its skirt + # fills the gap), each starting no higher than the one under it ends. + var levels: Dictionary = {} + for piece: StructureSet.Piece in structures.pieces.values(): + if piece.kind != StructureSet.BREAKWATER: + continue + var axis: int = 0 if piece.slot.w == StructureSet.SLOT_WALL_X else 1 + if piece.slot.x < 0 or piece.slot.z < 0 or piece.slot.x >= side or piece.slot.z >= side: + continue + var key: int = edge_key(piece.slot.x, piece.slot.z, axis) + if not levels.has(key): + levels[key] = PackedInt32Array() + levels[key].append(piece.slot.y) + _barriers.clear() + var piece_levels: int = roundi(Tuning.GRID_CELL_METRES / Tuning.BUILD_LEVEL_METRES) + for key: int in levels: + var stack: PackedInt32Array = levels[key] + stack.sort() + var index: int = key / 2 + var cx: int = index % side + var cz: int = index / side + var other: int = (index - 1) if key % 2 == 0 else (index - side) + if (key % 2 == 0 and cx == 0) or (key % 2 == 1 and cz == 0): + continue + var edge_floor: float = maxf(floors[index], floors[other]) + var top_level: int = NO_STACK + for level: int in stack: + if top_level == NO_STACK: + if level * Tuning.BUILD_LEVEL_METRES > edge_floor + Tuning.BUILD_LEVEL_METRES: + break + top_level = level + piece_levels + elif level <= top_level: + top_level = maxi(top_level, level + piece_levels) + else: + break + if top_level != NO_STACK: + _barriers[key] = top_level * Tuning.BUILD_LEVEL_METRES + return true + + +## Spreads the water for a new sea level and the current breakwaters, and advances +## filling basins by `seconds` of flow. Returns how many cells newly flooded. +func update(level: float, structures: StructureSet, seconds: float) -> int: + sea_level = level + if structures != null: + refresh_barriers(structures) + var reached: int = 0 + var edges: Array = _blocked.keys() + for key: int in edges: + if not _blocked.has(key): + continue + var from: int = key / 4 + var to: int = _neighbour(from, key % 4) + if flooded[to] != 0: + _blocked.erase(key) + continue + if _passable(from, to): + _blocked.erase(key) + reached += _pour(to) + _advance_groups(seconds) + return reached + + +## Follows the sea level and advances filling basins, without re-spreading. Cheap +## enough for every tick. +func flow(level: float, seconds: float) -> void: + sea_level = level + _advance_groups(seconds) + + +## Writes the flooded cells, filling groups and barriers, for Simulation.state_hash(). +func write_state(buffer: StreamPeerBuffer) -> void: + buffer.put_64(roundi(sea_level * 1000.0)) + buffer.put_data(flooded) + buffer.put_64(_groups.size()) + for group: int in _groups: + buffer.put_32(group) + buffer.put_64(roundi(float(_groups[group]["level"]) * 1000.0)) + buffer.put_64(_barriers.size()) + + +func _neighbour(index: int, direction: int) -> int: + var step: Vector2i = STEPS[direction] + var x: int = index % side + step.x + var z: int = index / side + step.y + if x < 0 or z < 0 or x >= side or z >= side: + return -1 + return z * side + x + + +func _passable(from: int, to: int) -> bool: + return floors[to] < sea_level and barrier_between(from, to) < sea_level + + +## Water pours across an edge into `to`, and on through everything it can reach. The +## reached cells fill together, from their lowest floor up. +func _pour(to: int) -> int: + flooded[to] = 1 + var queue: PackedInt32Array = PackedInt32Array([to]) + _spread(queue) + var group: int = _next_group + _next_group += 1 + var bottom: float = INF + for index: int in queue: + bottom = minf(bottom, floors[index]) + _groups[group] = {"level": bottom, "cells": queue} + for index: int in queue: + fill_group[index] = group + return queue.size() + + +## Breadth-first flood from the cells in `queue`, which must already be marked flooded. +## Appends every newly flooded cell to `queue` and records where the water stopped. +func _spread(queue: PackedInt32Array) -> void: + var head: int = 0 + while head < queue.size(): + var index: int = queue[head] + head += 1 + for direction: int in 4: + var next: int = _neighbour(index, direction) + if next < 0 or flooded[next] != 0: + continue + if _passable(index, next): + flooded[next] = 1 + queue.append(next) + else: + _blocked[index * 4 + direction] = true + + +func _advance_groups(seconds: float) -> void: + if _groups.is_empty(): + return + var done: Array[int] = [] + for group: int in _groups: + var entry: Dictionary = _groups[group] + entry["level"] = float(entry["level"]) + Tuning.BREACH_FLOW_METRES_PER_SECOND * seconds + if float(entry["level"]) >= sea_level: + done.append(group) + for group: int in done: + for index: int in _groups[group]["cells"]: + if fill_group[index] == group: + fill_group[index] = -1 + _groups.erase(group) diff --git a/src/sim/flood.gd.uid b/src/sim/flood.gd.uid new file mode 100644 index 0000000..8b73453 --- /dev/null +++ b/src/sim/flood.gd.uid @@ -0,0 +1 @@ +uid://dwo1wm7hkh01t diff --git a/src/sim/match.gd b/src/sim/match.gd index f6c949e..326a103 100644 --- a/src/sim/match.gd +++ b/src/sim/match.gd @@ -50,6 +50,9 @@ var winners: Array[int] = [] var events: Array[Dictionary] = [] var _next_bot_handle: int = FIRST_BOT_HANDLE +## Handles placed during the current step, for breaking a tie when the last players +## fall together. +var _placed_this_step: Array[int] = [] ## How many started the current match. var _match_size: int = 0 @@ -135,6 +138,7 @@ func alive() -> Array[int]: ## Advances one server tick. func step() -> void: events.clear() + _placed_this_step.clear() phase_ticks += 1 match phase: LOBBY: @@ -182,6 +186,7 @@ func _start() -> void: team_of[handle] = index / size _match_size = participants.size() sim.start_drop() + sim.start_tide() sim.place_loot() matches_started += 1 _enter(DROP) @@ -205,28 +210,85 @@ func _place(handle: int, by: int, left: bool) -> void: var place: int = _match_size - placements.size() var record: Dictionary = {"handle": handle, "place": place, "by": by, "left": left} placements.append(record) + if not left: + _placed_this_step.append(handle) var event: Dictionary = record.duplicate() event["type"] = "placed" events.append(event) -## Ends the match when at most one team has anyone standing. +## Ends the match when at most one team has anyone standing, or when the tide's time +## limit runs out. If the last players fall on the same tick, or time runs out with +## several still standing, the tie-break picks the winner, so every match that started +## with players has one. func _check_finished() -> void: if not in_match(): return + var living: Array[int] = alive() var teams: Dictionary = {} - for handle: int in alive(): + for handle: int in living: teams[team_of[handle]] = true - if teams.size() > 1: + var timed_out: bool = sim.tide != null and sim.tide.stage_at(sim.tick) == Tide.OVER + if teams.size() > 1 and not timed_out: return winners.clear() - for handle: int in alive(): - winners.append(handle) - # Winners take first place, after everyone eliminated. + if teams.size() >= 1: + var best: int = living[0] if teams.size() == 1 else _tie_break(living) + for handle: int in living: + if team_of[handle] == team_of[best]: + winners.append(handle) + # Anyone else still standing at the time limit is placed by the tie-break, worst last. + var losers: Array[int] = [] + for handle: int in living: + if not winners.has(handle): + losers.append(handle) + while not losers.is_empty(): + var worst: int = _tie_break(losers, true) + losers.erase(worst) + _place(worst, 0, false) + elif not _placed_this_step.is_empty(): + # Everyone fell on the same tick: the tie-break raises one team back to first. + var best: int = _tie_break(_placed_this_step) + for handle: int in _placed_this_step: + if team_of[handle] == team_of[best]: + winners.append(handle) + var kept: Array[Dictionary] = [] + for record: Dictionary in placements: + if not winners.has(record["handle"]): + kept.append(record) + placements = kept + # Renumber the rest of this tick's fallers below the winners. + var place: int = _match_size + for record: Dictionary in placements: + record["place"] = place + place -= 1 for handle: int in winners: placements.append({"handle": handle, "place": 1, "by": 0, "left": false}) _enter(RESULTS) - events.append({"type": "match_ended", "match": current_seed(), "winners": winners.duplicate()}) + events.append({"type": "match_ended", "match": current_seed(), "winners": winners.duplicate(), "timed_out": timed_out}) + + +## The best of `handles` by the tie-break: most health, then highest feet, then the +## earliest to join. With `worst`, the worst instead. +func _tie_break(handles: Array[int], worst: bool = false) -> int: + var chosen: int = handles[0] + for handle: int in handles: + if handle == chosen: + continue + var better: bool = _beats(handle, chosen) + if better != worst: + chosen = handle + return chosen + + +func _beats(a: int, b: int) -> bool: + var pa: SimEntity = sim.entities.find(entity_of[a]) + var pb: SimEntity = sim.entities.find(entity_of[b]) + if pa.health != pb.health: + return pa.health > pb.health + if not is_equal_approx(pa.position.y, pb.position.y): + return pa.position.y > pb.position.y + return participants.find(a) < participants.find(b) ## Back to the lobby: bots leave, the match's bookkeeping is cleared, and the next diff --git a/src/sim/safe_ground.gd b/src/sim/safe_ground.gd new file mode 100644 index 0000000..c69ffc1 --- /dev/null +++ b/src/sim/safe_ground.gd @@ -0,0 +1,97 @@ +## Safe ground: where the tide's next level leaves dry land, worked out from elevation on +## an 8 m grid over the island. It also plans the island's tide levels, so that each +## phase leaves safe ground on the main landmass: the table's level for a phase is +## lowered, when it has to be, to just under the highest point of the largest piece of +## land still dry when that phase's hold begins. The last phase always takes its table +## level, which covers every island. +class_name SafeGround +extends RefCounted + +const STRIDE_METRES: float = 8.0 +const STEPS: Array[Vector2i] = [Vector2i(1, 0), Vector2i(-1, 0), Vector2i(0, 1), Vector2i(0, -1)] + +var side: int = 0 +var heights: PackedFloat32Array = PackedFloat32Array() + + +func _init(ground: SimGround) -> void: + side = floori(Tuning.WORLD_SIZE_METRES / STRIDE_METRES) + 1 + heights.resize(side * side) + for gz: int in side: + for gx: int in side: + heights[gz * side + gx] = ground.terrain_height(gx * STRIDE_METRES, gz * STRIDE_METRES) + + +func highest() -> float: + var top: float = -INF + for value: float in heights: + top = maxf(top, value) + return top + + +## True where the ground at a point stands above `level`. +func is_safe(x: float, z: float, level: float) -> bool: + var gx: int = clampi(roundi(x / STRIDE_METRES), 0, side - 1) + var gz: int = clampi(roundi(z / STRIDE_METRES), 0, side - 1) + return heights[gz * side + gx] > level + + +## Every phase's level for this island, in phase order. See the class comment. +func plan_levels() -> PackedFloat32Array: + var levels: PackedFloat32Array = PackedFloat32Array() + var before: float = Tuning.SEA_LEVEL_START + var last: int = Tuning.TIDE_PHASES.size() - 1 + for index: int in Tuning.TIDE_PHASES.size(): + var level: float = float(Tuning.TIDE_PHASES[index]["level"]) + if index < last: + var top: float = top_of(largest_dry_piece(before)) + level = minf(level, top - Tuning.TIDE_SAFE_MARGIN_METRES) + level = maxf(level, before + Tuning.TIDE_MIN_RISE_METRES) + else: + level = maxf(level, before + Tuning.TIDE_MIN_RISE_METRES) + levels.append(level) + before = level + return levels + + +## The largest connected piece of ground above `level`, as a mark per grid cell. +func largest_dry_piece(level: float) -> PackedByteArray: + var seen: PackedByteArray = PackedByteArray() + seen.resize(side * side) + var best: PackedInt32Array = PackedInt32Array() + for start: int in side * side: + if seen[start] != 0 or heights[start] <= level: + continue + seen[start] = 1 + var piece: PackedInt32Array = PackedInt32Array([start]) + var head: int = 0 + while head < piece.size(): + var cell: int = piece[head] + head += 1 + var x: int = cell % side + var z: int = cell / side + for step: Vector2i in STEPS: + 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 seen[next] == 0 and heights[next] > level: + seen[next] = 1 + piece.append(next) + if piece.size() > best.size(): + best = piece + var marks: PackedByteArray = PackedByteArray() + marks.resize(side * side) + for cell: int in best: + marks[cell] = 1 + return marks + + +## The highest ground in a marked area, or -INF if it's empty. +func top_of(area: PackedByteArray) -> float: + var top: float = -INF + for cell: int in side * side: + if area[cell] != 0: + top = maxf(top, heights[cell]) + return top diff --git a/src/sim/safe_ground.gd.uid b/src/sim/safe_ground.gd.uid new file mode 100644 index 0000000..90fd646 --- /dev/null +++ b/src/sim/safe_ground.gd.uid @@ -0,0 +1 @@ +uid://dtu58jltyyigi diff --git a/src/sim/simulation.gd b/src/sim/simulation.gd index 82db06c..68ca4b0 100644 --- a/src/sim/simulation.gd +++ b/src/sim/simulation.gd @@ -28,6 +28,11 @@ var props: PropSet = PropSet.new() var sea_level: float = Tuning.SEA_LEVEL_START ## Damage per second to a player underwater with no breath left. Set by the tide phase. var drown_dps: int = Tuning.TIDE_PHASES[0]["drown_dps"] +## The tide's schedule, from start_tide() on. Null in tests that set the sea by hand. +var tide: Tide = null +## Where the sea reaches, on an island. Null on a test ground, where the sea is +## everywhere under `sea_level`. +var flood: Flood = null ## Every built piece. Their boxes are part of `ground`. var structures: StructureSet = StructureSet.new() ## The sky barge, from start_drop() on. Null in matches and tests that start on foot. @@ -64,6 +69,7 @@ func _init(match_seed: int, world: SimGround = null) -> void: pois.add_solids_to(world) props = PropSet.generate(island, pois) props.add_solids_to(world) + flood = Flood.create(world) ground = world structures.props = props @@ -140,12 +146,32 @@ static func crate_spill_points(prop_set: PropSet) -> Dictionary: return points +## Starts the tide's schedule from this tick. +func start_tide() -> void: + if island != null: + tide = Tide.new(tick, SafeGround.new(ground).plan_levels()) + else: + tide = Tide.new(tick) + + +## Height of the water surface over a point: the sea level where the flood reaches, +## Flood.NO_WATER where it doesn't. On a test ground, the sea level everywhere. +func water_level_at(point: Vector3) -> float: + if flood == null: + return sea_level + return flood.level_at(point.x, point.z) + + ## Advances the simulation by one tick. func step() -> void: events.clear() + if tide != null: + _advance_tide() + elif flood != null: + flood.flow(sea_level, SECONDS_PER_TICK) structures.advance_building() if tick % Tuning.TICK_RATE_HZ == Tuning.TICK_RATE_HZ - 1: - structures.tide_damage(sea_level, ground, events) + structures.tide_damage(sea_level, ground, events, flood) for player_id: int in _players: var queued: Dictionary = _pending[player_id] var command: PlayerCommand = queued.get(tick) @@ -182,9 +208,10 @@ func _ride(player: SimEntity, command: PlayerCommand) -> void: func _apply_command(player: SimEntity, command: PlayerCommand) -> void: - Movement.step(player, command, ground, sea_level) + var water: float = water_level_at(player.position) + Movement.step(player, command, ground, water) var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT) - Water.update(player, sea_level, drown_dps, sprinting) + Water.update(player, water_level_at(player.position), drown_dps, sprinting) if player.action_cooldown > 0: player.action_cooldown -= 1 Weapons.update(player) @@ -244,9 +271,34 @@ func _check_eliminations() -> void: Inventory.drop_all(self, player) -## Moves the sea surface. Takes effect on the next step. +## Moves the sea surface, and spreads the flood for it at once. Takes effect on the +## next step. With the tide running, the tide sets the level every tick instead. func set_sea_level(level: float) -> void: sea_level = level + if flood != null: + flood.update(level, structures, 0.0) + + +## The tide's tick: the sea level, drowning damage, storm surges, the flood's spread and +## sudden death. +func _advance_tide() -> void: + sea_level = tide.level_at(tick) + drown_dps = tide.drown_dps_at(tick) + if flood != null: + if tick % Tuning.TICK_RATE_HZ == 0: + flood.update(sea_level, structures, SECONDS_PER_TICK) + else: + flood.flow(sea_level, SECONDS_PER_TICK) + if tide.surge_starts(tick): + var amount: int = tide.surge_damage_at(tick) + events.append({"type": "surge", "phase": tide.phase_at(tick), "damage": amount}) + if amount > 0: + structures.surge(amount, sea_level, ground, events, flood) + if tide.stage_at(tick) == Tide.SUDDEN_DEATH and tick % Tuning.TICK_RATE_HZ == Tuning.TICK_RATE_HZ - 1: + for player_id: int in _players: + var player: SimEntity = entities.find(player_id) + if not player.eliminated and player.drop_state == Drop.NONE: + player.health = maxi(player.health - Tuning.TIDE_SUDDEN_DEATH_DPS, 0) ## Damages a piece. Returns true if this destroyed it; anything it held up collapses. @@ -319,6 +371,11 @@ func state_hash() -> String: buffer.put_64(roundi(value * 1000.0)) buffer.put_64(roundi(sea_level * 1000.0)) buffer.put_32(drown_dps) + buffer.put_64(tide.started_tick if tide != null else -1) + if tide != null: + buffer.put_data(tide.levels.to_byte_array()) + if flood != null: + flood.write_state(buffer) buffer.put_64(props.count()) buffer.put_data(props.health.to_byte_array()) structures.write_state(buffer) diff --git a/src/sim/structure_set.gd b/src/sim/structure_set.gd index ae1a0c5..9bcd686 100644 --- a/src/sim/structure_set.gd +++ b/src/sim/structure_set.gd @@ -439,12 +439,13 @@ func ground_changed(area: AABB, ground: SimGround, events: Array[Dictionary]) -> return collapse_unsupported(lost, ground, events) -## One second of the sea against every piece with its base under `sea_level`. -func tide_damage(sea_level: float, ground: SimGround, events: Array[Dictionary]) -> void: +## One second of the sea against every piece with its base under the water that reaches +## it. With no flood (a test ground), that's `sea_level` everywhere. +func tide_damage(sea_level: float, ground: SimGround, events: Array[Dictionary], flood: Flood = null) -> void: var hit: Array[Vector2i] = [] for piece: Piece in pieces.values(): var base: float = piece.slot.y * Tuning.BUILD_LEVEL_METRES - var head: float = sea_level - base + var head: float = water_at(piece, sea_level, flood) - base if head <= 0.0: continue var amount: int = Tuning.TIDE_STRUCTURE_DPS @@ -454,3 +455,34 @@ func tide_damage(sea_level: float, ground: SimGround, events: Array[Dictionary]) # Damage after the scan, since destroying pieces changes the dictionary. for entry: Vector2i in hit: damage(entry.x, entry.y, "tide", ground, events) + + +## A storm surge: `amount` damage to every piece whose base is below the water that +## reaches it plus Tuning.TIDE_SURGE_HEIGHT_METRES. +func surge(amount: int, sea_level: float, ground: SimGround, events: Array[Dictionary], flood: Flood = null) -> void: + var hit: PackedInt32Array = PackedInt32Array() + for piece: Piece in pieces.values(): + var water: float = water_at(piece, sea_level, flood) + if water <= Flood.NO_WATER: + continue + if piece.slot.y * Tuning.BUILD_LEVEL_METRES < water + Tuning.TIDE_SURGE_HEIGHT_METRES: + hit.append(piece.id) + for piece_id: int in hit: + if pieces.has(piece_id): + damage(piece_id, amount, "surge", ground, events) + + +## The water surface a piece stands in: for a wall or breakwater, the higher of the two +## cells it divides; otherwise its own cell. Flood.NO_WATER where the sea doesn't reach. +func water_at(piece: Piece, sea_level: float, flood: Flood) -> float: + if flood == null: + return sea_level + var size: float = Tuning.GRID_CELL_METRES + var x: float = (piece.slot.x + 0.5) * size + var z: float = (piece.slot.z + 0.5) * size + match piece.slot.w: + SLOT_WALL_X: + return maxf(flood.level_at(piece.slot.x * size - size * 0.5, z), flood.level_at(piece.slot.x * size + size * 0.5, z)) + SLOT_WALL_Z: + return maxf(flood.level_at(x, piece.slot.z * size - size * 0.5), flood.level_at(x, piece.slot.z * size + size * 0.5)) + return flood.level_at(x, z) diff --git a/src/sim/tide.gd b/src/sim/tide.gd new file mode 100644 index 0000000..7f93c69 --- /dev/null +++ b/src/sim/tide.gd @@ -0,0 +1,115 @@ +## The tide's schedule: Tuning.TIDE_PHASES played from the tick the tide started. Each +## phase holds the water still for `hold` seconds, then raises it over `rise` seconds to +## its `level`. After the last rise comes sudden death, and when that has run its course +## the match must end. Everything here is a pure function of elapsed ticks, so any tick's +## water level, forecast and phase can be asked for at any time. +class_name Tide +extends RefCounted + +const HOLD: int = 0 +const RISE: int = 1 +const SUDDEN_DEATH: int = 2 +const OVER: int = 3 + +const TICKS: int = Tuning.TICK_RATE_HZ + +var started_tick: int = 0 +## Each phase's level, from SafeGround.plan_levels() on an island, or the table's. +var levels: PackedFloat32Array = PackedFloat32Array() +## Tick offsets from the start: where each phase's hold and rise begin. +var _hold_starts: PackedInt32Array = PackedInt32Array() +var _rise_starts: PackedInt32Array = PackedInt32Array() +var _rise_ends: PackedInt32Array = PackedInt32Array() + + +func _init(start_tick: int, phase_levels: PackedFloat32Array = PackedFloat32Array()) -> void: + started_tick = start_tick + levels = phase_levels + if levels.is_empty(): + for phase: Dictionary in Tuning.TIDE_PHASES: + levels.append(float(phase["level"])) + var at: int = 0 + for phase: Dictionary in Tuning.TIDE_PHASES: + _hold_starts.append(at) + at += roundi(float(phase["hold"]) * TICKS) + _rise_starts.append(at) + at += maxi(roundi(float(phase["rise"]) * TICKS), 1) + _rise_ends.append(at) + + +static func phase_count() -> int: + return Tuning.TIDE_PHASES.size() + + +## Ticks from the start until sudden death begins. +func sudden_death_offset() -> int: + return _rise_ends[_rise_ends.size() - 1] + + +## Ticks from the start until the match must end. +func time_limit_offset() -> int: + return sudden_death_offset() + roundi(Tuning.TIDE_SUDDEN_DEATH_SECONDS * TICKS) + + +## The phase index in effect at `tick`: the one whose hold or rise is under way, or the +## last one from sudden death on. +func phase_at(tick: int) -> int: + var elapsed: int = tick - started_tick + for index: int in phase_count(): + if elapsed < _rise_ends[index]: + return index + return phase_count() - 1 + + +## HOLD, RISE, SUDDEN_DEATH or OVER at `tick`. +func stage_at(tick: int) -> int: + var elapsed: int = tick - started_tick + if elapsed >= time_limit_offset(): + return OVER + if elapsed >= sudden_death_offset(): + return SUDDEN_DEATH + var index: int = phase_at(tick) + return RISE if elapsed >= _rise_starts[index] else HOLD + + +## The sea level at `tick`. Before the tide starts it's the starting level. +func level_at(tick: int) -> float: + var elapsed: int = tick - started_tick + if elapsed <= 0: + return Tuning.SEA_LEVEL_START + var index: int = phase_at(tick) + var from: float = Tuning.SEA_LEVEL_START if index == 0 else levels[index - 1] + var to: float = levels[index] + if elapsed >= _rise_ends[index]: + return to + if elapsed < _rise_starts[index]: + return from + var fraction: float = float(elapsed - _rise_starts[index]) / (_rise_ends[index] - _rise_starts[index]) + return lerpf(from, to, fraction) + + +## The level the water is heading for: the current phase's level, announced from the +## start of its hold. From sudden death on, the final level. +func forecast_at(tick: int) -> float: + return levels[phase_at(tick)] + + +## Ticks until the current hold ends and the water starts rising, or 0 while it rises. +func ticks_until_rise(tick: int) -> int: + if stage_at(tick) != HOLD: + return 0 + return _rise_starts[phase_at(tick)] - (tick - started_tick) + + +func drown_dps_at(tick: int) -> int: + return int(Tuning.TIDE_PHASES[phase_at(tick)]["drown_dps"]) + + +## True on the first tick of a phase's rise: when that phase's storm surge strikes. +func surge_starts(tick: int) -> bool: + var elapsed: int = tick - started_tick + return _rise_starts.has(elapsed) + + +func surge_damage_at(tick: int) -> int: + return int(Tuning.TIDE_PHASES[phase_at(tick)].get("surge", 0)) diff --git a/src/sim/tide.gd.uid b/src/sim/tide.gd.uid new file mode 100644 index 0000000..5fa71df --- /dev/null +++ b/src/sim/tide.gd.uid @@ -0,0 +1 @@ +uid://beq3hlpyycdxq diff --git a/src/sim/tuning.gd b/src/sim/tuning.gd index 2178e4b..813dca3 100644 --- a/src/sim/tuning.gd +++ b/src/sim/tuning.gd @@ -175,14 +175,33 @@ const PROP_POI_CLEARANCE: float = 3.0 # must exceed ISLAND_MAX_HEIGHT, so that every match ends. const ISLAND_MAX_HEIGHT: float = 70.0 const TIDE_PHASES: Array[Dictionary] = [ - {"hold": 150.0, "rise": 60.0, "level": 8.0, "drown_dps": 2}, - {"hold": 100.0, "rise": 50.0, "level": 18.0, "drown_dps": 4}, - {"hold": 80.0, "rise": 45.0, "level": 30.0, "drown_dps": 6}, - {"hold": 60.0, "rise": 40.0, "level": 42.0, "drown_dps": 8}, - {"hold": 45.0, "rise": 35.0, "level": 54.0, "drown_dps": 12}, - {"hold": 30.0, "rise": 30.0, "level": 64.0, "drown_dps": 16}, - {"hold": 20.0, "rise": 40.0, "level": 75.0, "drown_dps": 25}, + {"hold": 150.0, "rise": 60.0, "level": 8.0, "drown_dps": 2, "surge": 0}, + {"hold": 100.0, "rise": 50.0, "level": 18.0, "drown_dps": 4, "surge": 40}, + {"hold": 80.0, "rise": 45.0, "level": 30.0, "drown_dps": 6, "surge": 60}, + {"hold": 60.0, "rise": 40.0, "level": 42.0, "drown_dps": 8, "surge": 80}, + {"hold": 45.0, "rise": 35.0, "level": 54.0, "drown_dps": 12, "surge": 100}, + {"hold": 30.0, "rise": 30.0, "level": 64.0, "drown_dps": 16, "surge": 120}, + {"hold": 20.0, "rise": 40.0, "level": 75.0, "drown_dps": 25, "surge": 150}, ] +## Each island's levels are planned from its terrain (SafeGround): a phase's level is +## lowered, if need be, to this far under the top of the largest piece of land still +## dry when it begins, but every phase still rises at least TIDE_MIN_RISE_METRES. The +## last phase always takes its table level. +const TIDE_SAFE_MARGIN_METRES: float = 2.0 +const TIDE_MIN_RISE_METRES: float = 4.0 +## When a phase's rise begins, a storm surge does the phase's `surge` damage once to +## every built piece whose base is below the water plus this height, where that water +## reaches it. Breakwaters take it too. +const TIDE_SURGE_HEIGHT_METRES: float = 2.0 +## Sudden death begins when the last rise ends: every player still standing loses this +## much health a second, armor or not. When it has run this long, the match ends and +## the winner is decided by Match's tie-break: most health, then highest feet, then +## earliest to join. So every match ends within the tide's total time plus this. +const TIDE_SUDDEN_DEATH_SECONDS: float = 60.0 +const TIDE_SUDDEN_DEATH_DPS: int = 5 +## The flood grid's cells are this big, matching the building grid so breakwater edges +## line up with cell edges. +const FLOOD_CELL_METRES: float = 4.0 # Building const GRID_CELL_METRES: float = 4.0 diff --git a/test/sim/safe_ground_survey.gd b/test/sim/safe_ground_survey.gd new file mode 100644 index 0000000..b718bdc --- /dev/null +++ b/test/sim/safe_ground_survey.gd @@ -0,0 +1,104 @@ +## Checks that safe ground stays reachable as the tide rises, for the tide tests' sweep, +## on SafeGround's 8 m grid. For each phase of the island's planned tide whose level +## some ground stands above, every cell of the main landmass (the largest dry piece when +## the phase's hold begins) must reach ground that stays dry after the rise within the +## phase's hold and rise: walking at WALK_SPEED over dry land, and swimming at +## SWIM_SPEED where the way crosses water. +class_name SafeGroundSurvey +extends RefCounted + +var safe: SafeGround +var levels: PackedFloat32Array + + +func _init(island: Island) -> void: + safe = SafeGround.new(island.ground) + levels = safe.plan_levels() + + +## One result per phase checked: {"phase", "level", "worst_seconds", "allowed_seconds", +## "unreached", "swimmers"}: the longest any main-landmass cell takes to reach safe +## ground, the time the phase allows, how many cells can't reach it at all, and how many +## must swim. +func check() -> Array[Dictionary]: + var results: Array[Dictionary] = [] + var highest: float = safe.highest() + var before: float = Tuning.SEA_LEVEL_START + for index: int in levels.size(): + var phase: Dictionary = Tuning.TIDE_PHASES[index] + var level: float = levels[index] + if level >= highest: + break + var main: PackedByteArray = safe.largest_dry_piece(before) + var timed: PackedFloat32Array = _time_to(level, before, false, main) + var walked: PackedFloat32Array = _time_to(level, before, true, main) + var worst: float = 0.0 + var unreached: int = 0 + var swimmers: int = 0 + for cell: int in main.size(): + if main[cell] == 0: + continue + if walked[cell] == INF: + swimmers += 1 + if timed[cell] == INF: + unreached += 1 + else: + worst = maxf(worst, timed[cell]) + results.append({ + "phase": index, "level": level, "worst_seconds": worst, + "allowed_seconds": float(phase["hold"]) + float(phase["rise"]), + "unreached": unreached, "swimmers": swimmers, + }) + before = level + return results + + +## Seconds from every cell to the nearest cell above `level`: a grid step at walking +## speed into a cell above `water`, at swimming speed into one below it (or not at all +## with `walk_only`, which also keeps to `area`). Dial's algorithm over whole steps. +func _time_to(level: float, water: float, walk_only: bool, area: PackedByteArray) -> PackedFloat32Array: + var side: int = safe.side + var heights: PackedFloat32Array = safe.heights + var swim_cost: int = maxi(roundi(Tuning.WALK_SPEED / Tuning.SWIM_SPEED), 1) + var unit: float = SafeGround.STRIDE_METRES / Tuning.WALK_SPEED + var cost: PackedInt32Array = PackedInt32Array() + cost.resize(side * side) + cost.fill(-1) + var buckets: Array[PackedInt32Array] = [PackedInt32Array()] + for cell: int in side * side: + if heights[cell] > level and (not walk_only or area[cell] != 0): + cost[cell] = 0 + buckets[0].append(cell) + var at: int = 0 + while at < buckets.size(): + var bucket: PackedInt32Array = buckets[at] + var head: int = 0 + while head < bucket.size(): + var cell: int = bucket[head] + head += 1 + if cost[cell] != at: + continue + var x: int = cell % side + var z: int = cell / side + for step: Vector2i in SafeGround.STEPS: + 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 + var dry: bool = heights[next] > water + if walk_only and (not dry or area[next] == 0): + continue + var total: int = at + (1 if dry else swim_cost) + if cost[next] >= 0 and cost[next] <= total: + continue + cost[next] = total + while buckets.size() <= total: + buckets.append(PackedInt32Array()) + buckets[total].append(next) + at += 1 + var seconds: PackedFloat32Array = PackedFloat32Array() + seconds.resize(side * side) + for cell: int in side * side: + seconds[cell] = INF if cost[cell] < 0 else cost[cell] * unit + return seconds diff --git a/test/sim/safe_ground_survey.gd.uid b/test/sim/safe_ground_survey.gd.uid new file mode 100644 index 0000000..5e9b4df --- /dev/null +++ b/test/sim/safe_ground_survey.gd.uid @@ -0,0 +1 @@ +uid://dugkjoornrh08 diff --git a/test/sim/test_island.gd b/test/sim/test_island.gd index c611687..d8827cb 100644 --- a/test/sim/test_island.gd +++ b/test/sim/test_island.gd @@ -91,6 +91,8 @@ func test_one_hundred_seeds_make_playable_islands() -> void: var worst_stranded: float = 0.0 var land_range: Vector2 = Vector2(INF, -INF) var peak_counts: Dictionary = {} + var safe_margin: float = INF + var lowered_phases: int = 0 for seed_value: int in range(1, SWEEP_SEEDS + 1): var started: int = Time.get_ticks_msec() var island: Island = Island.generate(seed_value) @@ -116,6 +118,23 @@ func test_one_hundred_seeds_make_playable_islands() -> void: assert_true(stranded <= MAX_STRANDED_FRACTION, "%s: at %.0f m, %.3f of dry land is cut off from the main landmass" % [label, level, stranded]) + # Safe ground (issue M2): every phase of the island's planned tide that leaves + # land leaves it within reach of the whole main landmass, on foot, in time. + var safe: SafeGroundSurvey = SafeGroundSurvey.new(island) + var checked: Array[Dictionary] = safe.check() + assert_true(checked.size() >= Tuning.TIDE_PHASES.size() - 2, "%s: only %d phases leave safe ground" % [label, checked.size()]) + for result: Dictionary in checked: + var phase_label: String = "%s phase %d (%.1f m)" % [label, result["phase"], result["level"]] + assert_eq(result["unreached"], 0, "%s: main landmass cells with no way to safe ground" % phase_label) + assert_eq(result["swimmers"], 0, "%s: main landmass cells that must swim to safe ground" % phase_label) + assert_true(result["worst_seconds"] <= result["allowed_seconds"], + "%s: %.0f s to safe ground, %.0f s allowed" % [phase_label, result["worst_seconds"], result["allowed_seconds"]]) + safe_margin = minf(safe_margin, result["allowed_seconds"] - result["worst_seconds"]) + for index: int in safe.levels.size(): + if not is_equal_approx(safe.levels[index], float(Tuning.TIDE_PHASES[index]["level"])): + lowered_phases += 1 + assert_eq(safe.levels[safe.levels.size() - 1], float(Tuning.TIDE_PHASES[-1]["level"]), "%s: the last phase keeps its level" % label) + 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()]) @@ -134,6 +153,7 @@ func test_one_hundred_seeds_make_playable_islands() -> void: 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: safe ground reached with at least %.0f s to spare; %d phase levels lowered by planning" % [safe_margin, lowered_phases]) print(" island sweep: islands by distinct high points %s, %d of %d with marsh" % [ peak_counts, marsh_islands, SWEEP_SEEDS]) diff --git a/test/sim/test_match.gd b/test/sim/test_match.gd index a3a00a4..dca2bc7 100644 --- a/test/sim/test_match.gd +++ b/test/sim/test_match.gd @@ -51,6 +51,7 @@ func _reference_hash(m: Match, index: int, players: int) -> String: for _index: int in players: sim.add_player() sim.start_drop() + sim.start_tide() sim.place_loot() return sim.state_hash() diff --git a/test/sim/test_tide.gd b/test/sim/test_tide.gd new file mode 100644 index 0000000..3b4fc33 --- /dev/null +++ b/test/sim/test_tide.gd @@ -0,0 +1,353 @@ +extends TestCase + +## The rising tide from issue M2: the phase schedule and forecasts, island-planned +## levels, flooding along the terrain, breakwaters that seal, wear, overflow and breach, +## storm surges, drowning, and sudden death with a deterministic winner. Safe ground over +## 100 seeds is checked in test_island's sweep, which already generates those islands. + +const SIDE: int = 513 +const SPACING: float = 2.0 +## A low square of land, 200 m across, in the middle of open sea. +const LAND_MIN: float = 400.0 +const LAND_MAX: float = 600.0 +## The breakwater ring: cells RING_MIN to RING_MAX inclusive, 12 m square. +const RING_MIN: int = 120 +const RING_MAX: int = 122 +const INSIDE: Vector3 = Vector3(486.0, 1.0, 486.0) +const OUTSIDE: Vector3 = Vector3(450.0, 1.0, 450.0) + + +## A heightfield world: open sea floor everywhere, `land` height over the land square, +## and `basin` height in a 40 m square in its middle (no basin if NAN). +func _ground(land: float, basin: float = NAN) -> SimGround: + var values: PackedFloat32Array = PackedFloat32Array() + values.resize(SIDE * SIDE) + for gz: int in SIDE: + for gx: int in SIDE: + var x: float = gx * SPACING + var z: float = gz * SPACING + var height: float = -Tuning.ISLAND_SEA_DEPTH + if x >= LAND_MIN and x <= LAND_MAX and z >= LAND_MIN and z <= LAND_MAX: + height = land + if not is_nan(basin) and x >= 480.0 and x <= 520.0 and z >= 480.0 and z <= 520.0: + height = basin + values[gz * SIDE + gx] = height + return SimGround.from_heights(values, SIDE, SPACING) + + +## A simulation over `ground` with a flood grid, as an island match has. +func _sim(ground: SimGround) -> Simulation: + var sim: Simulation = Simulation.new(3, ground) + sim.flood = Flood.create(ground) + return sim + + +## Seals the ring's twelve edges with breakwaters `stack` pieces high, the lowest based +## at build level `base`, and lets them finish building. +func _ring(sim: Simulation, stack: int = 1, base: int = 0, material: String = "stone") -> Array[int]: + var ids: Array[int] = [] + var stone: int = Materials.code_of(material) + for level_index: int in stack: + var level: int = base + level_index * 2 + for along: int in range(RING_MIN, RING_MAX + 1): + for slot: Vector4i in [ + Vector4i(RING_MIN, level, along, StructureSet.SLOT_WALL_X), + Vector4i(RING_MAX + 1, level, along, StructureSet.SLOT_WALL_X), + Vector4i(along, level, RING_MIN, StructureSet.SLOT_WALL_Z), + Vector4i(along, level, RING_MAX + 1, StructureSet.SLOT_WALL_Z), + ]: + ids.append(sim.structures.add(StructureSet.BREAKWATER, stone, slot, 0, 0, sim.tick, sim.ground).id) + for _index: int in roundi(float(Tuning.MATERIALS[material]["build_seconds"]) * Tuning.TICK_RATE_HZ) + 1: + sim.structures.advance_building() + return ids + + +## Steps the simulation for `seconds`, so newly flooded ground fills to the sea. +func _settle(sim: Simulation, seconds: float = 3.0) -> void: + for _index: int in roundi(seconds * Tuning.TICK_RATE_HZ): + sim.step() + + +func _tick_for(tide: Tide, seconds: float) -> int: + return tide.started_tick + roundi(seconds * Tuning.TICK_RATE_HZ) + + +func test_the_schedule_follows_the_table_and_forecasts_each_level() -> void: + var tide: Tide = Tide.new(100) + var phases: Array[Dictionary] = Tuning.TIDE_PHASES + assert_eq(tide.level_at(100), Tuning.SEA_LEVEL_START) + assert_eq(tide.stage_at(100), Tide.HOLD) + assert_eq(tide.forecast_at(100), float(phases[0]["level"]), "the first level is announced from the start") + var hold: float = phases[0]["hold"] + var rise: float = phases[0]["rise"] + assert_eq(tide.level_at(_tick_for(tide, hold - 1.0)), Tuning.SEA_LEVEL_START, "still during the hold") + assert_true(tide.ticks_until_rise(100) == roundi(hold * Tuning.TICK_RATE_HZ)) + assert_true(tide.surge_starts(_tick_for(tide, hold)), "the surge comes with the rise") + assert_false(tide.surge_starts(_tick_for(tide, hold) + 1)) + assert_eq(tide.stage_at(_tick_for(tide, hold + 1.0)), Tide.RISE) + assert_near(tide.level_at(_tick_for(tide, hold + rise * 0.5)), float(phases[0]["level"]) * 0.5, 0.01, "halfway up") + var end_first: int = _tick_for(tide, hold + rise) + assert_near(tide.level_at(end_first), float(phases[0]["level"]), 0.001) + assert_eq(tide.phase_at(end_first), 1) + assert_eq(tide.forecast_at(end_first), float(phases[1]["level"]), "each hold forecasts the next level") + assert_eq(tide.drown_dps_at(end_first), int(phases[1]["drown_dps"])) + # The whole schedule, then sudden death, then the time limit. + var total: float = 0.0 + for phase: Dictionary in phases: + total += float(phase["hold"]) + float(phase["rise"]) + assert_eq(tide.sudden_death_offset(), roundi(total * Tuning.TICK_RATE_HZ)) + assert_eq(tide.stage_at(100 + tide.sudden_death_offset()), Tide.SUDDEN_DEATH) + assert_eq(tide.level_at(100 + tide.sudden_death_offset() + 5), float(phases[-1]["level"])) + assert_eq(tide.stage_at(100 + tide.time_limit_offset()), Tide.OVER) + assert_eq(tide.time_limit_offset() - tide.sudden_death_offset(), roundi(Tuning.TIDE_SUDDEN_DEATH_SECONDS * Tuning.TICK_RATE_HZ)) + # Levels only rise. + var last: float = -INF + for tick: int in range(100, 100 + tide.time_limit_offset(), 97): + assert_true(tide.level_at(tick) >= last) + last = tide.level_at(tick) + + +func test_planned_levels_keep_safe_ground_on_the_main_land() -> void: + # A 30 m plateau: the table's 30 m phase would drown it all, so it's lowered. + var safe: SafeGround = SafeGround.new(_ground(30.0)) + var levels: PackedFloat32Array = safe.plan_levels() + assert_eq(levels.size(), Tuning.TIDE_PHASES.size()) + assert_eq(levels[0], float(Tuning.TIDE_PHASES[0]["level"])) + assert_eq(levels[1], float(Tuning.TIDE_PHASES[1]["level"])) + assert_eq(levels[2], 30.0 - Tuning.TIDE_SAFE_MARGIN_METRES, "lowered to just under the land's top") + for index: int in range(1, levels.size()): + assert_true(levels[index] >= levels[index - 1] + Tuning.TIDE_MIN_RISE_METRES - 0.001, "phase %d still rises" % index) + assert_eq(levels[levels.size() - 1], float(Tuning.TIDE_PHASES[-1]["level"]), "the last phase covers everything") + assert_true(safe.is_safe(500.0, 500.0, levels[2])) + assert_false(safe.is_safe(100.0, 100.0, 0.0), "open sea is never safe") + + +func test_low_ground_cut_off_from_the_sea_stays_dry_until_overtopped() -> void: + var sim: Simulation = _sim(_ground(3.0, -2.0)) + var basin: Vector3 = Vector3(500.0, -2.0, 500.0) + assert_eq(sim.water_level_at(Vector3(100.0, 0.0, 100.0)), 0.0, "the open sea") + assert_eq(sim.water_level_at(basin), Flood.NO_WATER, "the basin is below the sea but cut off") + sim.set_sea_level(2.5) + assert_eq(sim.water_level_at(basin), Flood.NO_WATER, "the land around it still holds") + sim.set_sea_level(4.0) + assert_true(sim.flood.is_flooded(basin.x, basin.z), "the sea poured over the land") + assert_near(sim.water_level_at(basin), -2.0, 0.01, "and starts filling it from the bottom") + for _index: int in 2 * Tuning.TICK_RATE_HZ: + sim.step() + assert_near(sim.water_level_at(basin), -2.0 + 2.0 * Tuning.BREACH_FLOW_METRES_PER_SECOND, 0.06, "it fills at the breach rate") + for _index: int in 3 * Tuning.TICK_RATE_HZ: + sim.step() + assert_eq(sim.water_level_at(basin), 4.0, "until it stands level with the sea") + + +func test_a_breakwater_ring_keeps_its_ground_dry() -> void: + var sim: Simulation = _sim(_ground(1.0)) + _ring(sim) + sim.set_sea_level(3.0) + assert_true(sim.flood.is_flooded(OUTSIDE.x, OUTSIDE.z), "the land outside floods") + assert_near(sim.water_level_at(OUTSIDE), 1.0, 0.01, "filling from its floor") + _settle(sim) + assert_eq(sim.water_level_at(OUTSIDE), 3.0, "up to the sea") + assert_eq(sim.water_level_at(INSIDE), Flood.NO_WATER, "inside the ring stays dry") + assert_eq(sim.flood.barrier_between(sim.flood.cell_of(INSIDE.x, INSIDE.z), sim.flood.cell_of(INSIDE.x - 4.0, INSIDE.z)), -INF, "no barrier inside the ring") + + +func test_a_breached_breakwater_floods_everything_behind_it() -> void: + var sim: Simulation = _sim(_ground(1.0)) + var ids: Array[int] = _ring(sim) + sim.set_sea_level(3.0) + _settle(sim) + assert_eq(sim.water_level_at(INSIDE), Flood.NO_WATER) + assert_true(sim.damage_piece(ids[0], 100000), "the breakwater breaks") + sim.set_sea_level(3.0) + assert_true(sim.flood.is_flooded(INSIDE.x, INSIDE.z), "the breach lets the sea in") + assert_near(sim.water_level_at(INSIDE), 1.0, 0.01, "filling from the floor") + for _index: int in Tuning.TICK_RATE_HZ: + sim.step() + assert_near(sim.water_level_at(INSIDE), 1.0 + Tuning.BREACH_FLOW_METRES_PER_SECOND, 0.06, "rising at the breach rate") + _settle(sim, 1.0) + assert_eq(sim.water_level_at(INSIDE), 3.0, "until it's level with the sea") + + +func test_water_spills_over_a_breakwater_that_is_too_low() -> void: + var sim: Simulation = _sim(_ground(1.0)) + _ring(sim) + sim.set_sea_level(3.9) + assert_eq(sim.water_level_at(INSIDE), Flood.NO_WATER) + sim.set_sea_level(4.5) + assert_true(sim.flood.is_flooded(INSIDE.x, INSIDE.z), "over the top of a 4 m breakwater") + + +func test_pressure_wears_breakwaters_and_too_much_head_breaks_them() -> void: + var sim: Simulation = _sim(_ground(1.0)) + var ids: Array[int] = _ring(sim, 2) + var piece: StructureSet.Piece = sim.structures.find(ids[0]) + var full: int = piece.health + sim.set_sea_level(3.0) + for _index: int in 3: + sim.flood.flow(3.0, 1.0) + sim.structures.tide_damage(sim.sea_level, sim.ground, sim.events, sim.flood) + assert_eq(piece.health, full - roundi(Tuning.BREAKWATER_WEAR_PER_METRE * 3.0), "worn per metre of head") + # 7 m of water on a breakwater based at 0 is past BREAKWATER_MAX_HEAD. + sim.set_sea_level(7.0) + for _index: int in 5: + sim.flood.flow(7.0, 1.0) + assert_eq(sim.water_level_at(INSIDE), Flood.NO_WATER, "the 8 m stack still holds 7 m") + sim.structures.tide_damage(sim.sea_level, sim.ground, sim.events, sim.flood) + assert_null(sim.structures.find(ids[0]), "too much head breaks it at once") + sim.set_sea_level(7.0) + assert_true(sim.flood.is_flooded(INSIDE.x, INSIDE.z), "and the sea comes through") + + +func test_pieces_in_dry_ground_take_no_tide_damage() -> void: + var sim: Simulation = _sim(_ground(1.0)) + _ring(sim) + var floor_piece: StructureSet.Piece = sim.structures.add(StructureSet.FLOOR, Materials.code_of("stone"), Vector4i(121, 0, 121, StructureSet.SLOT_FLOOR), 0, 0, 0, sim.ground) + var outside_piece: StructureSet.Piece = sim.structures.add(StructureSet.FLOOR, Materials.code_of("stone"), Vector4i(112, 0, 112, StructureSet.SLOT_FLOOR), 0, 0, 0, sim.ground) + var inside_health: int = floor_piece.health + var outside_health: int = outside_piece.health + sim.set_sea_level(3.0) + for _index: int in 3: + sim.flood.flow(3.0, 1.0) + sim.structures.tide_damage(sim.sea_level, sim.ground, sim.events, sim.flood) + assert_eq(floor_piece.health, inside_health, "behind the breakwater, the sea can't reach it") + assert_eq(outside_piece.health, outside_health - Tuning.TIDE_STRUCTURE_DPS) + + +func test_a_storm_surge_hits_low_pieces_where_the_water_reaches() -> void: + var sim: Simulation = _sim(_ground(1.0)) + _ring(sim) + var stone: int = Materials.code_of("stone") + var low: StructureSet.Piece = sim.structures.add(StructureSet.FLOOR, stone, Vector4i(112, 2, 112, StructureSet.SLOT_FLOOR), 0, 0, 0, sim.ground) + var high: StructureSet.Piece = sim.structures.add(StructureSet.FLOOR, stone, Vector4i(110, 6, 110, StructureSet.SLOT_FLOOR), 0, 0, 0, sim.ground) + var sheltered: StructureSet.Piece = sim.structures.add(StructureSet.FLOOR, stone, Vector4i(121, 0, 121, StructureSet.SLOT_FLOOR), 0, 0, 0, sim.ground) + var before: Array[int] = [low.health, high.health, sheltered.health] + sim.set_sea_level(3.0) + for _index: int in 3: + sim.flood.flow(3.0, 1.0) + sim.structures.surge(20, sim.sea_level, sim.ground, sim.events, sim.flood) + assert_eq(low.health, before[0] - 20, "a 4 m base is within the surge over 3 m of water") + assert_eq(high.health, before[1], "a 12 m base is above it") + assert_eq(sheltered.health, before[2], "the ring shelters what's inside") + + +func test_the_tide_raises_the_sea_floods_the_land_and_drowns() -> void: + # Land at 3 m, and a salvage iron ring based at 2 m, two pieces (10 m) high: the + # first phase's 8 m puts 6 m of head on it, which it holds while it wears. (Stone + # wears through during the rise: about 330 damage against 300 health.) + var sim: Simulation = _sim(_ground(3.0)) + _ring(sim, 2, 1, "salvage_iron") + var outside: int = sim.add_player() + var inside: int = sim.add_player() + sim.entities.find(outside).position = OUTSIDE + Vector3(0.0, 2.0, 0.0) + sim.entities.find(inside).position = INSIDE + Vector3(0.0, 2.0, 0.0) + sim.start_tide() + # Jump to just before the first rise: the sea is still at its start. + var phase: Dictionary = Tuning.TIDE_PHASES[0] + sim.tide = Tide.new(sim.tick - roundi(float(phase["hold"]) * Tuning.TICK_RATE_HZ) + 1) + var surged: bool = false + for _index: int in roundi(float(phase["rise"]) * Tuning.TICK_RATE_HZ) + Tuning.TICK_RATE_HZ: + sim.step() + for event: Dictionary in sim.events: + surged = surged or event["type"] == "surge" + assert_true(surged, "the rise brought a surge") + assert_near(sim.sea_level, float(phase["level"]), 0.001, "the first phase raised the sea") + assert_eq(sim.drown_dps, int(Tuning.TIDE_PHASES[1]["drown_dps"])) + assert_eq(sim.water_level_at(OUTSIDE), sim.sea_level, "the land flooded") + assert_eq(sim.water_level_at(INSIDE), Flood.NO_WATER, "a 10 m ring holds 8 m") + # An exhausted swimmer with no breath goes under and drowns at the phase's rate. + var swimmer: SimEntity = sim.entities.find(outside) + swimmer.stamina_ticks = 0 + swimmer.breath_ticks = 0 + var dry: SimEntity = sim.entities.find(inside) + var health: int = swimmer.health + for _index: int in 5 * Tuning.TICK_RATE_HZ: + sim.step() + assert_true(Water.head_under(swimmer, sim.water_level_at(swimmer.position)), "the exhausted swimmer went under") + assert_true(health - swimmer.health >= sim.drown_dps and (health - swimmer.health) % sim.drown_dps == 0, "drowning at the phase's rate: %d -> %d" % [health, swimmer.health]) + assert_eq(dry.health, Tuning.PLAYER_MAX_HEALTH, "the player behind the ring is dry") + assert_false(dry.swimming) + + +func _match(players: int) -> Match: + var rules: MatchRules = MatchRules.immediate() + rules.max_players = players + rules.fill_with_bots = false + var m: Match = Match.new(77, rules) + for handle: int in range(1, players + 1): + m.join(handle) + m.step() + assert_eq(m.phase, Match.DROP) + return m + + +func _land_everyone(m: Match) -> void: + for handle: int in m.entity_of: + var player: SimEntity = m.sim.entities.find(m.entity_of[handle]) + player.drop_state = Drop.NONE + player.position = Vector3(512.0, 200.0 + handle, 512.0) + + +func test_sudden_death_wears_everyone_down() -> void: + var m: Match = _match(3) + _land_everyone(m) + m.sim.tide = Tide.new(m.sim.tick - m.sim.tide.sudden_death_offset(), m.sim.tide.levels) + for _index: int in Tuning.TICK_RATE_HZ: + m.step() + for handle: int in m.entity_of: + assert_eq(m.sim.entities.find(m.entity_of[handle]).health, Tuning.PLAYER_MAX_HEALTH - Tuning.TIDE_SUDDEN_DEATH_DPS) + assert_true(m.in_match()) + + +func test_the_time_limit_ends_the_match_with_a_tie_break_winner() -> void: + var m: Match = _match(3) + _land_everyone(m) + var players: Array[SimEntity] = [] + for handle: int in [1, 2, 3]: + players.append(m.sim.entities.find(m.entity_of[handle])) + players[0].health = 50 + players[1].health = 90 + players[2].health = 90 + m.sim.tide = Tide.new(m.sim.tick - m.sim.tide.time_limit_offset() + 1, m.sim.tide.levels) + m.step() + assert_eq(m.phase, Match.RESULTS) + assert_eq(m.winners, [3] as Array[int], "most health, then highest feet") + var places: Dictionary = {} + for record: Dictionary in m.placements: + places[record["handle"]] = record["place"] + assert_eq(places, {1: 3, 2: 2, 3: 1}) + var timed_out: bool = false + for event: Dictionary in m.events: + if event["type"] == "match_ended": + timed_out = event["timed_out"] + assert_true(timed_out) + + +func test_when_the_last_players_fall_together_one_still_wins() -> void: + var m: Match = _match(3) + _land_everyone(m) + m.leave(1) + for handle: int in [2, 3]: + m.sim.entities.find(m.entity_of[handle]).health = 0 + m.step() + assert_eq(m.phase, Match.RESULTS) + assert_eq(m.winners, [3] as Array[int], "the higher of the two") + var places: Dictionary = {} + for record: Dictionary in m.placements: + places[record["handle"]] = record["place"] + assert_eq(places[3], 1) + assert_eq(places[2], 2) + assert_eq(places[1], 3, "the leaver keeps last place") + + +func test_every_match_ends_by_the_time_limit() -> void: + # The bound itself: nothing can keep a match going past the tide's time limit. + var tide: Tide = Tide.new(0) + var limit_seconds: float = tide.time_limit_offset() / float(Tuning.TICK_RATE_HZ) + var expected: float = Tuning.TIDE_SUDDEN_DEATH_SECONDS + for phase: Dictionary in Tuning.TIDE_PHASES: + expected += float(phase["hold"]) + float(phase["rise"]) + assert_near(limit_seconds, expected, 0.05) + # Sudden death alone takes a full-health, full-armor player out before the limit. + assert_true(Tuning.TIDE_SUDDEN_DEATH_DPS * Tuning.TIDE_SUDDEN_DEATH_SECONDS >= Tuning.PLAYER_MAX_HEALTH) + assert_true(Tuning.TIDE_PHASES[-1]["level"] > Tuning.ISLAND_MAX_HEIGHT) diff --git a/test/sim/test_tide.gd.uid b/test/sim/test_tide.gd.uid new file mode 100644 index 0000000..416ec88 --- /dev/null +++ b/test/sim/test_tide.gd.uid @@ -0,0 +1 @@ +uid://bqbrkt5tq1qf3 diff --git a/tools/_probe.gd.uid b/tools/_probe.gd.uid new file mode 100644 index 0000000..aef5cc0 --- /dev/null +++ b/tools/_probe.gd.uid @@ -0,0 +1 @@ +uid://d1thrumhwgto6