## 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. `difficulty` is every bot's, as an index ## into Tuning.BOT_DIFFICULTIES, or -1 to mix them. func _init(match_seed: int, bots: int, rules: MatchRules = null, difficulty: int = -1) -> void: loop = ServerLoop.new(match_seed, 1, bots, rules, difficulty) 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 not game.feed_changes.is_empty(): client.receive(NetProtocol.CHANNEL_CONTROL, game.feed_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)) var fx: PackedByteArray = game.fx_for(HANDLE) if not fx.is_empty(): client.receive(NetProtocol.CHANNEL_STATE, fx) ## 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()) client.receive(NetProtocol.CHANNEL_CONTROL, game.feed_notice())