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
+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