M8: Complete offline match

`make match` plays one whole match from the lobby to the results and back to the
lobby: one scripted player and 23 bots on a local server, with no script errors.

- CommandLog records the seed, the rules and every command the server is given.
  MatchReplay plays a log again with nobody thinking and ends on the same state
  hash; `make match` saves the log, reads it back and checks that.
- ServerLoop.submit() is now the one way commands reach the simulation, so a
  recording server sees them all.
- ScriptedPlayer plays a human seat: it drops, loots, fights and flees as a bot
  does, and also cuts driftwood and builds a breakwater and a wall.
- Bots draw randomness from their own per-bot generators, not the simulation's
  streams. A bot thinking no longer changes the simulation's state, which a
  replay without bots needs.
- MatchView and EntityView draw a match from one Simulation: terrain, sea,
  points of interest, props, pieces, players, the barge, items and chests, with
  stand-in shapes for the art pass to replace.
- `make match-captures` renders eight stages of the recorded match.

Closes #31

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 05:35:32 -05:00
co-authored by Claude Opus 5.5
parent 8cf164d562
commit 1d6a24ab64
38 changed files with 1633 additions and 15 deletions
+4 -4
View File
@@ -229,7 +229,7 @@ func _stop() -> void:
func _drop(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand:
state = "drop"
if _landing < 0 and not world.markers.is_empty() and sim.drop != null:
var rng: RandomNumberGenerator = sim.rng.stream("bots")
var rng: RandomNumberGenerator = nav.stream(sim)
var a: Vector2 = Vector2(sim.drop.start.x, sim.drop.start.z)
var b: Vector2 = Vector2(sim.drop.finish.x, sim.drop.finish.z)
var near: Array[int] = []
@@ -365,7 +365,7 @@ static func _weapon_score(me: SimEntity, slot: int, distance: float) -> float:
func _update_aim_error(sim: Simulation) -> void:
if (sim.tick + player_id) % Tuning.BOT_AIM_WANDER_TICKS == 0:
var rng: RandomNumberGenerator = sim.rng.stream("bots")
var rng: RandomNumberGenerator = nav.stream(sim)
_aim_error_goal = Vector2(rng.randf_range(-1.0, 1.0), rng.randf_range(-0.5, 0.5)) * _aim_error_degrees
_aim_error = _aim_error.lerp(_aim_error_goal, 0.25)
@@ -400,7 +400,7 @@ func _combat_move(sim: Simulation, grid: NavGrid, me: SimEntity, target: SimEnti
to /= gap
var wanted: float = minf(clampf(def.range_full * 0.8, 5.0, 30.0), _fire_range(def) * 0.8)
if sim.tick >= _strafe_until:
var rng: RandomNumberGenerator = sim.rng.stream("bots")
var rng: RandomNumberGenerator = nav.stream(sim)
_strafe = -_strafe
_strafe_until = sim.tick + rng.randi_range(TICKS / 2, TICKS * 2)
var side: Vector2 = Vector2(-to.y, to.x) * _strafe
@@ -758,7 +758,7 @@ func _hunt(sim: Simulation, world: BotWorld) -> void:
var arrived: bool = _goal_set and nav.status != NavBot.MOVING
if not _goal_set or arrived or sim.tick >= _hunt_until:
var phase: int = sim.tide.phase_at(sim.tick) if sim.tide != null else 0
_hunt_goal = world.random_safe(sim.rng.stream("bots"), phase)
_hunt_goal = world.random_safe(nav.stream(sim), phase)
_hunt_until = sim.tick + 40 * TICKS
_go(_hunt_goal, 4.0)
else:
+16 -2
View File
@@ -36,6 +36,20 @@ var _stuck_ticks: int = 0
var _stuck_tries: int = 0
var _jump_next: bool = false
var _leap_tick: int = -1
var _rng: RandomNumberGenerator = null
var _rng_seed: int = 0
## This bot's own random stream, seeded from the match seed and its player ID. Bots
## never draw from the simulation's streams: a bot is a player, and nothing a player
## thinks may change the simulation's state, or a replay of the same commands with no
## bots thinking would end up with a different state hash.
func stream(sim: Simulation) -> RandomNumberGenerator:
if _rng == null or _rng_seed != sim.rng.match_seed:
_rng = RandomNumberGenerator.new()
_rng_seed = sim.rng.match_seed
_rng.seed = _rng_seed ^ SimRng._hash_name("bot:%d" % player_id)
return _rng
func _init(id: int) -> void:
@@ -172,12 +186,12 @@ func _ride(sim: Simulation, player: SimEntity) -> PlayerCommand:
return PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0, buttons)
## A random open dry point within ROAM_RANGE that a path reaches, from the "bots"
## A random open dry point within ROAM_RANGE that a path reaches, from the bot's own
## stream. Plans the path at once, so it uses the tick's planning budget.
func _pick_roam_goal(sim: Simulation, grid: NavGrid, player: SimEntity) -> void:
if not grid.can_plan():
return
var rng: RandomNumberGenerator = sim.rng.stream("bots")
var rng: RandomNumberGenerator = stream(sim)
var centre: Vector3 = player.position
if player.drop_state == Drop.ABOARD:
centre = Vector3(Tuning.WORLD_SIZE_METRES * 0.5, 0.0, Tuning.WORLD_SIZE_METRES * 0.5)
+177
View File
@@ -0,0 +1,177 @@
## A stand-in for a person at the controls, for whole-match runs with no network and
## nobody watching. It plays a human seat through the same door as everyone else: one
## PlayerCommand a tick.
##
## It drops, loots, fights and keeps ahead of the tide as a normal bot does, and adds
## what bots don't do yet: once it has a weapon and nothing more pressing, it cuts
## driftwood with the boathook and builds a breakwater and a wall where it stands. So
## one scripted match exercises the drop, loot, combat, harvesting, building and the
## tide from a player's seat.
class_name ScriptedPlayer
extends BotBrain
const WAIT: int = 0
const HARVEST: int = 1
const BUILD: int = 2
const DONE: int = 3
const STEP_NAMES: Array[String] = ["wait", "harvest", "build", "done"]
## Driftwood to gather before building: a breakwater and a wall, and a swing to spare.
const WANTED_DRIFTWOOD: int = 45
## How far to look for something to cut, in metres.
const SEARCH_RADIUS: float = 45.0
## Starts the script this long after landing even with no weapon found.
const UNARMED_WAIT_SECONDS: float = 45.0
## Gives up on one prop, and on the whole script, after this long.
const PROP_TIMEOUT_SECONDS: float = 25.0
const SCRIPT_TIMEOUT_SECONDS: float = 150.0
## Inside this distance the script walks straight at the prop instead of path-finding.
const DIRECT_METRES: float = 6.0
var step: int = WAIT
## Driftwood gained and pieces placed by the script so far.
var harvested: int = 0
var built: int = 0
var _landed_tick: int = -1
var _script_since: int = 0
var _driving: bool = false
var _prop: int = -1
var _prop_since: int = 0
var _skipped_props: Dictionary = {}
var _to_build: Array[int] = [StructureSet.BREAKWATER, StructureSet.WALL]
var _build_yaw: float = 0.0
var _build_tries: int = 0
var _stock_before: int = -1
var _wood_seen: int = 0
func _init(id: int, level: int = NORMAL) -> void:
super(id, level)
func step_name() -> String:
return STEP_NAMES[step]
func think(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand:
var me: SimEntity = sim.entities.find(player_id)
if me == null or me.eliminated or me.drop_state != Drop.NONE or step == DONE:
return super(sim, grid, world)
if _landed_tick < 0:
_landed_tick = sim.tick
var wood: int = me.materials[Materials.DRIFTWOOD]
if wood > _wood_seen:
harvested += wood - _wood_seen
_wood_seen = wood
var busy: bool = _fleeing or target_id != 0 or _stage != OUTSIDE or me.swimming or not me.on_ground or _heal_slot(me) >= 0
if step == WAIT and not busy:
if _weapon_slot >= 0 or sim.tick - _landed_tick >= roundi(UNARMED_WAIT_SECONDS * TICKS):
step = HARVEST
_script_since = sim.tick
if step != WAIT and sim.tick - _script_since > roundi(SCRIPT_TIMEOUT_SECONDS * TICKS):
step = DONE
if busy or step == WAIT or step == DONE:
_release()
return super(sim, grid, world)
# The script has the controls this tick. Keep the senses going, and hand back to
# the brain on the next tick if they turn anything up.
_driving = true
_sense(sim, world, me)
_check_tide(sim, world, me)
if target_id != 0 or _fleeing:
return _hold(sim, me)
if step == HARVEST:
state = "harvest"
return _harvest(sim, grid, me)
state = "build"
return _build(sim, me)
## Gives the path follower back to the brain with no goal of the script's left in it.
func _release() -> void:
if _driving:
_stop()
_driving = false
_stock_before = -1
func _hold(sim: Simulation, me: SimEntity) -> PlayerCommand:
return PlayerCommand.from_input(sim.tick, Vector2.ZERO, float(me.yaw) / PlayerCommand.YAW_STEPS * TAU, 0.0)
## Walks to the nearest driftwood prop and swings at it until there's enough to build.
func _harvest(sim: Simulation, grid: NavGrid, me: SimEntity) -> PlayerCommand:
if me.materials[Materials.DRIFTWOOD] >= WANTED_DRIFTWOOD:
step = BUILD
_stop()
_build_yaw = float(me.yaw) / PlayerCommand.YAW_STEPS * TAU
return _hold(sim, me)
var standing: bool = _prop >= 0 and sim.props.is_standing(_prop)
if not standing or sim.tick - _prop_since > roundi(PROP_TIMEOUT_SECONDS * TICKS):
if standing:
_skipped_props[_prop] = true
_prop = _find_prop(sim, me)
_prop_since = sim.tick
if _prop < 0:
step = DONE
return _hold(sim, me)
var box: AABB = sim.props.boxes[_prop]
var eye: Vector3 = Harvest.eye(me)
var centre: Vector3 = box.get_center()
var aim: Vector3 = Vector3(centre.x, clampf(eye.y, box.position.y + 0.2, box.end.y - 0.1), centre.z)
var to: Vector3 = aim - eye
var flat: float = Vector2(to.x, to.z).length()
var yaw: float = atan2(to.x, to.z)
if PropSet._distance_to_box(box, eye) <= Harvest.reach() - 0.6:
_stop()
return PlayerCommand.from_input(sim.tick, Vector2.ZERO, yaw, atan2(to.y, flat), PlayerCommand.BUTTON_FIRE, Simulation.BOATHOOK_SLOT)
if flat <= DIRECT_METRES:
_stop()
var buttons: int = PlayerCommand.BUTTON_JUMP if (sim.tick - _prop_since) % (2 * TICKS) == 2 * TICKS - 1 else 0
return PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), yaw, 0.0, buttons)
_go(Vector3(centre.x, box.position.y, centre.z), DIRECT_METRES - 1.0)
var walk: PlayerCommand = nav.think(sim, grid)
if nav.status == NavBot.UNREACHABLE:
_skipped_props[_prop] = true
_prop = -1
return walk
## The nearest standing driftwood prop on dry ground that hasn't been given up on.
func _find_prop(sim: Simulation, me: SimEntity) -> int:
for prop: int in sim.props.near(me.position, SEARCH_RADIUS):
if _skipped_props.has(prop) or sim.props.material_of(prop) != Materials.NAMES[Materials.DRIFTWOOD]:
continue
var box: AABB = sim.props.boxes[prop]
if box.position.y > sim.sea_level + 0.5 and absf(box.position.y - me.position.y) < 8.0:
return prop
return -1
## Places each piece on the list where the player stands, trying each quarter turn.
func _build(sim: Simulation, me: SimEntity) -> PlayerCommand:
var stock: int = me.materials[Materials.DRIFTWOOD]
if _stock_before >= 0:
if stock < _stock_before:
built += 1
_to_build.pop_front()
_build_tries = 0
else:
_build_tries += 1
_build_yaw += PI * 0.5
if _build_tries >= 4:
_to_build.pop_front()
_build_tries = 0
_stock_before = -1
while not _to_build.is_empty() and stock < StructureSet.cost_of(_to_build[0]):
_to_build.pop_front()
if _to_build.is_empty():
step = DONE
return _hold(sim, me)
if me.action_cooldown > 0:
return PlayerCommand.from_input(sim.tick, Vector2.ZERO, _build_yaw, 0.0)
_stock_before = stock
return PlayerCommand.from_input(
sim.tick, Vector2.ZERO, _build_yaw, 0.0,
PlayerCommand.BUTTON_BUILD | PlayerCommand.BUTTON_FIRE, _to_build[0], Materials.DRIFTWOOD)
+1
View File
@@ -0,0 +1 @@
uid://n65m74kr6a20
+213
View File
@@ -0,0 +1,213 @@
## Draws what moves in a match: players, the sky barge while it crosses, items lying
## in the world and sea chests. `sync()` matches everything to the simulation as it is
## now. These are stand-in shapes built in code, in the weathered seafaring palette of
## docs/ORIGINALITY.md: an oilskin coat, a sou'wester and a canvas wing-sail. The art
## pass replaces them. Nothing here is ever used for collision.
class_name EntityView
extends Node3D
## Oilskin colours. A player's is picked by entity ID; the local player wears the first.
const OILSKINS: Array[Color] = [
Color(0.86, 0.66, 0.16), Color(0.56, 0.27, 0.20), Color(0.33, 0.55, 0.56), Color(0.36, 0.40, 0.30),
Color(0.48, 0.46, 0.44), Color(0.30, 0.36, 0.48), Color(0.62, 0.44, 0.28),
]
const SKIN: Color = Color(0.74, 0.58, 0.46)
const CANVAS: Color = Color(0.84, 0.80, 0.68)
const TAR: Color = Color(0.19, 0.16, 0.13)
const PLANK: Color = Color(0.50, 0.45, 0.37)
const CHEST_SHUT: Color = Color(0.33, 0.55, 0.56)
const CHEST_OPEN: Color = Color(0.22, 0.20, 0.18)
const ITEM: Color = Color(0.93, 0.80, 0.42)
## How far apart passengers stand on the barge's deck, in metres. The simulation
## carries them all at one point; this only spreads them out to be seen.
const DECK_SPACING: float = 1.3
const DECK_ROWS: int = 4
## The entity drawn in the brightest oilskin, or 0.
var local_id: int = 0
var _sim: Simulation
## Entity ID -> the figure's root node.
var _figures: Dictionary = {}
var _barge: Node3D
var _pickups: MultiMeshInstance3D
var _chests: MultiMeshInstance3D
func setup(sim: Simulation) -> void:
_sim = sim
_barge = _build_barge()
_barge.visible = false
add_child(_barge)
_pickups = _box_field("Pickups", Vector3(0.34, 0.34, 0.34), true)
add_child(_pickups)
_chests = _box_field("Chests", Vector3(0.9, 0.55, 0.6), false)
add_child(_chests)
sync()
func figure_count() -> int:
return _figures.size()
## The figure drawn for a player, or null.
func figure_of(entity_id: int) -> Node3D:
return _figures.get(entity_id)
func barge() -> Node3D:
return _barge
func sync() -> void:
if _sim == null:
return
var drop: Drop = _sim.drop
var crossing: bool = drop != null and not drop.finished
var heading: float = 0.0
if drop != null:
var along: Vector3 = drop.finish - drop.start
heading = atan2(along.x, along.z)
_barge.visible = crossing
if crossing:
_barge.position = drop.barge_position(_sim.tick)
_barge.rotation.y = heading
var seen: Dictionary = {}
var aboard: int = 0
for entity: SimEntity in _sim.entities.entities():
if entity.archetype != SimEntity.ARCHETYPE_PLAYER:
continue
seen[entity.id] = true
var figure: Node3D = _figures.get(entity.id)
if figure == null:
figure = _build_figure(entity.id)
_figures[entity.id] = figure
add_child(figure)
figure.visible = not entity.eliminated
figure.position = entity.position
figure.rotation.y = float(entity.yaw) / PlayerCommand.YAW_STEPS * TAU
if entity.drop_state == Drop.ABOARD:
var column: int = aboard / DECK_ROWS
var row: int = aboard % DECK_ROWS
var offset: Vector3 = Vector3((row - (DECK_ROWS - 1) * 0.5) * DECK_SPACING, 0.0, (2.5 - column) * DECK_SPACING)
figure.position += offset.rotated(Vector3.UP, heading)
figure.rotation.y = heading
aboard += 1
figure.scale.y = Tuning.CROUCH_HEIGHT / Tuning.PLAYER_HEIGHT if entity.crouching else 1.0
(figure.get_node("Sail") as Node3D).visible = entity.drop_state == Drop.GLIDING
for entity_id: int in _figures.keys():
if not seen.has(entity_id):
_figures[entity_id].queue_free()
_figures.erase(entity_id)
var items: MultiMesh = _pickups.multimesh
items.instance_count = _sim.pickups.size()
for index: int in _sim.pickups.size():
var pickup: SimEntity = _sim.entities.find(_sim.pickups[index])
var at: Vector3 = pickup.position + Vector3(0.0, 0.3, 0.0) if pickup != null else Vector3(0.0, -1000.0, 0.0)
items.set_instance_transform(index, Transform3D(Basis(Vector3.UP, 0.6 * index), at))
items.set_instance_color(index, ITEM)
var chests: MultiMesh = _chests.multimesh
chests.instance_count = _sim.loot.chest_positions.size()
for index: int in _sim.loot.chest_positions.size():
chests.set_instance_transform(index, Transform3D(Basis.IDENTITY, _sim.loot.chest_positions[index] + Vector3(0.0, 0.28, 0.0)))
chests.set_instance_color(index, CHEST_OPEN if _sim.loot.chest_opened[index] != 0 else CHEST_SHUT)
func _process(_delta: float) -> void:
sync()
func _build_figure(entity_id: int) -> Node3D:
var coat: Color = OILSKINS[0] if entity_id == local_id else OILSKINS[1 + entity_id % (OILSKINS.size() - 1)]
var figure: Node3D = Node3D.new()
figure.name = "player_%d" % entity_id
var legs: BoxMesh = BoxMesh.new()
legs.size = Vector3(0.42, 0.8, 0.26)
figure.add_child(_part(legs, TAR, Vector3(0.0, 0.4, 0.0)))
var body: CapsuleMesh = CapsuleMesh.new()
body.radius = 0.3
body.height = 0.95
figure.add_child(_part(body, coat, Vector3(0.0, 1.05, 0.0)))
var head: SphereMesh = SphereMesh.new()
head.radius = 0.16
head.height = 0.32
figure.add_child(_part(head, SKIN, Vector3(0.0, 1.6, 0.0)))
var brim: CylinderMesh = CylinderMesh.new()
brim.top_radius = 0.17
brim.bottom_radius = 0.33
brim.height = 0.16
# The sou'wester's brim runs long at the back.
figure.add_child(_part(brim, coat.darkened(0.25), Vector3(0.0, 1.76, -0.05)))
var sail_mesh: BoxMesh = BoxMesh.new()
sail_mesh.size = Vector3(2.6, 0.04, 0.9)
var sail: MeshInstance3D = _part(sail_mesh, CANVAS, Vector3(0.0, 2.15, -0.1))
sail.name = "Sail"
sail.rotation.x = deg_to_rad(-8.0)
sail.visible = false
figure.add_child(sail)
return figure
## A flat-bottomed hull hung under a canvas envelope. Its deck is at the origin, where
## the simulation carries the passengers.
func _build_barge() -> Node3D:
var barge: Node3D = Node3D.new()
barge.name = "Barge"
var deck: BoxMesh = BoxMesh.new()
deck.size = Vector3(7.5, 0.3, 11.0)
barge.add_child(_part(deck, PLANK, Vector3(0.0, -0.15, 0.0)))
var hull: BoxMesh = BoxMesh.new()
hull.size = Vector3(6.4, 1.3, 9.6)
barge.add_child(_part(hull, TAR, Vector3(0.0, -0.95, 0.0)))
for side: float in [-1.0, 1.0]:
var rail: BoxMesh = BoxMesh.new()
rail.size = Vector3(0.15, 0.7, 11.0)
barge.add_child(_part(rail, TAR, Vector3(side * 3.68, 0.35, 0.0)))
for end: float in [-1.0, 1.0]:
var rope: CylinderMesh = CylinderMesh.new()
rope.top_radius = 0.05
rope.bottom_radius = 0.05
rope.height = 7.0
barge.add_child(_part(rope, PLANK.darkened(0.3), Vector3(side * 3.4, 3.5, end * 4.6)))
var envelope: SphereMesh = SphereMesh.new()
envelope.radius = 1.0
envelope.height = 2.0
var bag: MeshInstance3D = _part(envelope, CANVAS, Vector3(0.0, 10.5, 0.0))
bag.scale = Vector3(5.2, 3.8, 9.0)
barge.add_child(bag)
return barge
func _part(mesh: PrimitiveMesh, colour: Color, at: Vector3) -> MeshInstance3D:
var material: StandardMaterial3D = StandardMaterial3D.new()
material.albedo_color = colour
material.roughness = 0.85
mesh.material = material
var instance: MeshInstance3D = MeshInstance3D.new()
instance.mesh = mesh
instance.position = at
return instance
func _box_field(node_name: String, size: Vector3, glow: bool) -> MultiMeshInstance3D:
var material: StandardMaterial3D = StandardMaterial3D.new()
material.vertex_color_use_as_albedo = true
material.roughness = 0.7
if glow:
material.emission_enabled = true
material.emission = ITEM
material.emission_energy_multiplier = 0.5
var mesh: BoxMesh = BoxMesh.new()
mesh.size = size
mesh.material = material
var multimesh: MultiMesh = MultiMesh.new()
multimesh.transform_format = MultiMesh.TRANSFORM_3D
multimesh.use_colors = true
multimesh.mesh = mesh
var instance: MultiMeshInstance3D = MultiMeshInstance3D.new()
instance.name = node_name
instance.multimesh = multimesh
instance.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
return instance
+1
View File
@@ -0,0 +1 @@
uid://cx6ttunmd4ng4
+148
View File
@@ -0,0 +1,148 @@
## The client's picture of one match: sky, sun, terrain, sea, points of interest, props,
## built pieces and everything that moves, all drawn from one Simulation, with the
## third-person camera on a player's shoulder. It only reads the simulation.
##
## A match gets a new Simulation, so it gets a new MatchView. Until snapshots arrive
## (v0.5) the simulation it reads is the local server's or a replay's.
class_name MatchView
extends Node3D
var sim: Simulation
var terrain: TerrainView
var water: WaterView
var pois: PoiView
var props: PropView
var structures: StructureView
var entities: EntityView
var camera: Camera3D
var rig: CameraRig = CameraRig.new()
## Builds the scene for `simulation`. `local_id` is the player this client plays, or 0.
func setup(simulation: Simulation, local_id: int = 0) -> void:
sim = simulation
var sky_material: ProceduralSkyMaterial = ProceduralSkyMaterial.new()
sky_material.sky_top_color = Color(0.32, 0.5, 0.68)
sky_material.sky_horizon_color = Color(0.82, 0.78, 0.68)
sky_material.ground_bottom_color = Color(0.18, 0.2, 0.2)
sky_material.ground_horizon_color = Color(0.82, 0.78, 0.68)
var sky: Sky = Sky.new()
sky.sky_material = sky_material
var environment: Environment = Environment.new()
environment.background_mode = Environment.BG_SKY
environment.sky = sky
environment.ambient_light_source = Environment.AMBIENT_SOURCE_SKY
environment.ambient_light_energy = 0.45
environment.tonemap_mode = Environment.TONE_MAPPER_FILMIC
environment.fog_enabled = true
environment.fog_light_color = Color(0.78, 0.78, 0.74)
environment.fog_density = 0.0005
environment.fog_aerial_perspective = 0.4
var world: WorldEnvironment = WorldEnvironment.new()
world.environment = environment
add_child(world)
var sun: DirectionalLight3D = DirectionalLight3D.new()
sun.rotation_degrees = Vector3(-35.0, -130.0, 0.0)
sun.light_energy = 0.95
sun.shadow_enabled = true
sun.directional_shadow_max_distance = 400.0
add_child(sun)
camera = Camera3D.new()
camera.near = CameraRig.NEAR
camera.far = 2500.0
camera.fov = CameraRig.FOV
add_child(camera)
camera.make_current()
if sim.island != null:
terrain = TerrainView.new()
terrain.setup(sim.island)
add_child(terrain)
water = WaterView.new()
add_child(water)
pois = PoiView.new()
pois.setup(sim.pois)
add_child(pois)
props = PropView.new()
props.setup(sim.props)
add_child(props)
structures = StructureView.new()
structures.setup(sim.structures)
add_child(structures)
entities = EntityView.new()
entities.local_id = local_id
entities.setup(sim)
add_child(entities)
sync()
## Matches everything drawn to the simulation as it is now.
func sync() -> void:
water.follow(sim)
props.sync()
structures.sync()
entities.sync()
## Puts the camera on a player's shoulder, looking where they look. `pitch` replaces
## their own pitch when given, in radians, for views such as looking down from a glide.
func follow(entity_id: int, pitch: float = NAN) -> bool:
var player: SimEntity = sim.entities.find(entity_id)
if player == null:
return false
var yaw: float = float(player.yaw) / PlayerCommand.YAW_STEPS * TAU
var look_pitch: float = pitch if not is_nan(pitch) else float(player.pitch) / PlayerCommand.PITCH_MAX * (PI * 0.5)
camera.transform = rig.solve(player.position, yaw, look_pitch, player.crouching, sim.ground)
camera.fov = rig.fov()
_focus()
return true
## Frames a player from outside: the camera stands `distance` metres off at `height`
## above their feet and looks at them, from the first of eight directions that has a
## clear line and no prop around the lens. With `beyond` given, it starts on the far
## side of the player from that point, so the point is in the picture behind them.
func frame(entity_id: int, distance: float = 6.0, height: float = 2.6, beyond: Vector3 = Vector3.INF) -> bool:
var player: SimEntity = sim.entities.find(entity_id)
if player == null:
return false
var chest: Vector3 = player.position + Vector3(0.0, 1.2, 0.0)
var first: float = float(player.yaw) / PlayerCommand.YAW_STEPS * TAU + PI
if beyond != Vector3.INF:
first = atan2(player.position.x - beyond.x, player.position.z - beyond.z)
var eye: Vector3 = chest
for turn: int in 8:
# Straight on first, then alternately to each side.
var angle: float = first + (turn + 1) / 2 * (PI / 4.0) * (1.0 if turn % 2 == 1 else -1.0)
eye = player.position + Vector3(sin(angle) * distance, height, cos(angle) * distance)
eye.y = maxf(eye.y, sim.ground.terrain_height(eye.x, eye.z) + 1.0)
var feet: Vector3 = Vector3(eye.x, sim.ground.terrain_height(eye.x, eye.z), eye.z)
if sim.ground.raycast(chest, eye) >= 1.0 and sim.props.near(feet, 5.0).is_empty():
break
look_from(eye, chest if beyond == Vector3.INF else chest.lerp(beyond, 0.35))
return true
## Puts the camera at `eye`, looking at `target`.
func look_from(eye: Vector3, target: Vector3) -> void:
camera.transform = Transform3D(Basis.IDENTITY, eye).looking_at(target, Vector3.UP)
camera.fov = CameraRig.FOV
_focus()
## The whole island from high over its south-west, as the lobby shows it.
func overview() -> void:
var size: float = Tuning.WORLD_SIZE_METRES
look_from(Vector3(size * 0.2, 300.0, size * 0.92), Vector3(size * 0.5, 0.0, size * 0.47))
## Builds every terrain chunk for the current camera at once. For loading and captures.
func settle() -> void:
if terrain != null:
terrain.build_all_now()
func _focus() -> void:
if terrain != null:
terrain.focus = camera.position
+1
View File
@@ -0,0 +1 @@
uid://ctcbsm7hld1dc
+178
View File
@@ -0,0 +1,178 @@
## A match's seed, rules and every command the server was given, in the order it got
## them. With the same engine build that is enough to play the match again exactly:
## the simulation takes nothing else in. See MatchReplay.
##
## Each record is the simulation tick the command arrived on, the handle it came from
## and the command's own 14 bytes. Commands are logged whether or not the simulation
## accepted them, so a replay turns the same ones down.
##
## On disk: "TWCL", a u32 header length, the header as JSON, a u32 length of the raw
## records, then the records compressed with Zstandard. The seed is a string in the
## header, because JSON numbers can't hold 63 bits.
class_name CommandLog
extends RefCounted
const MAGIC: String = "TWCL"
const VERSION: int = 1
## at-tick u32, handle s32, then the command.
const RECORD_SIZE: int = 8 + PlayerCommand.ENCODED_SIZE
## Refuse files that claim more than this many raw bytes: about four full matches.
const MAX_RAW_BYTES: int = 64 * 1024 * 1024
const RULE_KEYS: Array[String] = [
"max_players", "min_players", "team_size", "lobby_ticks", "countdown_ticks", "results_ticks", "fill_with_bots",
]
var session_seed: int = 0
## Human participants, who join with handles 1 and up before the first tick.
var humans: int = 0
var rules: MatchRules = MatchRules.new()
## What the recording ended with: the simulation tick, its state hash and the winning
## handles. `final_hash` is empty for a recording that was never finished.
var final_tick: int = 0
var final_hash: String = ""
var winners: Array[int] = []
## Free-form notes for whoever reads the file: bot count, difficulty and so on. Not
## needed to replay.
var notes: Dictionary = {}
var _records: StreamPeerBuffer = StreamPeerBuffer.new()
func _init(seed_value: int = 0, human_players: int = 0, match_rules: MatchRules = null) -> void:
session_seed = seed_value
humans = human_players
if match_rules != null:
rules = match_rules
_records.big_endian = false
func count() -> int:
return _records.get_size() / RECORD_SIZE
## Adds a command that arrived from `handle` while the simulation was at `at_tick`.
func record(at_tick: int, handle: int, command: PlayerCommand) -> void:
_records.seek(_records.get_size())
_records.put_u32(at_tick)
_records.put_32(handle)
_records.put_data(command.encode())
func at_tick_of(index: int) -> int:
return _records.data_array.decode_u32(index * RECORD_SIZE)
func handle_of(index: int) -> int:
return _records.data_array.decode_s32(index * RECORD_SIZE + 4)
func command_of(index: int) -> PlayerCommand:
return PlayerCommand.decode(_records.data_array, index * RECORD_SIZE + 8)
## Marks the recording finished with the state it reached.
func finish(flow: Match) -> void:
final_tick = flow.sim.tick
final_hash = flow.sim.state_hash()
winners = flow.winners.duplicate()
func header() -> Dictionary:
var rule_values: Dictionary = {}
for key: String in RULE_KEYS:
rule_values[key] = rules.get(key)
return {
"version": VERSION,
"engine": Engine.get_version_info()["string"],
"seed": str(session_seed),
"humans": humans,
"rules": rule_values,
"records": count(),
"final_tick": final_tick,
"final_hash": final_hash,
"winners": winners,
"notes": notes,
}
func to_bytes() -> PackedByteArray:
var head: PackedByteArray = JSON.stringify(header()).to_utf8_buffer()
var raw: PackedByteArray = _records.data_array
var out: StreamPeerBuffer = StreamPeerBuffer.new()
out.big_endian = false
out.put_data(MAGIC.to_ascii_buffer())
out.put_u32(head.size())
out.put_data(head)
out.put_u32(raw.size())
if raw.size() > 0:
out.put_data(raw.compress(FileAccess.COMPRESSION_ZSTD))
return out.data_array
## Reads a log back, or returns null if the bytes aren't a usable log. Nothing in a bad
## file can raise an error: every length is checked before it is used.
static func from_bytes(bytes: PackedByteArray) -> CommandLog:
if bytes.size() < 12 or bytes.slice(0, 4).get_string_from_ascii() != MAGIC:
return null
var head_size: int = bytes.decode_u32(4)
if head_size <= 0 or 8 + head_size + 4 > bytes.size():
return null
var parser: JSON = JSON.new()
if parser.parse(bytes.slice(8, 8 + head_size).get_string_from_utf8()) != OK or not parser.data is Dictionary:
return null
var head: Dictionary = parser.data
if int(head.get("version", 0)) != VERSION or not head.get("rules") is Dictionary or not str(head.get("seed", "")).is_valid_int():
return null
var raw_size: int = bytes.decode_u32(8 + head_size)
if raw_size < 0 or raw_size > MAX_RAW_BYTES or raw_size % RECORD_SIZE != 0:
return null
var raw: PackedByteArray = PackedByteArray()
if raw_size > 0:
var packed: PackedByteArray = bytes.slice(12 + head_size)
if packed.is_empty():
return null
raw = packed.decompress(raw_size, FileAccess.COMPRESSION_ZSTD)
if raw.size() != raw_size:
return null
var result: CommandLog = CommandLog.new(str(head["seed"]).to_int(), clampi(int(head.get("humans", 0)), 0, Tuning.SOLO_PLAYERS))
var rule_values: Dictionary = head["rules"]
for key: String in RULE_KEYS:
if not rule_values.has(key):
return null
if key == "fill_with_bots":
result.rules.fill_with_bots = bool(rule_values[key])
else:
result.rules.set(key, int(rule_values[key]))
result.rules.max_players = clampi(result.rules.max_players, 1, Tuning.SOLO_PLAYERS)
result.rules.team_size = maxi(result.rules.team_size, 1)
result.final_tick = int(head.get("final_tick", 0))
result.final_hash = str(head.get("final_hash", ""))
if head.get("winners") is Array:
for winner: Variant in head["winners"]:
result.winners.append(int(winner))
if head.get("notes") is Dictionary:
result.notes = head["notes"]
result._records.data_array = raw
return result
## Writes the log to `path`, creating its folder. Returns OK or the error.
func save(path: String) -> Error:
var folder: String = path.get_base_dir()
if not DirAccess.dir_exists_absolute(folder):
var made: Error = DirAccess.make_dir_recursive_absolute(folder)
if made != OK:
return made
var file: FileAccess = FileAccess.open(path, FileAccess.WRITE)
if file == null:
return FileAccess.get_open_error()
file.store_buffer(to_bytes())
file.close()
return OK
## Reads the log at `path`, or returns null if it is missing or unusable.
static func load_from(path: String) -> CommandLog:
if not FileAccess.file_exists(path):
return null
return from_bytes(FileAccess.get_file_as_bytes(path))
+1
View File
@@ -0,0 +1 @@
uid://b0f8jbsbyhwiu
+85
View File
@@ -0,0 +1,85 @@
## Plays a recorded match again from its CommandLog: the same seed, the same rules, the
## same commands on the same ticks, and nobody thinking. Bots and scripted players
## aren't run; their commands are in the log like everyone else's.
##
## The replay covers the log's first match, from the lobby to its results.
class_name MatchReplay
extends RefCounted
var commands: CommandLog
var flow: Match
var sim: Simulation:
get:
return flow.sim
## Server ticks run, lobby and countdown included.
var ticks: int = 0
var _cursor: int = 0
func _init(command_log: CommandLog) -> void:
commands = command_log
flow = Match.new(commands.session_seed, commands.rules)
for handle: int in range(1, commands.humans + 1):
flow.join(handle)
## True once the match's results are in, or the match can't go on.
func finished() -> bool:
return flow.phase == Match.RESULTS
## Runs one server tick. Returns false, doing nothing, once the match has finished.
func step() -> bool:
if finished():
return false
if flow.in_match():
var tick: int = sim.tick
while _cursor < commands.count() and commands.at_tick_of(_cursor) <= tick:
if commands.at_tick_of(_cursor) == tick:
flow.submit_command(commands.handle_of(_cursor), commands.command_of(_cursor))
_cursor += 1
flow.step()
ticks += 1
return true
## Steps until `done` returns true (it is asked before each tick), the match finishes,
## or `limit` server ticks have run. Returns true if `done` was satisfied.
func run_until(done: Callable, limit: int = default_limit()) -> bool:
while ticks < limit:
if done.call():
return true
if not step():
return bool(done.call())
return bool(done.call())
## Steps to the match's results. Returns true if it got there within `limit` ticks.
func run_to_end(limit: int = default_limit()) -> bool:
while ticks < limit and step():
pass
return finished()
## The longest a logged match can take in server ticks: lobby, countdown, the tide's
## whole schedule, and slack.
func default_limit() -> int:
return commands.rules.lobby_ticks + commands.rules.countdown_ticks + Tide.new(0).time_limit_offset() + 60 * Tuning.TICK_RATE_HZ
## Compares where the replay is with what the recording ended on. Call after
## run_to_end(). Returns {"ok", "tick", "expected_tick", "hash", "expected_hash",
## "winners", "expected_winners"}.
func verify() -> Dictionary:
var digest: String = sim.state_hash()
return {
"ok": finished() and not commands.final_hash.is_empty() and digest == commands.final_hash
and sim.tick == commands.final_tick and flow.winners == commands.winners,
"tick": sim.tick,
"expected_tick": commands.final_tick,
"hash": digest,
"expected_hash": commands.final_hash,
"winners": flow.winners.duplicate(),
"expected_winners": commands.winners.duplicate(),
}
+1
View File
@@ -0,0 +1 @@
uid://bbybxusl4dakt
+57 -7
View File
@@ -15,6 +15,10 @@ var sim: Simulation:
## Entity IDs of everyone in the current match, humans first.
var player_ids: Array[int] = []
var bots: Array[BotBrain] = []
## Human seats played by script, when play_humans_by_script() was called.
var scripted: Array[ScriptedPlayer] = []
## When set, every command the server is given during the first match goes in it.
var recorder: CommandLog = null
## The current or next match's navigation grid and bot map, built while the lobby waits.
var nav: NavGrid = null
var world: BotWorld = null
@@ -25,6 +29,8 @@ var tick_usec: PackedInt64Array = PackedInt64Array()
## Server ticks run, across every match.
var ticks: int = 0
var _script_humans: bool = false
## `human_players` join as idle participants with handles 1 and up; `bot_count` bots
## fill the rest of every match. With `rules` null the match starts at once, and the
@@ -32,11 +38,7 @@ var ticks: int = 0
func _init(match_seed: int, human_players: int, bot_count: int, rules: MatchRules = null, difficulty: int = -1) -> void:
bot_difficulty = difficulty
if rules == null:
rules = MatchRules.immediate()
rules.max_players = maxi(human_players + bot_count, 1)
rules.fill_with_bots = bot_count > 0
# With only bots there's nobody to wait for, so the lobby starts with no one in it.
rules.min_players = 0 if human_players == 0 and bot_count > 0 else 1
rules = immediate_rules(human_players, bot_count)
match_flow = Match.new(match_seed, rules)
nav = NavGrid.build(match_flow.sim)
world = BotWorld.build(match_flow.sim, nav)
@@ -47,14 +49,55 @@ func _init(match_seed: int, human_players: int, bot_count: int, rules: MatchRule
_advance()
## Rules for a server that skips the lobby and fills the match with `bot_count` bots.
static func immediate_rules(human_players: int, bot_count: int) -> MatchRules:
var rules: MatchRules = MatchRules.immediate()
rules.max_players = maxi(human_players + bot_count, 1)
rules.fill_with_bots = bot_count > 0
# With only bots there's nobody to wait for, so the lobby starts with no one in it.
rules.min_players = 0 if human_players == 0 and bot_count > 0 else 1
return rules
## Starts recording every command into a new log, which is returned. Call before the
## first tick; the log covers the first match.
func record_commands() -> CommandLog:
var humans: int = 0
for handle: int in match_flow.participants:
if not match_flow.bot_handles.has(handle):
humans += 1
recorder = CommandLog.new(match_flow.session_seed, humans, match_flow.rules)
recorder.notes = {"bot_difficulty": bot_difficulty}
return recorder
## From now on, every human seat is played by a ScriptedPlayer: a stand-in for a
## person at the controls, for whole-match tests before and without the network.
func play_humans_by_script() -> void:
_script_humans = true
if match_flow.in_match():
_track_players()
## Gives the simulation a participant's command for the current match. Returns false
## if it was turned down. This is the one way commands get in, for people, scripts and
## bots alike, so the recorder sees them all.
func submit(handle: int, command: PlayerCommand) -> bool:
if recorder != null and match_flow.matches_started == 1 and match_flow.in_match():
recorder.record(sim.tick, handle, command)
return match_flow.submit_command(handle, command)
## Runs one tick and records how long it took.
func run_tick() -> void:
var started: int = Time.get_ticks_usec()
if match_flow.in_match():
nav.sync(sim)
world.observe(sim)
for player: ScriptedPlayer in scripted:
submit(match_flow.handle_of[player.player_id], player.think(sim, nav, world))
for bot: BotBrain in bots:
sim.submit_command(bot.player_id, bot.think(sim, nav, world))
submit(match_flow.handle_of[bot.player_id], bot.think(sim, nav, world))
_advance()
ticks += 1
tick_usec.append(Time.get_ticks_usec() - started)
@@ -65,9 +108,12 @@ func _advance() -> void:
for event: Dictionary in match_flow.events:
if event["type"] == "match_started":
_track_players()
elif event["type"] == "match_ended" and recorder != null and match_flow.matches_started == 1 and recorder.final_hash.is_empty():
recorder.finish(match_flow)
elif event["type"] == "phase" and event["to"] == "lobby":
player_ids.clear()
bots.clear()
scripted.clear()
if event["from"] == "results":
nav = NavGrid.build(match_flow.sim)
world = BotWorld.build(match_flow.sim, nav)
@@ -76,10 +122,14 @@ func _advance() -> void:
func _track_players() -> void:
player_ids.clear()
bots.clear()
scripted.clear()
for handle: int in match_flow.participants:
var entity_id: int = match_flow.entity_of[handle]
player_ids.append(entity_id)
if match_flow.bot_handles.has(handle):
if not match_flow.bot_handles.has(handle):
if _script_humans:
scripted.append(ScriptedPlayer.new(entity_id))
else:
var level: int = bot_difficulty if bot_difficulty >= 0 else bots.size() % Tuning.BOT_DIFFICULTIES.size()
bots.append(BotBrain.new(entity_id, level))
world.player_ids = player_ids.duplicate()