Skip to content

200 netplay 6 the room

Alex Diakovsky edited this page Dec 3, 2026 · 1 revision

200. Netplay 6: the room (N5, issue #153)

Question: after document 199 two linked machines agree they run the same game, and the host presses Start on the Link play screen with a map and some computers it alone picked. The joiner sees nothing of that until the match loads. Its people have no say in which side they play. How do the machines set one match up together, so that every machine sees the same rows, map, rules and netplay settings as they change, each machine picks sides for its own people, and the match starts only once everyone has seen what they are starting (issue #153, stage N5; tracking #43)?

The netplay series: document 195 is the plan (stages N1 to N8); 196 is N1, save and restore; 197 is N2, the rollback session; 198 is N3, WebRTC and link codes; 199 is N4, the handshake. This document is N5, the room.

Glossary

Term Meaning
room The side-pick screen (document 191) while machines are linked: the same match setup on every machine (NetRoom).
host / joiner The machine that made the link code (peer 0) and the machines that answered it (peers 1, 2, ...).
row One player in the setup: a person or a computer, and the side (column) it plays on. In a room each person row carries the peer of the machine it sits at.
own row A row this machine may move: its own people, and on the host the computers too.
Ready A joiner's tick box: "I have seen this room and will play it".
version The host's count of changes to the room. A Ready names the version it was given for.

The answer, up front

  1. The host's setup is the room. Joiners never change it themselves: they ask the host, which checks the ask, applies it, and sends the whole room to every joiner. A star around the host, like the handshake.
  2. The whole room goes out after every change. A setup is a few hundred bytes of JSON, so room_state carries all of it: rows, map, rules, colours, netplay settings and who is ready. Nothing is sent as a change, so no machine can miss one and drift out of step.
  3. Each machine brings its own people (one, or two on a split screen) as rows tagged with its peer. A joiner asks to join with how many; it repeats the ask every 500 ms until the room lists its rows, since the host may open its room after the first ask arrives. "Players on this machine" changes the count later.
  4. Each machine moves only its own rows. The joiner's screen enables only its own arrows. The host checks every move ask against the row's peer, so a forged ask to move someone else's row does nothing.
  5. Computer rows are the host's. It adds, removes and moves them, and its machine runs them in the match (owner peer 0).
  6. The host alone changes the shared picks: the map, the rules, colours, skill, computers, and the netplay settings (input delay, window, and what happens on a lost link). A joiner sees them change but cannot edit them.
  7. Every change clears every Ready, and a stale Ready doesn't count. The host's Start is on once the setup is complete and every joiner has said Ready to the current version. A Ready that crossed a change on the wire names an older version and is ignored.
  8. Start goes through the handshake. The host draws a new seed and sends the setup in the handshake's start message (document 199), so every machine starts the same match, each as itself.
  9. The room outlives the match. After a match every machine returns to the same room for a rematch, the picks kept, and every joiner says Ready again. A lost link takes that machine's rows out. Back leaves the room and closes the link.
  10. The Link play screen now only links. Once the handshake agrees, it hands over to the screen named by its "next" (default "match", the side-pick screen). The map and computer choices it had in N3 and N4 are gone; the room does that now.

The messages

Each joiner asks to join with how many people it brings and repeats the ask until the room lists it; the host adds the joiner's rows and sends the whole room to everyone; a joiner asks to move one of its own rows and the host checks the row is that joiner's, moves it and sends the room again; when the host changes the map, a rule or a setting it raises the version, clears every Ready and sends the room; each joiner says Ready naming the version it saw, and the host ignores a Ready for an older version; once every joiner is ready the host presses Start and sends start with the setup through the handshake

Mermaid source
sequenceDiagram
  participant H as Host (peer 0)
  participant J as Joiner (peer 1)
  Note over H,J: the link is open and the handshake agreed (document 199)
  J->>H: room_join {people: 2}
  Note over J: repeated every 500 ms until the room lists it
  H->>J: room_state {setup, ready, version}
  J->>H: room_move {row, dir}
  Note over H: only if that row is peer 1's
  H->>J: room_state (moved)
  Note over H: the host picks a map, version + 1, every Ready cleared
  H->>J: room_state (new map)
  J->>H: room_ready {on, version}
  Note over H: counts only if version is the current one
  H->>J: room_state (peer 1 ready)
  Note over H: Start (every joiner ready)
  H->>J: start {setup, seed} (the handshake)
Loading
Kind From Carries The host does
room_join joiner how many people it brings adds that many person rows for the peer, raises the version, sends the room (or only sends it again, if the joiner is already listed)
room_people joiner a new count grows or shrinks the peer's rows, last ones first
room_move joiner row index, -1 or +1 moves it, only if the row is a person of that peer
room_ready joiner on or off, the version it saw records it only if the version is current
room_state host the whole setup, who is ready, the version — (joiners replace their copy)

All of them go through the handshake's channel: NetHandshake.poll passes every message whose kind starts with room_ to the room (room_message signal), and the room sends with the handshake's new send.

The room

NetRoom holds the setup. On the host it starts from the host's own picks, keeping its own people and its computers and dropping rows of other machines left from an earlier room:

# addons/openfire_engine/game/net/net_room.gd
func _init(h: NetHandshake, pack: Pack, s: MatchSetup = null, people := 1) -> void:
	handshake = h
	me = h.me
	setup = s if s != null else MatchSetup.new()
	setup.me = me
	h.room_message.connect(_take)
	h.setup_received.connect(func(st: MatchSetup): started.emit(st))
	h.transport.peer_disconnected.connect(func(peer: int): _lost(peer))
	_pack = pack
	_people = clampi(people, 1, MatchSetup.MAX_PEOPLE)
	if is_host():
		# the host's own people stay (at most MAX_PEOPLE), as peer 0's; other machines' rows from an earlier room go
		var mine := setup.rows.filter(func(r): return r["kind"] == "person" and int(r.get("peer", 0)) == 0)
		var computers := setup.rows.filter(func(r): return r["kind"] == "computer")
		for r in mine:
			r["peer"] = 0
		setup.rows = mine + computers
		_set_people_of(0, _people)   # the people the host brings (one unless told), the first of its rows kept
		_map_sides()
	else:
		_ask_to_join()

What a joiner may move, and what the host makes of a move ask:

# addons/openfire_engine/game/net/net_room.gd
func owns_row(i: int) -> bool:
	if i < 0 or i >= setup.rows.size():
		return false
	if setup.rows[i]["kind"] == "computer":
		return is_host()
	return int(setup.rows[i].get("peer", 0)) == me

func _take(from: int, d: Dictionary) -> void:
	match String(d["kind"]):
		...
		"room_move":
			var i := int(d.get("row", -1))
			if is_host() and i >= 0 and i < setup.rows.size() and setup.rows[i]["kind"] == "person" and int(setup.rows[i].get("peer", 0)) == from:
				setup.move_row(i, clampi(int(d.get("dir", 0)), -1, 1), _sides)
				edited()
		"room_ready":
			if is_host() and joiners().has(from):
				# a ready for an older room (the host changed something since) does not count
				var on := bool(d.get("on", false)) and int(d.get("version", -1)) == version
				ready[from] = on
				_broadcast()
				changed.emit()

Every change on the host goes through edited, which is where Ready is cleared:

# addons/openfire_engine/game/net/net_room.gd
func edited() -> void:
	if not is_host():
		return
	_map_sides()
	version += 1
	ready.clear()
	_broadcast()
	changed.emit()

func _broadcast() -> void:
	var r := {}
	for p in ready:
		r[str(p)] = ready[p]
	var msg := {"kind": "room_state", "setup": setup.to_dict(), "ready": r, "version": version}
	for p in joiners():
		handshake.send(p, msg)

Start is on when problem() is empty, in this order: the setup's own problem (no map, a side with nobody), no joiner yet, a joiner not ready, the link not yet timed (the handshake's pings):

# addons/openfire_engine/game/net/net_room.gd
func problem() -> String:
	var p := setup.problem()
	if p != "":
		return p
	if joiners().is_empty():
		return "no_joiner"
	if not all_ready():
		return "not_ready"
	if not handshake.can_start():
		return "linking"
	return ""

func start() -> MatchSetup:
	if not is_host() or problem() != "":
		return null
	setup.match_seed = FxRand.new_seed()
	setup.me = 0
	handshake.send_start(setup)
	return setup

The owners the match gets follow from the rows: each person row's peer, and peer 0 for computers. With the host's person, one person on each of two joiners, and a host computer, the owners are [0, 1, 2, 0].

The side-pick screen as the room

SidePickScreen gets a room; with none it is the one-machine screen of document 191, unchanged. With one, its setup is the room's, every edit goes through the room, and every changed redraws it:

# addons/openfire_engine/game/side_pick_screen.gd
func row_name(i: int) -> String:
	var r: Dictionary = setup_data.rows[i]
	if r["kind"] == "person":
		var n := 1 + setup_data.rows.slice(0, i).filter(func(x): return x["kind"] == "person").size()
		var name := label("person", {"n": n})
		if room == null:
			return name
		var peer := int(r.get("peer", 0))
		name = label("here", {"name": name}) if peer == room.me else label("there", {"name": name, "m": peer + 1})
		return label("is_ready", {"name": name}) if room.ready.get(peer, false) else name
	return label("computer")

func move_row(i: int, dir: int) -> void:
	_focus_key = "%s%d" % ["r" if dir > 0 else "l", i]
	if room != null:
		room.move_own(i, dir)
		return
	setup_data.move_row(i, dir, _sides)
	_rebuild()

func press_start() -> void:
	if room != null:
		var st := room.start()
		if st != null:
			start_pressed.emit(st)
	elif setup_data.problem() == "":
		start_pressed.emit(setup_data)

Below the columns the room adds its own lines: "Players on this machine" (1 or 2), "Ready to play" on a joiner, and the netplay settings, which only the host can change:

# addons/openfire_engine/game/side_pick_screen.gd
func _room_rows() -> void:
	_spin(label("players_here"), room.my_people(), MatchSetup.MAX_PEOPLE, func(v): room.set_people(v))
	...
	if not room.is_host():
		_check(label("ready_check"), room.ready.get(room.me, false), func(on): room.set_ready(on))
	_text(_body, label("netplay"), 0)
	var ns: Dictionary = setup_data.net_settings
	_spin(label("input_delay"), int(ns.get("input_delay", 2)), 8, func(v):
		setup_data.net_settings["input_delay"] = v
		_edited())
	_lock_last()
	...

A joiner has no Start button. Its status line says "Waiting for the host to start.", or "The link to the host was lost." once it is. Every new word is a label a pack can replace through the screen's "labels" (document 191): here, there, is_ready, players_here, ready_check, netplay, input_delay, window, on_disconnect, on_disconnect_computer, on_disconnect_end, no_joiner, not_ready, linking, waiting_host, lost_host. The defaults are plain English, as for the rest of the screen.

MatchSetup.net_settings gains "on_disconnect": "computer" (a computer takes over a lost machine's players) or "end" (the match ends). The room only sets and shares it; N7 acts on it.

How the front end gets there

GameFlow keeps the room across matches. The link screen's linked signal now fires once the handshake agrees, and the flow goes on to the screen's "next":

# addons/openfire_engine/game/game_flow.gd
	s.linked.connect(func(handshake: NetHandshake):
		_net_handshake = handshake
		_net_transport = handshake.transport
		_net_room = null
		show_screen(String(screen.get("next", "match"))))

and the side-pick screen becomes the room while a link is open:

# addons/openfire_engine/game/game_flow.gd
	if _net_handshake != null:
		if _net_room == null:
			_net_room = NetRoom.new(_net_handshake, pack, MatchSetup.from_dict(_match_setup.to_dict()) if _match_setup != null else null)
		else:
			_net_room.new_round()   # back from a match: a rematch, everyone says ready again
		s.room = _net_room
	...
	s.start_pressed.connect(func(setup: MatchSetup):
		_match_setup = setup
		_from_setup = true
		if _net_room == null:
			_close_net()
		start_level(setup.level_id))
	s.back_pressed.connect(func():
		_close_net()
		show_screen(String(screen.get("back", _menus.start))))

new_round also calls the handshake's new reset_round, which forgets the last match's go moment and ready hashes, so the rematch counts down afresh. NetSession.start now drains packets left on the words channel from the last match before its first tick.

Two smaller fixes came with it: MatchSetup.from_dict turns only JSON's floats back into ints and leaves every other value as it came, and the host's default setup, which has two person rows for a split screen, is trimmed to the people the host brings.

How it was checked

Check What it proves
engine tests/net_room_check.gd Three machines over LoopbackNet (one to three frames each way, one packet in ten lost), each with a SidePickScreen in room mode, driven as players would. The joiners' people arrive as rows (host 1, first joiner 2, second 1). The host's map reaches every machine, with its four sides. Each machine moves its own rows and all see [1, 2, 1, 3]. A move of another's row, sent straight or forged as a message, changes nothing. A computer row, a rule, a colour and the netplay settings reach everyone. A joiner's screen has no Start, enables only its own arrows, and cannot add a computer. Ready: Start waits for every joiner; a change clears it; a Ready sent for the older version doesn't count. A joiner dropping to one person is seen everywhere and needs Ready again. Start: every machine gets the same setup and seed, each as itself, owners [0, 1, 2, 0]. Rematch: Ready needed again, the last start forgotten. Lost link: that machine's rows leave every room. After every step all three machines' setups are equal
engine tests/net_link_check.gd, tests/net_handshake_check.gd Still pass: the level scenes start and agree on every confirmed tick
openfire-nettest CI (web.yml) The two browser pages link over WebRTC, open a room each, the joiner says Ready, the host starts from the room. web_pair.mjs now also checks that both pages hand over the same room setup (window.ofRoomState); then, as before, the start gap and all 600 hashes
engine CI (determinism.yml) adds net_room_check on Linux
engine suite 89 checks pass

First green run: nettest 9c65e02, engine 59c390f. Over WebRTC in headless Chromium, both pages went into a room. The joiner found its row listed and said Ready. The host timed the link (a 48 ms round trip) and started. Both pages hand over the same room setup (597 characters of JSON). The matches started 28 ms apart, and both pages' 600 confirmed hashes equal the recording's, with no desyncs. Stalls (183 and 188 ticks, about 13.1 s for 600 ticks) are in line with N4's run, so the room adds nothing to the match's cost.

Not tried here: the room screen by hand in two tabs. The in-app browser pane would not paste a link code into the game, so that part of "done" waits for the user's try-out.

Not done here

  • The disconnect policy is only chosen. on_disconnect travels with the setup; N7 (#155) makes the match act on it.
  • Joiners still link by pasted codes, two machines at a time. The room and the check handle any number of joiners; reaching them needs the signalling server (N6).
  • A joiner's people cannot pick their names or colours. Colours are the host's, as on one machine; names stay "Person n".
  • A lost host ends the room for the joiners (they see why and go Back). Nothing hands the room to another machine.

Where the code is (today)

What Where
The room addons/openfire_engine/game/net/net_room.gd (NetRoom)
Room messages over the handshake game/net/net_handshake.gd (room_message, send, reset_round)
The screen game/side_pick_screen.gd (room, can_edit, _room_rows, the new labels)
The flow game/game_flow.gd (_net_room, _show_side_pick_screen, _show_net_link_screen), game/net_link_screen.gd (linked), game/menu_def.gd ("next")
Settings game/match_setup.gd (net_settings["on_disconnect"], ON_DISCONNECT)
The checks engine tests/net_room_check.gd, tools/ci/web_pair.mjs; openfire-nettest tests/recorded_match/net_pair.gd

Next: N6, #154: signalling and room codes. A small server passes the link offers along, so players type a short room code instead of pasting long ones, and more than two machines can meet. The user chooses where it runs.

Clone this wiki locally