Files
tidewall/src/net/client_world.gd
T
claudeandClaude Opus 5.5 6b21e9d4f1 N5: Replicate building, world damage, tide and loot
Built pieces, props' health, opened chests and the tide's schedule now reach
clients as WORLD messages on the reliable channel, and each player is told
what they carry as OWN messages.

- NetWorld: the WORLD and OWN wire formats, and world_hash(), a digest of
  everything replicated this way.
- WorldSender: one message after each tick in which something changed, the
  same for everyone, and the whole state for someone joining or a new match.
  StructureSet and PropSet keep the change lists it reads.
- ClientWorld: applies them to the client's world, so pieces and broken props
  are solid for prediction. A piece's health follows from its building and
  damage, so building costs nothing on the wire.
- Placing ahead of the server: a provisional piece goes up with the command
  and is replaced by the server's, or taken back once a snapshot shows the
  server had its chance. Snapshots carry the newest WORLD number for that.
- Protocol version 3.

A test plays a whole scripted match on a real island with a ClientGame
attached and compares the two worlds' hashes throughout.

Closes #36

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

215 lines
8.5 KiB
GDScript

## The client's side of WORLD and OWN messages (see NetWorld): keeps the client's copy
## of the match's world, a Simulation that is never stepped, in line with the server's,
## and places the client's own pieces before the server has answered.
##
## What is kept in line: built pieces (with their health and building), props' health,
## opened chests, unspilled crates and the tide's schedule. NetWorld.world_hash() of
## the client's world equals the server's once every message up to a tick has been
## applied and sync() has been called for that tick.
##
## Placing ahead of the server: when the player places a piece and the client's own
## check passes, a provisional piece goes into the world at once, under an ID the
## server never uses, and its cost is held back from the materials shown. The server's
## piece arriving in the same slot replaces it. If a snapshot from after the placing
## tick has arrived, the world messages it speaks of have all arrived too, and no
## piece came, the server turned it down and the provisional piece is taken away.
class_name ClientWorld
extends RefCounted
## Provisional pieces get IDs from here up.
const PROVISIONAL_FIRST_ID: int = 1 << 30
var world: Simulation = null
## The newest WORLD applied: its number (-1 before the first full one) and tick.
var seq: int = -1
var tick: int = 0
## True once anything has been applied that a new match would have to undo.
var dirty: bool = false
## The last OWN (see NetWorld.decode_own), or empty.
var own: Dictionary = {}
## Counts, for tests and the network graph.
var applied: int = 0
var gaps: int = 0
var confirmed: int = 0
var rolled_back: int = 0
## Piece ID -> damage taken, for every piece the server has sent.
var _damage: Dictionary = {}
## Piece ID -> the simulation tick its building began, worked back from how far it had
## got when the server sent it.
var _build_began: Dictionary = {}
## Provisional pieces: {"id", "slot", "kind", "material", "tick", "owner"}.
var _pending: Array[Dictionary] = []
var _next_provisional: int = PROVISIONAL_FIRST_ID
var _build_ready_tick: int = 0
var _loot_planned: bool = false
## Starts again on a freshly made world.
func begin(fresh: Simulation) -> void:
world = fresh
seq = -1
tick = 0
dirty = false
own = {}
_damage.clear()
_build_began.clear()
_pending.clear()
_build_ready_tick = 0
_loot_planned = false
## Applies one decoded WORLD. A full one must be given a world nothing has been applied
## to: see `dirty`.
func take(message: Dictionary) -> void:
if world == null:
return
var structures: StructureSet = world.structures
if message["full"]:
_damage.clear()
_build_began.clear()
elif int(message["seq"]) != seq + 1:
# The channel is reliable and ordered, so this shouldn't happen. Carry on: the
# changes are still true.
gaps += 1
seq = message["seq"]
tick = int(message["tick"]) if message["full"] else maxi(tick, int(message["tick"]))
applied += 1
if message["loot"] and not _loot_planned:
_loot_planned = true
if world.island != null:
# The same rolls the server made, from the same stream and the same props.
world.loot = LootSet.plan(world.rng.stream("loot"), world.pois.loot_markers(), Simulation.crate_spill_points(world.props))
dirty = true
var tide: Dictionary = message["tide"]
if not tide.is_empty():
world.tide = Tide.new(tide["started"], tide["levels"])
dirty = true
for entry: Array in message["pieces"]:
var piece_id: int = entry[NetWorld.P_ID]
dirty = true
if structures.find(piece_id) == null:
_replace_provisional(entry)
structures.add(entry[NetWorld.P_KIND], entry[NetWorld.P_MATERIAL], entry[NetWorld.P_SLOT], entry[NetWorld.P_FACING], entry[NetWorld.P_OWNER], entry[NetWorld.P_PLACED], world.ground, piece_id)
_damage[piece_id] = entry[NetWorld.P_DAMAGE]
_build_began[piece_id] = int(message["tick"]) - int(entry[NetWorld.P_ELAPSED])
_set_progress(piece_id)
var damaged: PackedInt32Array = message["damaged"]
for index: int in range(0, damaged.size(), 2):
if structures.find(damaged[index]) != null:
_damage[damaged[index]] = damaged[index + 1]
_set_progress(damaged[index])
for piece_id: int in message["removed"]:
if structures.remove(piece_id, world.ground):
_damage.erase(piece_id)
_build_began.erase(piece_id)
var props: PackedInt32Array = message["props"]
for index: int in range(0, props.size(), 2):
var prop: int = props[index]
if prop >= world.props.count():
continue
dirty = true
if world.props.damage(prop, world.props.health[prop] - props[index + 1]):
# A broken crate has spilled what it held.
world.loot.crate_contents.erase(prop)
for chest: int in message["chests"]:
if chest < world.loot.chest_opened.size():
world.loot.chest_opened[chest] = 1
dirty = true
## Brings every piece still being built up to simulation tick `sim_tick`.
func sync(sim_tick: int) -> void:
if world == null:
return
tick = maxi(tick, sim_tick)
for piece_id: int in world.structures.building().duplicate():
_set_progress(piece_id)
## The materials the player has to spend: what the server last said, less what the
## provisional pieces will cost.
func available_materials() -> PackedInt32Array:
var materials: PackedInt32Array = PackedInt32Array()
materials.resize(Materials.NAMES.size())
if not own.is_empty():
materials = (own["materials"] as PackedInt32Array).duplicate()
for pending: Dictionary in _pending:
var material: int = pending["material"]
materials[material] = maxi(materials[material] - StructureSet.cost_of(pending["kind"]), 0)
return materials
## Provisional pieces waiting for the server's answer.
func pending_count() -> int:
return _pending.size()
## The player's command for `command_tick` has just been predicted on `player`: if it
## places a piece and the checks the server will make pass here, puts a provisional
## piece in the world. Returns the Building.Result, or -1 if the command places nothing
## or the last piece was too recent.
func try_place(player: SimEntity, command: PlayerCommand, command_tick: int) -> int:
if world == null or command == null or command_tick < _build_ready_tick:
return -1
if not command.is_pressed(PlayerCommand.BUTTON_BUILD) or not command.is_pressed(PlayerCommand.BUTTON_FIRE):
return -1
player.materials = available_materials()
var at: Building.Target = Building.target(player, command.selection)
var result: Building.Result = Building.check(world, player, at, command.material)
if result == Building.Result.OK and Building.would_trap(player, Building.boxes_for_target(at, world.ground)):
result = Building.Result.BLOCKED_BY_PLAYER
if result != Building.Result.OK:
return result
var piece: StructureSet.Piece = world.structures.add(at.kind, command.material, at.slot, at.facing, player.id, command_tick, world.ground, _next_provisional)
_next_provisional += 1
_pending.append({"id": piece.id, "slot": at.slot, "kind": at.kind, "material": command.material, "tick": command_tick, "owner": player.id})
dirty = true
_build_ready_tick = command_tick + Tuning.BUILD_INTERVAL_TICKS
Building.lift(player, piece.boxes)
player.materials = available_materials()
return result
## Called with each snapshot: `sim_tick` is the snapshot's simulation tick and
## `world_seq` the newest WORLD the server had made by then. Takes away every
## provisional piece the server has had its chance to place and didn't. Returns how
## many went.
func settle(sim_tick: int, world_seq: int) -> int:
if _pending.is_empty() or seq < world_seq:
return 0
var waiting: Array[Dictionary] = []
var gone: int = 0
for pending: Dictionary in _pending:
if int(pending["tick"]) >= sim_tick:
waiting.append(pending)
continue
world.structures.remove(pending["id"], world.ground)
gone += 1
_pending = waiting
rolled_back += gone
return gone
## The server's piece `entry` is about to be added: a provisional piece in its slot
## makes way.
func _replace_provisional(entry: Array) -> void:
for index: int in _pending.size():
var pending: Dictionary = _pending[index]
if pending["slot"] != entry[NetWorld.P_SLOT]:
continue
world.structures.remove(pending["id"], world.ground)
_pending.remove_at(index)
if pending["kind"] == entry[NetWorld.P_KIND] and pending["owner"] == entry[NetWorld.P_OWNER]:
confirmed += 1
else:
rolled_back += 1
return
func _set_progress(piece_id: int) -> void:
var piece: StructureSet.Piece = world.structures.find(piece_id)
if piece != null:
# A provisional piece hasn't begun, as far as the server has said.
world.structures.set_progress(piece_id, tick - int(_build_began.get(piece_id, tick)), int(_damage.get(piece_id, 0)))