Stage 2: accounts, characters, permadeath, levels and experience
ci / verify (push) Successful in 47s

Identity is shaped like Steamworks so swapping to it is one subclass and no
schema change: the client presents an opaque ticket, the server validates it
into a stable 64-bit account id, and nothing downstream sees anything else.
LocalAuthProvider takes any ticket at face value -- insecure on purpose, and
labelled as such everywhere, because the point is the shape rather than the
security. Do not ship it.

Characters persist as JSON keyed by account. Account ids are written as decimal
strings because they are 64-bit and JSON numbers are doubles, which would
silently round them. A corrupt store aborts the server rather than starting
empty: starting empty looks like it worked and then saves over every character
on the first level-up.

Levels 1-15, +10 max health each, level DERIVED from lifetime experience rather
than stored beside it, so a hand-edited save cannot produce a level 12 character
with a level 3's experience. Experience is shared undivided across everyone
alive in the instance -- splitting it would make bringing a friend cost you
progress. A level-up heals by what it added, so gaining one mid-fight is relief
rather than a bar that moved further from full.

Death is permanent and unbinds the character entirely: no "return to the hub as
the character who just died", because the run is over. The record is retired,
never deleted. The five-character cap counts LIVING characters only -- counting
the dead would lock a player out of their own account after five deaths.

Verified by tools/diag_progression.tscn, which drives the real server through
kill -> xp -> level -> health and death -> retire -> roster. The bot smoke test
cannot cover that: bots are poor shots and rarely kill anything. Writing it
caught two real ordering bugs -- the death event was dispatched before the
payload that tells the player they died, and the dead character stayed bound to
the peer.

Also added --account and --store so several clients and test runs can coexist
on one machine. The smoke test now uses a scratch store; without it a rerun
resumed the previous run's characters and "a character was created" quietly
stopped being true.

193 tests. check.sh, test.sh, smoke.sh, diag_progression and diag_prediction
all pass.
This commit is contained in:
2026-09-04 00:44:34 +02:00
parent ff5e527ad4
commit 4765bbce28
36 changed files with 1613 additions and 34 deletions
+58
View File
@@ -15,6 +15,9 @@ signal local_hit(damage: int)
signal shot_fired
signal enemy_died
signal boss_died
## The account's character roster changed: created, selected, levelled or died.
signal characters_changed
signal select_failed(reason: String)
var my_peer: int = 0
var instance_id: int = 0
@@ -38,6 +41,9 @@ var _last_move := Vector2.ZERO
# Authoritative mirror of the local player.
var my_hp: int = SimConfig.PLAYER_MAX_HP
## Follows the character's level, so the HUD bar cannot be computed from a
## constant.
var my_max_hp: int = SimConfig.PLAYER_MAX_HP
var my_alive: bool = true
var my_escape: float = 0.0
var my_escaping: bool = false
@@ -59,6 +65,14 @@ var request_escape: bool = false
## Who is online and where, for the hub's player list. Server-pushed.
var roster: Array[Dictionary] = []
## This account's characters, and which one is being played. Server-pushed;
## the client never invents an entry.
var characters: Array[Dictionary] = []
var selected_character: String = ""
## True once the server has told us the roster, so the UI can tell "no
## characters yet" from "not asked yet".
var characters_known: bool = false
## Whole seconds until a cleared dungeon returns the party, or
## Protocol.COUNTDOWN_NONE outside that state.
var cleared_countdown: int = Protocol.COUNTDOWN_NONE
@@ -227,6 +241,49 @@ func on_map_chunks(from_instance: int, data: PackedByteArray) -> void:
NetCodec.decode_map_chunks_into(world.map, data)
func on_characters(data: PackedByteArray) -> void:
var decoded := NetCodec.decode_characters(data)
characters = decoded["characters"]
selected_character = String(decoded["selected"])
characters_known = true
characters_changed.emit()
hud_dirty.emit()
_bot_pick_character()
## A bot has no roster screen to click, so it makes the choice the screen would
## offer: resume a living character, or create one. Without this the smoke test
## would authenticate and then stand at a menu forever.
func _bot_pick_character() -> void:
if not GameOpts.bot_client or not selected_character.is_empty():
return
for c in characters:
if c["active"]:
Net.select_character(String(c["id"]))
return
Net.create_character(GameOpts.player_name)
func on_select_result(result: int, reason: String) -> void:
if result != Protocol.SelectResult.OK:
GameLog.warn("client", "character selection refused: %s" % reason)
select_failed.emit(reason)
## The character currently being played, or an empty dictionary while none is.
func current_character() -> Dictionary:
for c in characters:
if String(c["id"]) == selected_character:
return c
return {}
## True when the player has no character in the world and must pick one -- at
## first login, or after their last one died.
func needs_character() -> bool:
return characters_known and selected_character.is_empty()
func on_roster(data: PackedByteArray) -> void:
roster = NetCodec.decode_roster(data)
hud_dirty.emit()
@@ -301,6 +358,7 @@ func on_snapshot(data: PackedByteArray) -> void:
## land where the client should actually be right now.
func _reconcile(rec: Dictionary) -> void:
my_hp = int(rec["hp"])
my_max_hp = int(rec["max_hp"])
my_alive = (int(rec["flags"]) & Protocol.F_ALIVE) != 0
my_escaping = (int(rec["flags"]) & Protocol.F_ESCAPING) != 0
my_spawn_grace = (int(rec["flags"]) & Protocol.F_SPAWN_GRACE) != 0
+57
View File
@@ -45,6 +45,10 @@ static func encode_snapshot(world: SimWorld,
b.put_float(p.pos.y)
b.put_u16(wrapi(roundi(p.aim / TAU * 65536.0), 0, 65536))
b.put_u16(clampi(p.hp, 0, 65535))
# Sent rather than assumed: max health follows the character's level, so
# a HUD bar computed from a constant would be wrong for anyone past
# level 1, and wrong for every other player in the party.
b.put_u16(clampi(p.max_hp, 1, 65535))
var flags := 0
if p.alive:
flags |= Protocol.F_ALIVE
@@ -61,6 +65,10 @@ static func encode_snapshot(world: SimWorld,
b.put_u8(clampi(roundi(float(p.respawn_lockout) / 6.0), 0, 255))
# Echoed so the owning client knows how far to rewind when reconciling.
b.put_u32(p.last_input_tick)
# Static per character, so sending it every snapshot is slightly
# wasteful -- but it is four bytes, and the alternative is a separate
# message plus the join-ordering bug where someone arrives before it.
b.put_u32(p.colour.to_rgba32())
var live_enemies: Array[SimEnemy] = []
for e in world.enemies.values():
@@ -111,10 +119,12 @@ static func decode_snapshot(data: PackedByteArray) -> Dictionary:
"pos": Vector2(b.get_float(), b.get_float()),
"aim": float(b.get_u16()) / 65536.0 * TAU,
"hp": b.get_u16(),
"max_hp": b.get_u16(),
"flags": b.get_u8(),
"escape": float(b.get_u8()) / 255.0,
"respawn_wait": float(b.get_u8()) / 10.0,
"last_input_tick": b.get_u32(),
"colour": Color.hex(b.get_u32()),
})
var ecount := b.get_u16()
@@ -353,3 +363,50 @@ static func decode_map_chunks_into(map: MapGrid, data: PackedByteArray) -> int:
map.apply_chunk(id, b.get_data(n)[1])
applied += 1
return applied
# --- Character roster -------------------------------------------------------
# Sent once at login and after any change. Low frequency and carries strings,
# like the online roster, so it is the same fixed-header-then-utf8 shape.
static func encode_characters(chars: Array[Character], selected: String) -> PackedByteArray:
var b := StreamPeerBuffer.new()
b.big_endian = false
b.put_utf8_string(selected)
b.put_u8(mini(chars.size(), 255))
for c in chars:
b.put_utf8_string(c.id)
b.put_utf8_string(c.display_name)
b.put_u8(clampi(c.level, 1, 255))
b.put_u32(maxi(c.total_xp, 0))
b.put_u8(clampi(roundi(c.xp_progress() * 255.0), 0, 255))
b.put_u16(clampi(c.max_hp(), 1, 65535))
b.put_u8(1 if c.active else 0)
b.put_u32(c.colour.to_rgba32())
return b.data_array
## Returns { "selected": String, "characters": Array[Dictionary] }.
static func decode_characters(data: PackedByteArray) -> Dictionary:
var out: Array[Dictionary] = []
if data.size() < 1:
return {"selected": "", "characters": out}
var b := StreamPeerBuffer.new()
b.big_endian = false
b.data_array = data
var selected := b.get_utf8_string()
var count := b.get_u8()
for _i in count:
if b.get_available_bytes() <= 0:
break
out.append({
"id": b.get_utf8_string(),
"name": b.get_utf8_string(),
"level": b.get_u8(),
"xp": b.get_u32(),
"progress": float(b.get_u8()) / 255.0,
"max_hp": b.get_u16(),
"active": b.get_u8() == 1,
"colour": Color.hex(b.get_u32()),
})
return {"selected": selected, "characters": out}
+7 -1
View File
@@ -10,7 +10,9 @@ extends RefCounted
## 4: added SimEvent.Type.PLAYER_FIRED. It was inserted mid-enum, which shifts
## the wire value of every event after it -- a mismatched client would
## mis-decode every hit and death, so the handshake has to reject it.
const VERSION := 4
## 5: handshake carries an auth ticket instead of a bare name; added character
## list/select/create messages and per-player max health in the snapshot.
const VERSION := 5
const DEFAULT_PORT := 27015
const MAX_CLIENTS := 32
@@ -25,6 +27,10 @@ const CHANNEL_COUNT := 8
enum InstanceKind { LOBBY, DUNGEON }
## Why a character selection failed. Sent rather than a bare "no", so the UI can
## say something useful instead of appearing broken.
enum SelectResult { OK, NO_SUCH_CHARACTER, CHARACTER_IS_DEAD, LIMIT_REACHED, NOT_AUTHENTICATED }
## Player flags packed into the snapshot's per-player byte.
const F_ALIVE := 1
const F_ESCAPING := 4
+203 -8
View File
@@ -11,6 +11,14 @@ extends Node
var instances: Dictionary[int, Instance] = {}
var peer_instance: Dictionary[int, int] = {}
var peer_names: Dictionary[int, String] = {}
## Authenticated account behind each peer. Set at handshake and never taken
## from anything the client says afterwards.
var peer_accounts: Dictionary[int, int] = {}
## Which character each peer is currently playing.
var peer_characters: Dictionary[int, String] = {}
## Characters, levels and experience. Owned here: the simulation reads a
## player's level, but only this layer ever writes progression.
var store: CharacterStore = null
## Map chunks each peer has been sent, per peer. Reset on every instance
## transfer -- knowledge of one dungeon must not carry into the next.
var peer_chunks: Dictionary[int, Dictionary] = {}
@@ -21,6 +29,14 @@ var _snapshot_phase: int = 0
func _ready() -> void:
if store == null:
store = CharacterStore.new(GameOpts.store_path)
if not store.load_from_disk():
# Refusing to start beats starting empty and saving over everyone's
# characters on the first level-up.
GameLog.error("server", "character store failed to load; refusing to start")
get_tree().quit(1)
return
lobby = Instance.make_lobby(_take_instance_id())
instances[lobby.id] = lobby
GameLog.info("server", "lobby instance %d up" % lobby.id)
@@ -74,8 +90,18 @@ func _dispatch_events(inst: Instance) -> void:
# inst.peers and would otherwise change the list mid-broadcast.
var to_lobby: Array[int] = []
var to_dungeon: Array[int] = []
var died: Array[int] = []
for ev in events:
match int(ev["t"]):
SimEvent.Type.ENEMY_DIED:
_award_kill(inst, Progression.xp_for_enemy(StringName(ev.get("def", ""))))
SimEvent.Type.BOSS_DIED:
_award_kill(inst, Progression.xp_for_boss(StringName(ev.get("def", ""))))
SimEvent.Type.PLAYER_DIED:
# Deferred like the transfers below: the payload has not been
# sent yet, and a player must still receive news of its own
# death before it stops being a member of the instance.
died.append(int(ev["peer"]))
SimEvent.Type.ESCAPE_COMPLETED, SimEvent.Type.RESPAWN_REQUESTED:
var peer := int(ev["peer"])
if not to_lobby.has(peer):
@@ -107,6 +133,8 @@ func _dispatch_events(inst: Instance) -> void:
continue
Net.send_events(peer, NetCodec.encode_events(inst.world.tick, for_peer))
for peer in died:
_on_player_died(inst, peer)
for peer in to_lobby:
_send_to_lobby(peer)
for peer in to_dungeon:
@@ -145,6 +173,8 @@ func _forget_peer(peer_id: int) -> void:
peer_instance.erase(peer_id)
peer_names.erase(peer_id)
peer_chunks.erase(peer_id)
peer_accounts.erase(peer_id)
peer_characters.erase(peer_id)
_broadcast_roster()
@@ -158,22 +188,98 @@ func _release_linkdead(peer_id: int, inst: Instance) -> void:
_forget_peer(peer_id)
func on_hello(peer_id: int, version: int, display_name: String) -> void:
if peer_names.has(peer_id):
## Handshake: validate the ticket into an account, then offer that account's
## characters. A peer is NOT placed in the world here -- it has no character
## yet, and a player without a character has nothing to control.
func on_hello(peer_id: int, version: int, ticket: PackedByteArray) -> void:
if peer_accounts.has(peer_id):
return # a second hello from the same peer is either a bug or an attack
if version != Protocol.VERSION:
GameLog.warn("server", "peer %d protocol %d != %d, rejecting" % [peer_id, version, Protocol.VERSION])
Net.send_reject(peer_id, "protocol mismatch: server %d, client %d" % [Protocol.VERSION, version])
Net.kick(peer_id)
return
# Never trust a client-supplied string for anything but display.
var clean := display_name.strip_edges().substr(0, 24)
if clean.is_empty():
clean = "player%d" % peer_id
peer_names[peer_id] = clean
var account := Net.auth.validate(ticket)
if account == AuthProvider.NO_ACCOUNT:
GameLog.warn("server", "peer %d failed authentication" % peer_id)
Net.send_reject(peer_id, "authentication failed")
Net.kick(peer_id)
return
peer_accounts[peer_id] = account
Net.send_welcome(peer_id)
GameLog.info("server", "peer %d authenticated as account %d (%s)"
% [peer_id, account, Net.auth.provider_name()])
# Auto-select the last character played, so a returning player lands in the
# hub rather than at a menu they have already answered.
var resume := store.last_played(account)
if resume != null:
_enter_world_as(peer_id, resume)
_send_characters(peer_id)
func _send_characters(peer_id: int) -> void:
var account: int = peer_accounts.get(peer_id, AuthProvider.NO_ACCOUNT)
if account == AuthProvider.NO_ACCOUNT:
return
Net.send_characters(peer_id, NetCodec.encode_characters(
store.characters_for(account), peer_characters.get(peer_id, "")))
func on_select_character(peer_id: int, character_id: String) -> void:
var account: int = peer_accounts.get(peer_id, AuthProvider.NO_ACCOUNT)
if account == AuthProvider.NO_ACCOUNT:
Net.send_select_result(peer_id, Protocol.SelectResult.NOT_AUTHENTICATED, "not signed in")
return
# Looked up against THIS account's characters, so a client cannot select
# somebody else's by guessing an id.
var c := store.get_character(account, character_id)
if c == null:
Net.send_select_result(peer_id, Protocol.SelectResult.NO_SUCH_CHARACTER, "no such character")
return
if not c.active:
Net.send_select_result(peer_id, Protocol.SelectResult.CHARACTER_IS_DEAD,
"%s is dead" % c.display_name)
return
_enter_world_as(peer_id, c)
Net.send_select_result(peer_id, Protocol.SelectResult.OK, "")
_send_characters(peer_id)
func on_create_character(peer_id: int, character_name: String) -> void:
var account: int = peer_accounts.get(peer_id, AuthProvider.NO_ACCOUNT)
if account == AuthProvider.NO_ACCOUNT:
Net.send_select_result(peer_id, Protocol.SelectResult.NOT_AUTHENTICATED, "not signed in")
return
var c := store.create_character(account, character_name)
if c == null:
Net.send_select_result(peer_id, Protocol.SelectResult.LIMIT_REACHED,
"%d living characters is the limit" % CharacterStore.MAX_ACTIVE)
return
GameLog.info("server", "account %d created '%s'" % [account, c.display_name])
_enter_world_as(peer_id, c)
Net.send_select_result(peer_id, Protocol.SelectResult.OK, "")
_send_characters(peer_id)
## Put a peer into the hub playing [param c], switching characters if it was
## already in the world.
func _enter_world_as(peer_id: int, c: Character) -> void:
var account: int = peer_accounts[peer_id]
var previous := instance_of(peer_id)
if previous != null:
previous.remove_peer(peer_id)
peer_characters[peer_id] = c.id
peer_names[peer_id] = c.display_name
store.set_last_played(account, c.id)
_place(peer_id, lobby)
GameLog.info("server", "peer %d joined as '%s'" % [peer_id, clean])
var p: SimPlayer = lobby.world.players.get(peer_id)
if p != null:
p.adopt(c)
p.reset_for_instance(lobby.world.spawn_point, 0)
p.adopt(c)
GameLog.info("server", "peer %d playing '%s' (level %d)"
% [peer_id, c.display_name, c.level])
_broadcast_roster()
@@ -228,6 +334,23 @@ func _send_to_lobby(peer_id: int) -> void:
if p != null and p.linkdead:
_release_linkdead(peer_id, from)
return
# The character that just died is retired, so returning "as them" is not an
# option. Fall back to whatever is left, and leave the player at the
# character screen if nothing is.
var account: int = peer_accounts.get(peer_id, AuthProvider.NO_ACCOUNT)
if account != AuthProvider.NO_ACCOUNT:
var current := store.get_character(account, peer_characters.get(peer_id, ""))
if current == null or not current.active:
var replacement := store.last_played(account)
if replacement != null:
_enter_world_as(peer_id, replacement)
else:
if from != null:
from.remove_peer(peer_id)
peer_instance.erase(peer_id)
peer_characters.erase(peer_id)
_send_characters(peer_id)
return
GameLog.info("server", "peer %d escaped to lobby" % peer_id)
_transfer(peer_id, lobby)
@@ -283,6 +406,78 @@ func _stream_map(peer_id: int, inst: Instance) -> void:
NetCodec.encode_map_chunks(inst.world.map, batch))
## Experience is shared by everyone alive in the instance, undivided. Splitting
## it would make bringing a friend cost you progress, which is the opposite of
## what a co-op game wants; the hub roster exists to help people group up.
func _award_kill(inst: Instance, amount: int) -> void:
if amount <= 0 or inst.kind != Protocol.InstanceKind.DUNGEON:
return
for peer in inst.peers:
var p: SimPlayer = inst.world.players.get(peer)
if p == null or not p.alive:
continue
_grant_xp(peer, amount)
func _grant_xp(peer_id: int, amount: int) -> void:
var account: int = peer_accounts.get(peer_id, AuthProvider.NO_ACCOUNT)
var character_id: String = peer_characters.get(peer_id, "")
if account == AuthProvider.NO_ACCOUNT or character_id.is_empty():
return
var levels := store.grant_xp(account, character_id, amount)
if levels <= 0:
return
# A level raises max health immediately, and heals by the amount gained --
# a level-up mid-fight should feel like relief, not like a bar that grew
# further away from full.
var c := store.get_character(account, character_id)
var inst := instance_of(peer_id)
if inst != null:
var p: SimPlayer = inst.world.players.get(peer_id)
if p != null:
var before := p.max_hp
p.level = c.level
p.max_hp = c.max_hp()
p.hp = mini(p.hp + (p.max_hp - before), p.max_hp)
GameLog.info("server", "peer %d reached level %d" % [peer_id, c.level])
_send_characters(peer_id)
## Death is permanent. The character is retired -- kept for archival, never
## deleted -- and the player is taken out of the world entirely.
##
## There is deliberately no "return to the hub as the character who just died":
## the run is over, so the peer is unbound and left at the roster screen to pick
## another or make one. A linkdead player is the exception -- it has nobody to
## show a roster to, so its body is left for the escape channel to resolve.
func _on_player_died(inst: Instance, peer_id: int) -> void:
if inst.kind != Protocol.InstanceKind.DUNGEON:
return
var account: int = peer_accounts.get(peer_id, AuthProvider.NO_ACCOUNT)
var character_id: String = peer_characters.get(peer_id, "")
if account == AuthProvider.NO_ACCOUNT or character_id.is_empty():
return
var c := store.get_character(account, character_id)
if c == null or not c.active:
return
store.retire_character(account, character_id)
GameLog.info("server", "peer %d lost '%s' at level %d"
% [peer_id, c.display_name, c.level])
var p: SimPlayer = inst.world.players.get(peer_id)
if p != null and p.linkdead:
_send_characters(peer_id)
_broadcast_roster()
return
inst.remove_peer(peer_id)
peer_instance.erase(peer_id)
peer_characters.erase(peer_id)
peer_chunks.erase(peer_id)
_send_characters(peer_id)
_broadcast_roster()
# --- Roster -----------------------------------------------------------------
## Tell everyone who is online and where they are, so the hub can show that a