Files
tidewall/src/sim/simulation.gd
T
claudeandClaude Opus 5.5 f35ebf7171 B2: Grid building and placement preview
Server-authoritative grid building with wall, floor, ramp, roof and
breakwater pieces in driftwood, stone and salvage iron, plus a client
placement ghost.

- StructureSet: pieces in grid slots (floor, two wall edges, cell
  volume), their collision boxes in SimGround, and touching-neighbour
  links kept up to date for B3. Ramps are stairs of 0.4 m steps; walls
  over lower ground get a skirt down to the terrain; roofs are a low
  stepped pyramid. Pieces are part of the state hash.
- Building: target() snaps look and position to a slot, and check()
  validates any slot as if a hostile client chose it: state, range,
  occupancy, trapping a player, cost and support. Fire in build mode
  places at most 10 pieces a second; players in a low step are lifted.
- Levels are half a cell (2 m) apart, so ground pieces sit within a
  metre of the builder's feet instead of being half buried.
- Client: StructureView draws pieces from their boxes in plank, course
  or panel strips; ramps draw as a sloped deck. BuildGhost shows sea
  green or rust red from the same target() and check().
- Tests: 15 sim tests (targeting, every rejection, overlap, support,
  stairs climbable, skirts, determinism, 24 builders at 10 pieces a
  second within the tick budget) and 5 client tests (ghost states,
  ghost agrees with the server, view sync, mesh orientation).
- Capture scenarios build_fort and build_fort_side.

Closes #16

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:23:29 -05:00

216 lines
8.0 KiB
GDScript

## The authoritative fixed-tick game state. It takes commands and a seed and nothing
## else: no scene tree, no wall clock, no unseeded randomness.
##
## Movement rules live in Movement; the world's solid shape lives in `ground`.
class_name Simulation
extends RefCounted
const SECONDS_PER_TICK: float = 1.0 / Tuning.TICK_RATE_HZ
const SPAWN_ATTEMPTS: int = 64
## The command selection that holds the boathook, which every player always carries.
const BOATHOOK_SLOT: int = 0
var tick: int = 0
var entities: EntityRegistry = EntityRegistry.new()
var rng: SimRng
## Terrain and solids. The island's heightfield unless a test supplied its own ground.
var ground: SimGround
## The generated island, or null when a test supplied its own ground.
var island: Island
## The island's points of interest, whose solids are part of `ground`. Empty when a
## test supplied its own ground.
var pois: PoiSet = PoiSet.new()
## Trees, scrub, boulders, wrecks and crates, whose boxes are part of `ground`. Empty
## when a test supplied its own ground.
var props: PropSet = PropSet.new()
## Height of the sea surface, in metres. The tide changes it during a match; movement
## and drowning read it every tick, so a change takes effect on the next step.
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"]
## 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.
var drop: Drop = null
## What happened during the last step(): harvests, destroyed props, placed pieces.
## Each is a Dictionary with a "type". Cleared at the start of every step.
var events: Array[Dictionary] = []
## Player entity ID -> { command tick -> PlayerCommand }
var _pending: Dictionary = {}
## Player entity IDs, ascending.
var _players: Array[int] = []
## 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)
if world == null:
island = Island.generate(match_seed)
world = island.ground
pois = PoiSet.generate(island)
pois.add_solids_to(world)
props = PropSet.generate(island, pois)
props.add_solids_to(world)
ground = world
## Adds a player at a seeded spawn position and returns its entity ID.
func add_player() -> int:
var player: SimEntity = entities.create(SimEntity.ARCHETYPE_PLAYER)
var spawn: RandomNumberGenerator = rng.stream("spawn")
var size: float = Tuning.WORLD_SIZE_METRES
var x: 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:
var feet: Vector3 = Vector3(x, ground.terrain_height(x, z), z)
if feet.y > Tuning.ISLAND_BEACH_TOP and not ground.body_blocked(feet, 2.0, Tuning.PLAYER_HEIGHT, 0.0):
break
x = spawn.randf() * size
z = spawn.randf() * size
player.position = Vector3(x, ground.terrain_height(x, z), z)
player.on_ground = true
player.health = Tuning.PLAYER_MAX_HEALTH
Water.reset(player)
if drop != null and not drop.finished:
Drop.board(player, drop.barge_position(tick))
_players.append(player.id)
_pending[player.id] = {}
return player.id
## Removes a player and any commands queued for it.
func remove_player(player_id: int) -> void:
entities.remove(player_id)
_players.erase(player_id)
_pending.erase(player_id)
## Queues a command for the tick it names. Returns false if it was rejected: the player
## is unknown, the tick has passed, or the tick is too far ahead to be legitimate.
## A later command for the same tick replaces an earlier one.
func submit_command(player_id: int, command: PlayerCommand) -> bool:
if not _pending.has(player_id):
return false
if command.tick < tick or command.tick > tick + Tuning.MAX_COMMAND_LEAD_TICKS:
return false
_pending[player_id][command.tick] = command
return true
## Starts the match's drop: plans the barge's route and puts every player aboard.
func start_drop() -> void:
drop = Drop.plan(ground, rng, tick)
for player_id: int in _players:
Drop.board(entities.find(player_id), drop.barge_position(tick))
## Advances the simulation by one tick.
func step() -> void:
events.clear()
for player_id: int in _players:
var queued: Dictionary = _pending[player_id]
var command: PlayerCommand = queued.get(tick)
queued.erase(tick)
var player: SimEntity = entities.find(player_id)
if player.drop_state == Drop.ABOARD:
_ride(player, command)
else:
_apply_command(player, command)
if drop != null and not drop.finished and drop.is_over(tick + 1):
# The end of the route: everyone still aboard goes over the side.
for player_id: int in _players:
var player: SimEntity = entities.find(player_id)
if player.drop_state == Drop.ABOARD:
drop.leap(player, tick + 1)
drop.finished = true
tick += 1
## A tick aboard the barge: jump leaps off, anything else rides along.
func _ride(player: SimEntity, command: PlayerCommand) -> void:
if command != null:
player.yaw = command.yaw
player.pitch = command.pitch
if command.is_pressed(PlayerCommand.BUTTON_JUMP):
drop.leap(player, tick)
return
player.position = drop.barge_position(tick + 1)
func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
Movement.step(player, command, ground, sea_level)
var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT)
Water.update(player, sea_level, drown_dps, sprinting)
if player.action_cooldown > 0:
player.action_cooldown -= 1
if command == null or not command.is_pressed(PlayerCommand.BUTTON_FIRE):
return
if not Building.is_allowed(player):
return
if command.is_pressed(PlayerCommand.BUTTON_BUILD):
Building.act(self, player, command)
return
if command.selection == BOATHOOK_SLOT:
Harvest.swing(player, ground, props, events)
## Moves the sea surface. Takes effect on the next step.
func set_sea_level(level: float) -> void:
sea_level = level
## Damages a prop. Returns true if this destroyed it; its collision goes at once.
func damage_prop(prop: int, amount: int) -> bool:
return props.damage(prop, amount)
## SHA-256 hex digest of a canonical encoding of the whole state.
func state_hash() -> String:
var buffer: StreamPeerBuffer = StreamPeerBuffer.new()
buffer.big_endian = false
buffer.put_64(tick)
buffer.put_64(entities.next_id())
buffer.put_64(rng.match_seed)
for stream_name: String in rng.stream_names():
buffer.put_utf8_string(stream_name)
buffer.put_64(rng.stream(stream_name).state)
buffer.put_64(entities.count())
for entity: SimEntity in entities.entities():
buffer.put_64(entity.id)
buffer.put_32(entity.archetype)
buffer.put_32(entity.health)
buffer.put_32(entity.yaw)
buffer.put_32(entity.pitch)
buffer.put_u8((1 if entity.on_ground else 0) | (2 if entity.crouching else 0) | (4 if entity.swimming else 0))
buffer.put_32(entity.breath_ticks)
buffer.put_32(entity.stamina_ticks)
buffer.put_32(entity.drown_ticks)
buffer.put_u8(entity.drop_state)
buffer.put_data(entity.materials.to_byte_array())
buffer.put_32(entity.action_cooldown)
for value: float in [entity.position.x, entity.position.y, entity.position.z]:
buffer.put_64(roundi(value * 1000.0))
for value: float in [entity.velocity.x, entity.velocity.y, entity.velocity.z]:
buffer.put_64(roundi(value * 1000.0))
if drop != null:
buffer.put_64(drop.began_tick)
buffer.put_64(drop.duration_ticks)
buffer.put_u8(1 if drop.finished else 0)
for value: float in [drop.start.x, drop.start.z, drop.finish.x, drop.finish.z]:
buffer.put_64(roundi(value * 1000.0))
buffer.put_64(roundi(sea_level * 1000.0))
buffer.put_32(drown_dps)
buffer.put_64(props.count())
buffer.put_data(props.health.to_byte_array())
structures.write_state(buffer)
var hasher: HashingContext = HashingContext.new()
hasher.start(HashingContext.HASH_SHA256)
hasher.update(buffer.data_array)
return hasher.finish().hex_encode()