Files
tidewall/src/sim/simulation.gd
T
claudeandClaude Opus 5.5 5d2a2bbc31 B7: Weapon roster and consumables
Eight slot weapons: the six from the design plus the rivet repeater (fast,
short-range automatic) and the harpoon gun (slow heavy bolt, 2.5x damage to
built pieces). Four quality tiers, Rusted to Captain's, scale damage and reload
time. The line thrower now yanks the shooter towards where its line lands,
through a data field (pull_speed) any weapon can use.

Four consumables: sailcloth bandage (heals to 75), brine tonic, cork vest and
the new tar patch. Fire with one held starts using it if it would help; it
takes effect after its use time. Changing slot, dropping, sprinting, swimming
or elimination interrupts it and uses nothing up. All checks run on the server.

A data-validation test covers every weapon, tier, consumable and ammunition
type, including unknown stat keys, name format and that every ammo type is
used. The GDD's weapons section lists the roster.

Closes #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:26:04 -05:00

290 lines
11 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
## Items lying in the world, as entity IDs in ascending order. See Inventory.
var pickups: Array[int] = []
## Shots in flight, as entity IDs in ascending order. See Weapons.
var projectiles: Array[int] = []
## 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
structures.props = props
## 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)
Inventory.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()
structures.advance_building()
if tick % Tuning.TICK_RATE_HZ == Tuning.TICK_RATE_HZ - 1:
structures.tide_damage(sea_level, ground, events)
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.eliminated:
continue
if player.drop_state == Drop.ABOARD:
_ride(player, command)
else:
_apply_command(player, command)
Weapons.advance_projectiles(self)
_check_eliminations()
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
Weapons.update(player)
Consumables.update(self, player, command)
var held: int = command.buttons if command != null else 0
var pressed: int = held & ~player.prev_buttons
player.prev_buttons = held
if command != null and not command.is_pressed(PlayerCommand.BUTTON_BUILD):
Inventory.select(player, command.selection)
if Harvest.can_swing(player):
if pressed & PlayerCommand.BUTTON_INTERACT:
Inventory.interact(self, player)
if pressed & PlayerCommand.BUTTON_DROP:
Inventory.drop_held(self, player)
if command != null and command.is_pressed(PlayerCommand.BUTTON_RELOAD):
Weapons.start_reload(player)
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 player.selected == BOATHOOK_SLOT:
Harvest.swing(player, ground, props, events, structures)
else:
var def: ItemDef = Inventory.held_def(player)
if def != null and def.kind == ItemDef.CONSUMABLE:
Consumables.start(self, player)
else:
Weapons.fire(self, player, command.is_pressed(PlayerCommand.BUTTON_AIM))
## Marks players whose health reached 0 as eliminated, and drops what they carried.
func _check_eliminations() -> void:
for player_id: int in _players:
var player: SimEntity = entities.find(player_id)
if player.eliminated or player.health > 0:
continue
player.eliminated = true
player.velocity = Vector3.ZERO
events.append({"type": "eliminated", "player": player_id, "by": player.last_attacker})
Inventory.drop_all(self, player)
## Moves the sea surface. Takes effect on the next step.
func set_sea_level(level: float) -> void:
sea_level = level
## Damages a piece. Returns true if this destroyed it; anything it held up collapses.
func damage_piece(piece_id: int, amount: int, cause: String = "damage") -> bool:
return structures.damage(piece_id, amount, cause, ground, events)
## Tells structures the terrain or fixed solids in `area` changed, so pieces that lost
## their footing can collapse. Returns how many collapsed.
func ground_changed(area: AABB) -> int:
return structures.ground_changed(area, ground, events)
## 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)
buffer.put_32(entity.armor)
buffer.put_32(entity.selected)
for array: PackedInt32Array in [entity.slot_items, entity.slot_counts, entity.slot_rounds, entity.slot_tiers, entity.ammo]:
buffer.put_data(array.to_byte_array())
buffer.put_32(entity.reload_ticks)
buffer.put_32(entity.use_ticks)
buffer.put_64(roundi(entity.bloom * 1000.0))
buffer.put_32(entity.prev_buttons)
buffer.put_u8(1 if entity.eliminated else 0)
buffer.put_32(entity.last_attacker)
buffer.put_32(entity.item)
buffer.put_32(entity.item_count)
buffer.put_32(entity.item_rounds)
buffer.put_32(entity.item_tier)
buffer.put_32(entity.owner_id)
for value: float in [entity.origin.x, entity.origin.y, entity.origin.z]:
buffer.put_64(roundi(value * 1000.0))
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()