N10: Playable network client
The client program now turns a connection into a match someone can play. - ClientSession: a ClientGame, the keyboard and mouse as commands (ClientInput), and a MatchView of the client's own copy of the world. - ClientMirror writes what the client is showing into that world every frame: other players from the recent past, its own player where it was predicted, items, the barge, the clock and the sea. The existing views draw it unchanged. - LocalServer: offline play is the same ServerLoop and NetGame in the same process, with packets handed across in memory, so there is one path. - main.gd: --connect=HOST[:PORT] joins a server, otherwise an offline match; --autoplay and --client-seconds=N for scripts and checks. - The camera aboard the barge follows the player's own place on the deck. Tests drive a scripted client through a whole match on a real server over loopback UDP, lobby to results, and through an offline match. `make client-check` does it with two real processes, and `make client-captures` renders what the client sees. Closes #77 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
## What the client was asked to do on the command line.
|
||||
##
|
||||
## tidewall an offline match against bots
|
||||
## tidewall --connect=HOST[:PORT] join a server
|
||||
## options: --name=NAME --seed=N --bots=N (offline) --autoplay
|
||||
## --client-seconds=N quit after N seconds, saying what happened
|
||||
##
|
||||
## Menus replace most of this later. Under tools/godot.sh, which has no window, a mode
|
||||
## has to be asked for: --offline or --connect.
|
||||
class_name ClientConfig
|
||||
extends RefCounted
|
||||
|
||||
const DEFAULT_NAME: String = "Islander"
|
||||
const DEFAULT_BOTS: int = Tuning.SOLO_PLAYERS - 1
|
||||
|
||||
## Empty to play offline.
|
||||
var host: String = ""
|
||||
var port: int = ServerConfig.DEFAULT_PORT
|
||||
var player_name: String = DEFAULT_NAME
|
||||
var match_seed: int = 0
|
||||
var has_seed: bool = false
|
||||
var bots: int = DEFAULT_BOTS
|
||||
var autoplay: bool = false
|
||||
## Quit after this many seconds; 0 runs until the window is closed.
|
||||
var seconds: float = 0.0
|
||||
## True when --offline or --connect was given.
|
||||
var asked: bool = false
|
||||
var errors: Array[String] = []
|
||||
|
||||
|
||||
static func parse(args: PackedStringArray) -> ClientConfig:
|
||||
var config: ClientConfig = ClientConfig.new()
|
||||
for arg: String in args:
|
||||
var parts: PackedStringArray = arg.split("=", true, 1)
|
||||
var value: String = parts[1] if parts.size() == 2 else ""
|
||||
match parts[0]:
|
||||
"--offline":
|
||||
config.asked = true
|
||||
"--autoplay":
|
||||
config.autoplay = true
|
||||
"--connect":
|
||||
config.asked = true
|
||||
var at: int = value.rfind(":")
|
||||
config.host = value if at < 0 else value.substr(0, at)
|
||||
if at >= 0:
|
||||
var port_text: String = value.substr(at + 1)
|
||||
config.port = port_text.to_int() if port_text.is_valid_int() else 0
|
||||
if config.host.is_empty():
|
||||
config.errors.append("--connect needs a host, as in --connect=192.0.2.7:%d" % ServerConfig.DEFAULT_PORT)
|
||||
if config.port < 1 or config.port > 65535:
|
||||
config.errors.append("the port in --connect must be between 1 and 65535")
|
||||
"--name":
|
||||
config.player_name = value
|
||||
"--seed":
|
||||
config.has_seed = value.is_valid_int()
|
||||
config.match_seed = value.to_int()
|
||||
if not config.has_seed:
|
||||
config.errors.append("--seed must be a whole number, got '%s'" % value)
|
||||
"--bots":
|
||||
config.bots = value.to_int()
|
||||
if not value.is_valid_int() or config.bots < 0 or config.bots > Tuning.SOLO_PLAYERS - 1:
|
||||
config.errors.append("--bots must be between 0 and %d, got '%s'" % [Tuning.SOLO_PLAYERS - 1, value])
|
||||
"--client-seconds":
|
||||
config.seconds = value.to_float()
|
||||
if not value.is_valid_float() or config.seconds <= 0.0:
|
||||
config.errors.append("--client-seconds must be a number above 0, got '%s'" % value)
|
||||
_:
|
||||
if arg.begins_with("--"):
|
||||
config.errors.append("unknown option '%s'" % arg)
|
||||
return config
|
||||
|
||||
|
||||
func is_valid() -> bool:
|
||||
return errors.is_empty()
|
||||
@@ -0,0 +1 @@
|
||||
uid://bkko3gtgadosa
|
||||
@@ -0,0 +1,146 @@
|
||||
## The client program while it is in a game: a ClientGame fed by a server (one across
|
||||
## the network, or a LocalServer in this process when playing offline), the keyboard
|
||||
## and mouse turned into its commands, and a MatchView drawing the client's world as
|
||||
## ClientMirror fills it in.
|
||||
##
|
||||
## pump() does a frame's work and needs no scene tree, so tests drive it directly.
|
||||
class_name ClientSession
|
||||
extends Node3D
|
||||
|
||||
var game: ClientGame = ClientGame.new()
|
||||
var mirror: ClientMirror = ClientMirror.new()
|
||||
var input: ClientInput = ClientInput.new()
|
||||
## The connection, when playing on a server across the network.
|
||||
var link: NetClient = null
|
||||
## The server in this process, when playing offline.
|
||||
var local: LocalServer = null
|
||||
## The picture of the current match's world, or null before there is one.
|
||||
var view: MatchView = null
|
||||
## Every match phase this client has been in, in order, without repeats.
|
||||
var phases: Array[int] = []
|
||||
## Frames in which the client's own player was in the match, and frames pumped.
|
||||
var frames_playing: int = 0
|
||||
var frames: int = 0
|
||||
|
||||
var _viewed: Simulation = null
|
||||
var _status: Label = null
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
game.sample_input = _sample
|
||||
|
||||
|
||||
## Starts joining the server at `host`. Returns an error if the socket can't be made.
|
||||
func connect_to(host: String, port: int, player_name: String) -> Error:
|
||||
link = NetClient.new()
|
||||
game.attach(link)
|
||||
return link.connect_to(host, port, player_name)
|
||||
|
||||
|
||||
## Starts an offline match of this player and `bots` bots on a server in this process.
|
||||
func play_offline(match_seed: int, bots: int, rules: MatchRules = null) -> void:
|
||||
local = LocalServer.new(match_seed, bots, rules)
|
||||
|
||||
|
||||
## Leaves the server, if there is one across the network.
|
||||
func leave() -> void:
|
||||
if link != null:
|
||||
link.leave()
|
||||
|
||||
|
||||
## One line saying where things stand, for the corner of the screen and the log.
|
||||
func status_text() -> String:
|
||||
if link != null and link.state != NetClient.JOINED:
|
||||
return link.status_text()
|
||||
if game.world == null:
|
||||
return "Waiting for the server"
|
||||
var phase: String = Match.PHASE_NAMES[game.match_phase]
|
||||
if game.match_phase == Match.LOBBY or game.match_phase == Match.COUNTDOWN:
|
||||
return "In the %s" % phase
|
||||
if game.playing():
|
||||
return ""
|
||||
return "Watching" if game.match_phase != Match.RESULTS else "The match is over"
|
||||
|
||||
|
||||
## One frame: packets in, commands out, and the picture brought up to date.
|
||||
func pump(delta: float) -> void:
|
||||
frames += 1
|
||||
input.poll()
|
||||
if link != null:
|
||||
game.poll()
|
||||
if local != null:
|
||||
local.advance(delta, game)
|
||||
game.advance(delta)
|
||||
if game.world != null and (phases.is_empty() or phases[phases.size() - 1] != game.match_phase):
|
||||
phases.append(game.match_phase)
|
||||
if game.playing():
|
||||
frames_playing += 1
|
||||
mirror.sync(game)
|
||||
_show(delta)
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
_status = Label.new()
|
||||
_status.position = Vector2(24.0, 20.0)
|
||||
_status.add_theme_font_size_override("font_size", 22)
|
||||
_status.add_theme_color_override("font_outline_color", Color(0.08, 0.08, 0.08))
|
||||
_status.add_theme_constant_override("outline_size", 6)
|
||||
add_child(_status)
|
||||
if DisplayServer.get_name() != "headless" and not input.autoplay:
|
||||
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
|
||||
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
pump(delta)
|
||||
if _status != null:
|
||||
_status.text = status_text()
|
||||
|
||||
|
||||
func _unhandled_input(event: InputEvent) -> void:
|
||||
var captured: bool = Input.mouse_mode == Input.MOUSE_MODE_CAPTURED
|
||||
var key: InputEventKey = event as InputEventKey
|
||||
var click: InputEventMouseButton = event as InputEventMouseButton
|
||||
if key != null and key.pressed and key.physical_keycode == KEY_ESCAPE:
|
||||
# Escape lets go of the mouse; a click takes it back.
|
||||
Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
|
||||
elif click != null and click.pressed and not captured and not input.autoplay:
|
||||
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
|
||||
else:
|
||||
input.handle(event, captured)
|
||||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
leave()
|
||||
|
||||
|
||||
func _sample(tick: int) -> PlayerCommand:
|
||||
if input.autoplay and game.world != null:
|
||||
return input.autoplay_command(tick, game.prediction.player, game.world.ground)
|
||||
return input.command(tick)
|
||||
|
||||
|
||||
## Draws the client's world: a new MatchView whenever there is a new world, and the
|
||||
## camera on the watched player's shoulder, or over the island when there is nobody.
|
||||
func _show(delta: float) -> void:
|
||||
if game.world != _viewed:
|
||||
_viewed = game.world
|
||||
if view != null:
|
||||
remove_child(view)
|
||||
view.queue_free()
|
||||
view = null
|
||||
if _viewed != null:
|
||||
view = MatchView.new()
|
||||
view.setup(_viewed, 0)
|
||||
add_child(view)
|
||||
move_child(view, 0)
|
||||
if view == null:
|
||||
return
|
||||
view.entities.local_id = mirror.own_id if mirror.own_id != 0 else view.entities.local_id
|
||||
view.entities.barge_at = mirror.barge_at
|
||||
view.rig.update_aim(input.aiming() and mirror.own_id != 0, delta)
|
||||
view.sync()
|
||||
if mirror.own_id != 0:
|
||||
# The player's own look is newer than any command made from it.
|
||||
view.follow(mirror.own_id, input.pitch, input.yaw)
|
||||
elif mirror.watched_id == 0 or not view.follow(mirror.watched_id):
|
||||
view.overview()
|
||||
@@ -0,0 +1 @@
|
||||
uid://c8vm3i2nd55jh
|
||||
+55
-3
@@ -1,18 +1,70 @@
|
||||
## Application entry point. Picks the mode from the command line:
|
||||
##
|
||||
## tools/godot.sh -- --server [options] headless dedicated server (see ServerConfig)
|
||||
## tidewall [options] the game: an offline match, or
|
||||
## tidewall --connect=HOST[:PORT] a match on a server (see ClientConfig)
|
||||
##
|
||||
## Client startup is added by later milestones.
|
||||
## Without a window (tools/godot.sh is always headless) the game only starts when
|
||||
## --offline or --connect asks for it, so a bare run prints a line and stops.
|
||||
extends Node
|
||||
|
||||
var _config: ClientConfig
|
||||
var _session: ClientSession
|
||||
var _left: float = 0.0
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
var args: PackedStringArray = OS.get_cmdline_user_args()
|
||||
if not args.has("--server"):
|
||||
# Also accept --server before the "--" separator.
|
||||
args = OS.get_cmdline_args()
|
||||
var all: PackedStringArray = OS.get_cmdline_args()
|
||||
if all.has("--server"):
|
||||
args = all
|
||||
var config: ServerConfig = ServerConfig.parse(args)
|
||||
if config.server:
|
||||
add_child(HeadlessServer.new(config))
|
||||
return
|
||||
print("Tidewall")
|
||||
_config = ClientConfig.parse(args)
|
||||
if not _config.is_valid():
|
||||
for problem: String in _config.errors:
|
||||
printerr("tidewall: " + problem)
|
||||
get_tree().quit(2)
|
||||
return
|
||||
if DisplayServer.get_name() == "headless" and not _config.asked:
|
||||
print("Tidewall")
|
||||
return
|
||||
_session = ClientSession.new()
|
||||
_session.input.autoplay = _config.autoplay
|
||||
if _config.host.is_empty():
|
||||
var match_seed: int = _config.match_seed if _config.has_seed else int(Time.get_unix_time_from_system() * 1000.0) & 0x7FFFFFFF
|
||||
_session.play_offline(match_seed, _config.bots)
|
||||
else:
|
||||
var error: Error = _session.connect_to(_config.host, _config.port, _config.player_name)
|
||||
if error != OK:
|
||||
printerr("tidewall: couldn't open a connection: %s" % error_string(error))
|
||||
get_tree().quit(1)
|
||||
return
|
||||
add_child(_session)
|
||||
_left = _config.seconds
|
||||
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if _session == null or _config.seconds <= 0.0:
|
||||
return
|
||||
_left -= delta
|
||||
if _left > 0.0:
|
||||
return
|
||||
# A timed run says what happened, for scripts: one JSON line.
|
||||
var phases: Array[String] = []
|
||||
for phase: int in _session.phases:
|
||||
phases.append(Match.PHASE_NAMES[phase])
|
||||
var joined: bool = _session.local != null or _session.link.state == NetClient.JOINED
|
||||
print(JSON.stringify({
|
||||
"event": "client", "joined": joined, "status": _session.status_text(), "phases": phases,
|
||||
"frames": _session.frames, "frames_playing": _session.frames_playing,
|
||||
"world_messages": _session.game.replica.applied, "bad_packets": _session.game.bad_packets,
|
||||
"corrections": _session.game.prediction.mispredictions,
|
||||
}))
|
||||
_session.leave()
|
||||
_session = null
|
||||
get_tree().quit(0 if joined else 1)
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
## Turns the keyboard and mouse into the local player's commands, one per tick.
|
||||
##
|
||||
## Keys (physical positions, so they sit the same on any layout):
|
||||
## W A S D move · Space jump · Ctrl crouch · Shift sprint · left mouse use or fire ·
|
||||
## right mouse aim · R reload · E pick up or open · G drop the held item ·
|
||||
## 1 the boathook, 2 to 6 the five slots · B build mode on and off ·
|
||||
## in build mode 1 to 5 pick wall, floor, ramp, roof or breakwater, Tab the material,
|
||||
## and left mouse places.
|
||||
## Rebinding and gamepads come with the settings menu.
|
||||
##
|
||||
## With `autoplay` on, a simple script plays instead: it leaps from the barge over
|
||||
## land, glides, and walks about. That is for tests and for checking a connection with
|
||||
## nobody at the keyboard.
|
||||
class_name ClientInput
|
||||
extends RefCounted
|
||||
|
||||
var settings: InputSettings = InputSettings.new()
|
||||
## The look direction, in radians, in the simulation's convention.
|
||||
var yaw: float = 0.0
|
||||
var pitch: float = 0.0
|
||||
## What is held down now: Vector2(strafe right, forward) and PlayerCommand.BUTTON_ bits.
|
||||
var move: Vector2 = Vector2.ZERO
|
||||
var buttons: int = 0
|
||||
## The held selection outside build mode: 0 the boathook, 1 to 5 a slot.
|
||||
var slot: int = 0
|
||||
var build_mode: bool = false
|
||||
## The piece kind and material placed in build mode.
|
||||
var build_kind: int = StructureSet.WALL
|
||||
var material: int = Materials.DRIFTWOOD
|
||||
var autoplay: bool = false
|
||||
|
||||
|
||||
func aiming() -> bool:
|
||||
return buttons & PlayerCommand.BUTTON_AIM != 0 and not build_mode
|
||||
|
||||
|
||||
## Reads what is held down from the keyboard and mouse. Call once a frame.
|
||||
func poll() -> void:
|
||||
if autoplay:
|
||||
return
|
||||
move = Vector2(
|
||||
_axis(KEY_D, KEY_A),
|
||||
_axis(KEY_W, KEY_S),
|
||||
)
|
||||
buttons = 0
|
||||
var keys: Dictionary = {
|
||||
KEY_SPACE: PlayerCommand.BUTTON_JUMP, KEY_CTRL: PlayerCommand.BUTTON_CROUCH,
|
||||
KEY_SHIFT: PlayerCommand.BUTTON_SPRINT, KEY_R: PlayerCommand.BUTTON_RELOAD,
|
||||
KEY_E: PlayerCommand.BUTTON_INTERACT, KEY_G: PlayerCommand.BUTTON_DROP,
|
||||
}
|
||||
for key: Key in keys:
|
||||
if Input.is_physical_key_pressed(key):
|
||||
buttons |= int(keys[key])
|
||||
if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
|
||||
buttons |= PlayerCommand.BUTTON_FIRE
|
||||
if Input.is_mouse_button_pressed(MOUSE_BUTTON_RIGHT):
|
||||
buttons |= PlayerCommand.BUTTON_AIM
|
||||
|
||||
|
||||
## Takes one input event: mouse motion turns the look, and keys that act once per
|
||||
## press do. `captured` says whether the mouse belongs to the game just now.
|
||||
func handle(event: InputEvent, captured: bool) -> void:
|
||||
if autoplay:
|
||||
return
|
||||
var motion: InputEventMouseMotion = event as InputEventMouseMotion
|
||||
if motion != null and captured:
|
||||
turn(motion.relative)
|
||||
return
|
||||
var key: InputEventKey = event as InputEventKey
|
||||
if key != null and key.pressed and not key.echo:
|
||||
press(key.physical_keycode)
|
||||
|
||||
|
||||
## Turns the look by a mouse motion, in pixels.
|
||||
func turn(relative: Vector2) -> void:
|
||||
var look: Vector2 = settings.apply_mouse(relative, yaw, pitch, aiming())
|
||||
yaw = look.x
|
||||
pitch = look.y
|
||||
|
||||
|
||||
## A key that acts once per press: the number row, build mode and the material.
|
||||
func press(keycode: Key) -> void:
|
||||
if keycode == KEY_B:
|
||||
build_mode = not build_mode
|
||||
elif keycode == KEY_TAB and build_mode:
|
||||
material = (material + 1) % Materials.NAMES.size()
|
||||
elif keycode >= KEY_1 and keycode <= KEY_9:
|
||||
var number: int = keycode - KEY_1
|
||||
if build_mode:
|
||||
if number < StructureSet.KINDS.size():
|
||||
build_kind = number
|
||||
elif number <= Inventory.slot_count():
|
||||
slot = number
|
||||
|
||||
|
||||
## The command for `tick`, from what is held now.
|
||||
func command(tick: int) -> PlayerCommand:
|
||||
var pressed: int = buttons
|
||||
var selection: int = slot
|
||||
if build_mode:
|
||||
pressed |= PlayerCommand.BUTTON_BUILD
|
||||
selection = build_kind
|
||||
return PlayerCommand.from_input(tick, move, yaw, pitch, pressed, selection, material)
|
||||
|
||||
|
||||
## The script's command for `tick`: `me` is the client's copy of its own player and
|
||||
## `ground` the island under it.
|
||||
func autoplay_command(tick: int, me: SimEntity, ground: SimGround) -> PlayerCommand:
|
||||
var centre: float = Tuning.WORLD_SIZE_METRES * 0.5
|
||||
yaw = atan2(centre - me.position.x, centre - me.position.z)
|
||||
pitch = deg_to_rad(-12.0)
|
||||
move = Vector2.ZERO
|
||||
buttons = 0
|
||||
if me.drop_state == Drop.ABOARD:
|
||||
# Over dry land, with a moment to look about first.
|
||||
if tick > 3 * Tuning.TICK_RATE_HZ and ground.terrain_height(me.position.x, me.position.z) > Tuning.ISLAND_BEACH_TOP + 2.0:
|
||||
buttons = PlayerCommand.BUTTON_JUMP
|
||||
elif me.drop_state != Drop.NONE:
|
||||
move = Vector2(0.0, 1.0)
|
||||
else:
|
||||
# Walk a slow circle about the middle of the island, with a hop now and then.
|
||||
var seconds: float = float(tick) / Tuning.TICK_RATE_HZ
|
||||
yaw += sin(seconds * 0.4) * 1.2
|
||||
move = Vector2(0.0, 1.0) if fmod(seconds, 9.0) < 6.0 else Vector2.ZERO
|
||||
if tick % (4 * Tuning.TICK_RATE_HZ) == 0:
|
||||
buttons = PlayerCommand.BUTTON_JUMP
|
||||
return command(tick)
|
||||
|
||||
|
||||
func _axis(positive: Key, negative: Key) -> float:
|
||||
return (1.0 if Input.is_physical_key_pressed(positive) else 0.0) - (1.0 if Input.is_physical_key_pressed(negative) else 0.0)
|
||||
@@ -0,0 +1 @@
|
||||
uid://x752jdh6pmnn
|
||||
@@ -25,6 +25,9 @@ const DECK_ROWS: int = 4
|
||||
|
||||
## The entity drawn in the brightest oilskin, or 0.
|
||||
var local_id: int = 0
|
||||
## Where to draw the barge, when its owner knows better than the simulation's tick: a
|
||||
## network client, which draws between ticks. Vector3.INF leaves it to the tick.
|
||||
var barge_at: Vector3 = Vector3.INF
|
||||
|
||||
var _sim: Simulation
|
||||
## Entity ID -> the figure's root node.
|
||||
@@ -70,7 +73,7 @@ func sync() -> void:
|
||||
heading = atan2(along.x, along.z)
|
||||
_barge.visible = crossing
|
||||
if crossing:
|
||||
_barge.position = drop.barge_position(_sim.tick)
|
||||
_barge.position = barge_at if barge_at != Vector3.INF else drop.barge_position(_sim.tick)
|
||||
_barge.rotation.y = heading
|
||||
|
||||
var seen: Dictionary = {}
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
## 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.
|
||||
## A match gets a new Simulation, so it gets a new MatchView. In play the simulation is
|
||||
## the client's own copy of the world, which ClientMirror fills with what the server
|
||||
## has sent; captures and tests also point it at a server's or a replay's.
|
||||
class_name MatchView
|
||||
extends Node3D
|
||||
|
||||
@@ -86,14 +87,21 @@ func sync() -> void:
|
||||
|
||||
|
||||
## 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:
|
||||
## their own pitch when given, in radians, for views such as looking down from a glide,
|
||||
## and `look_yaw` their yaw, for the local player, whose look is newer than any command.
|
||||
func follow(entity_id: int, pitch: float = NAN, look_yaw: 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 yaw: float = look_yaw if not is_nan(look_yaw) else 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)
|
||||
# Where the figure is drawn: on the barge's deck that is its own place, not the
|
||||
# one point the simulation carries every passenger at.
|
||||
var feet: Vector3 = player.position
|
||||
var figure: Node3D = entities.figure_of(entity_id)
|
||||
if figure != null and player.drop_state == Drop.ABOARD:
|
||||
feet = figure.position
|
||||
camera.transform = rig.solve(feet, yaw, look_pitch, player.crouching, sim.ground)
|
||||
camera.fov = rig.fov()
|
||||
_focus()
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
## Writes what a ClientGame is showing into the client's own copy of the world, so
|
||||
## that everything which draws a Simulation draws a networked match the same way.
|
||||
##
|
||||
## The client's world is a Simulation that is never stepped. ClientWorld keeps its
|
||||
## pieces, props, chests and tide in line with the server. This adds the rest of the
|
||||
## picture, afresh every frame: every entity the server has told this client about,
|
||||
## where it is being drawn now (everyone else from the recent past, the client's own
|
||||
## player where it was predicted), the barge, the clock and the sea level. Nothing
|
||||
## here is authoritative, and nothing reads it back but views and the client's own
|
||||
## check before placing a piece.
|
||||
class_name ClientMirror
|
||||
extends RefCounted
|
||||
|
||||
## The entity the camera belongs on: the client's own player, or whoever it is
|
||||
## spectating. 0 outside a match.
|
||||
var watched_id: int = 0
|
||||
## The client's own player while it is in the match, or 0.
|
||||
var own_id: int = 0
|
||||
## Where the barge is being drawn, or Vector3.INF when it isn't crossing.
|
||||
var barge_at: Vector3 = Vector3.INF
|
||||
## The moment being drawn, in simulation ticks.
|
||||
var time: float = 0.0
|
||||
|
||||
var _drop: Drop = null
|
||||
var _drop_world: Simulation = null
|
||||
|
||||
|
||||
func sync(game: ClientGame) -> void:
|
||||
var world: Simulation = game.world
|
||||
watched_id = 0
|
||||
own_id = 0
|
||||
barge_at = Vector3.INF
|
||||
if world == null:
|
||||
return
|
||||
var receiver: SnapshotReceiver = game.receiver
|
||||
var playing: bool = game.playing()
|
||||
var in_match: bool = receiver.own_id != 0 and game.remote.started
|
||||
if playing:
|
||||
# The own player is drawn part way through the newest predicted tick.
|
||||
time = float(game.prediction.next_tick - 1) + game.clock.fraction()
|
||||
elif in_match:
|
||||
time = game.remote.time
|
||||
else:
|
||||
time = float(receiver.sim_tick)
|
||||
world.tick = maxi(floori(time), 0)
|
||||
world.sea_level = world.tide.level_at(world.tick) if world.tide != null else receiver.sea_level
|
||||
|
||||
if in_match:
|
||||
if _drop == null or _drop_world != world:
|
||||
# The route comes from the seed alone, as the server's does.
|
||||
_drop = Drop.plan(world.ground, SimRng.new(game.world_seed), 0)
|
||||
_drop_world = world
|
||||
_drop.finished = _drop.is_over(world.tick)
|
||||
world.drop = _drop
|
||||
if not _drop.finished:
|
||||
barge_at = _drop.barge_position(world.tick).lerp(_drop.barge_position(world.tick + 1), time - floorf(time))
|
||||
else:
|
||||
world.drop = null
|
||||
|
||||
var seen: Dictionary = {}
|
||||
var pickups: Array[int] = []
|
||||
var projectiles: Array[int] = []
|
||||
if in_match:
|
||||
for entity_id: int in receiver.entities:
|
||||
var record: PackedInt32Array = receiver.entities[entity_id]
|
||||
var shown: Dictionary = game.remote.sample(entity_id)
|
||||
if shown.is_empty():
|
||||
continue
|
||||
var archetype: int = record[NetSnapshot.R_ARCHETYPE]
|
||||
var entity: SimEntity = world.entities.find(entity_id)
|
||||
if entity == null:
|
||||
entity = world.entities.restore(entity_id, archetype)
|
||||
elif entity.archetype != archetype:
|
||||
continue
|
||||
seen[entity_id] = true
|
||||
entity.position = shown["position"]
|
||||
match archetype:
|
||||
SimEntity.ARCHETYPE_PLAYER:
|
||||
_show_player(entity, record, shown)
|
||||
SimEntity.ARCHETYPE_PICKUP:
|
||||
entity.item = record[NetSnapshot.R_ITEM] - 1
|
||||
entity.item_count = record[NetSnapshot.R_COUNT]
|
||||
entity.item_tier = record[NetSnapshot.R_TIER]
|
||||
pickups.append(entity_id)
|
||||
SimEntity.ARCHETYPE_PROJECTILE:
|
||||
entity.item = record[NetSnapshot.R_ITEM] - 1
|
||||
entity.owner_id = record[NetSnapshot.R_OWNER]
|
||||
projectiles.append(entity_id)
|
||||
if seen.has(receiver.own_id):
|
||||
watched_id = receiver.own_id
|
||||
if playing and seen.has(receiver.own_id):
|
||||
own_id = receiver.own_id
|
||||
_show_own(world.entities.find(own_id), game)
|
||||
for entity: SimEntity in world.entities.entities():
|
||||
if not seen.has(entity.id):
|
||||
world.entities.remove(entity.id)
|
||||
pickups.sort()
|
||||
projectiles.sort()
|
||||
world.pickups = pickups
|
||||
world.projectiles = projectiles
|
||||
|
||||
|
||||
func _show_player(entity: SimEntity, record: PackedInt32Array, shown: Dictionary) -> void:
|
||||
var flags: int = record[NetSnapshot.R_FLAGS]
|
||||
entity.yaw = posmod(roundi(float(shown["yaw"]) / TAU * PlayerCommand.YAW_STEPS), PlayerCommand.YAW_STEPS)
|
||||
entity.pitch = clampi(roundi(float(shown["pitch"]) / (PI * 0.5) * PlayerCommand.PITCH_MAX), -PlayerCommand.PITCH_MAX, PlayerCommand.PITCH_MAX)
|
||||
entity.health = record[NetSnapshot.R_HEALTH]
|
||||
entity.armor = record[NetSnapshot.R_ARMOR]
|
||||
entity.on_ground = flags & NetSnapshot.FLAG_ON_GROUND != 0
|
||||
entity.crouching = flags & NetSnapshot.FLAG_CROUCHING != 0
|
||||
entity.swimming = flags & NetSnapshot.FLAG_SWIMMING != 0
|
||||
entity.eliminated = flags & NetSnapshot.FLAG_ELIMINATED != 0
|
||||
entity.drop_state = (flags >> NetSnapshot.FLAG_DROP_SHIFT) & 3
|
||||
# What is in the player's hands, for whoever draws it: the item's code, or -1.
|
||||
entity.item = record[NetSnapshot.R_HELD] - 1
|
||||
if entity.drop_state == Drop.ABOARD and barge_at != Vector3.INF:
|
||||
entity.position = barge_at
|
||||
|
||||
|
||||
## The client's own player: where and how it was predicted, not where the server last
|
||||
## had it.
|
||||
func _show_own(entity: SimEntity, game: ClientGame) -> void:
|
||||
var me: SimEntity = game.prediction.player
|
||||
entity.position = game.own_position()
|
||||
entity.yaw = me.yaw
|
||||
entity.pitch = me.pitch
|
||||
entity.on_ground = me.on_ground
|
||||
entity.crouching = me.crouching
|
||||
entity.swimming = me.swimming
|
||||
entity.drop_state = me.drop_state
|
||||
if me.drop_state == Drop.ABOARD and barge_at != Vector3.INF:
|
||||
entity.position = barge_at
|
||||
@@ -0,0 +1 @@
|
||||
uid://bfhscfjoig3tb
|
||||
@@ -0,0 +1,64 @@
|
||||
## A whole server inside the client program, for playing offline. It is the same
|
||||
## ServerLoop and NetGame a dedicated server runs, and the client talks to it with the
|
||||
## same packets through the same ClientGame; they are handed across in memory instead
|
||||
## of sent over a socket. So offline play and network play are one code path.
|
||||
class_name LocalServer
|
||||
extends RefCounted
|
||||
|
||||
## The one person's handle.
|
||||
const HANDLE: int = 1
|
||||
## If a frame takes long, at most this many ticks are run to catch up.
|
||||
const MAX_TICKS_PER_FRAME: int = 4
|
||||
|
||||
var loop: ServerLoop
|
||||
var game: NetGame
|
||||
|
||||
var _accumulator: float = 0.0
|
||||
var _greeted: bool = false
|
||||
|
||||
|
||||
## A match of one person and `bots` bots. With `rules` null it starts at once, and a
|
||||
## new one starts after each one's results.
|
||||
func _init(match_seed: int, bots: int, rules: MatchRules = null) -> void:
|
||||
loop = ServerLoop.new(match_seed, 1, bots, rules)
|
||||
game = NetGame.new(loop, NetServer.new())
|
||||
game.adopt(HANDLE)
|
||||
|
||||
|
||||
## Runs the server for `delta` seconds of real time, carrying packets both ways.
|
||||
func advance(delta: float, client: ClientGame) -> void:
|
||||
_greet(client)
|
||||
_accumulator += delta
|
||||
var due: int = mini(floori(_accumulator * Tuning.TICK_RATE_HZ), MAX_TICKS_PER_FRAME)
|
||||
_accumulator = minf(_accumulator - float(due) / Tuning.TICK_RATE_HZ, 1.0 / Tuning.TICK_RATE_HZ)
|
||||
for _index: int in due:
|
||||
tick(client)
|
||||
|
||||
|
||||
## One server tick: the client's packets go in, and everything the server has for it
|
||||
## comes out, reliable messages first, in the order a socket would deliver them.
|
||||
func tick(client: ClientGame) -> void:
|
||||
_greet(client)
|
||||
for bytes: PackedByteArray in client.outbox:
|
||||
game.take_input(HANDLE, bytes)
|
||||
client.outbox.clear()
|
||||
loop.run_tick()
|
||||
game.after_tick()
|
||||
for event: Dictionary in loop.match_flow.events:
|
||||
if event["type"] == "phase":
|
||||
client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice())
|
||||
if not game.world_changes.is_empty():
|
||||
client.receive(NetProtocol.CHANNEL_CONTROL, game.world_changes)
|
||||
if game.own_changes.has(HANDLE):
|
||||
client.receive(NetProtocol.CHANNEL_CONTROL, game.own_changes[HANDLE])
|
||||
if game.snapshot_due():
|
||||
client.receive(NetProtocol.CHANNEL_STATE, game.snapshot_for(HANDLE))
|
||||
|
||||
|
||||
## What someone is sent on joining: the match notice, then the whole world.
|
||||
func _greet(client: ClientGame) -> void:
|
||||
if _greeted:
|
||||
return
|
||||
_greeted = true
|
||||
client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice())
|
||||
client.receive(NetProtocol.CHANNEL_CONTROL, game.world_notice())
|
||||
@@ -0,0 +1 @@
|
||||
uid://do7rh3lofmurm
|
||||
@@ -18,6 +18,23 @@ func create(archetype: int) -> SimEntity:
|
||||
return entity
|
||||
|
||||
|
||||
## Creates an entity under an ID chosen elsewhere: a network client's copy of one the
|
||||
## server made. Iteration stays in ascending ID order.
|
||||
func restore(id: int, archetype: int) -> SimEntity:
|
||||
var entity: SimEntity = SimEntity.new(id, archetype)
|
||||
var newest: bool = id >= _next_id
|
||||
_by_id[id] = entity
|
||||
_next_id = maxi(_next_id, id + 1)
|
||||
if not newest:
|
||||
var ids: Array = _by_id.keys()
|
||||
ids.sort()
|
||||
var sorted: Dictionary = {}
|
||||
for key: int in ids:
|
||||
sorted[key] = _by_id[key]
|
||||
_by_id = sorted
|
||||
return entity
|
||||
|
||||
|
||||
## Returns the entity, or null if it doesn't exist or has been removed.
|
||||
func find(id: int) -> SimEntity:
|
||||
return _by_id.get(id)
|
||||
|
||||
Reference in New Issue
Block a user