Skip to content

199 netplay 5 the handshake

Alex Diakovsky edited this page Dec 3, 2026 · 2 revisions

199. Netplay 5: the handshake (N4, issues #152 and #16)

Question: document 198 links two machines and starts the match when the host presses Start. Nothing checks that the other machine runs the same game. A different vehicle speed or tile rule on one side would desync the match minutes in, with no hint why. And the joiner started a round trip after the host. What must two machines agree on before they play, which differences can they ignore, and how do they start on the same tick when their clocks are unrelated (issue #152, stage N4, with #16, the gameplay data in the pack identity; 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. This document is N4, the handshake.

Glossary

Term Meaning
identity What a machine tells the other in its hello (NetIdentity.of): its build and the hash of its gameplay data, and its pack's name and version for messages.
build The game's version and build id. An export writes the id (res://build_id.txt): the game's commit and the engine's.
gameplay hash A hash of the loaded pack (all layers resolved), leaving out the fields the match never reads.
art-only difference A pack that differs only in what is drawn, heard or shown in menus: another vehicle picture, another sound, another menu text. Two such machines can play together.
offset How far the joiner's clock is from the host's, measured by the host from ping round trips.
countdown The 3 s between the host's "go" and the first tick, shown on screen as 3, 2, 1.

The answer, up front

  1. Two things must match before the link is any use: the build and the gameplay data. Each machine sends a hello with its NetIdentity as soon as the link opens. Either side that finds the other's different refuses, both ways, with a reason: "build" or "gameplay". Link play offers Start only once both agree.
  2. The gameplay hash is the whole pack, minus a traced list. Every field of the loaded Pack goes in, except those only views, sounds, menus, the player's keys or the machine's own paths read (25 fields, traced below), and the manifest's descriptive keys (name, version, author and so on). A field nobody has traced counts as gameplay. So a new field is safe by default: a wrong guess refuses a link, it never lets a desync through. Dictionaries are hashed with sorted keys, so the same data in another key order is the same data.
  3. The level and the setup are checked by the match itself. After the start message each machine sets the match up and sends the host its SimHash before tick 0. A different hash (another map file, another setup) is refused as "setup". This covers everything that goes into the match, level data included, with no second list to keep.
  4. They start on the same tick. The host pings each joiner five times and keeps the shortest round trip; from it, it reads how far the joiner's clock is from its own. When every machine is ready, the host picks a moment 3 s ahead and sends each joiner that moment in the joiner's clock. Each machine holds its match at tick 0, shows the countdown, and starts its session when its own clock gets there. In the check, two clocks 987,654 ms apart start in the same frame. In CI, two browser pages start within a few ms of each other.
  5. The netplay settings travel with the setup: MatchSetup.net_settings (input delay, window, hash interval) is the host's, and every session runs with it.
  6. An export writes its build id. Two exports of different code must not link, and the pack hash cannot see code. So the game's export plugin writes its commit and the engine's into res://build_id.txt, and NetIdentity.build reads it. A run from the editor says "dev".

The handshake

Both machines send hello with their identity; a different build or gameplay data is refused both ways with the reason; otherwise the host pings the joiner five times and keeps the shortest round trip and the clock offset; Start becomes possible; the host sends start with the match setup and the netplay settings; both load the level and hold it at tick 0; the joiner sends ready with its match hash; the host compares it with its own and refuses a different one as setup; when all are ready the host sends go with a moment three seconds ahead in the joiner's clock; both show the countdown and start their sessions when their own clock reaches it

Mermaid source
sequenceDiagram
  participant H as Host (peer 0)
  participant J as Joiner (peer 1)
  Note over H,J: the link opens (document 198)
  H->>J: hello {identity}
  J->>H: hello {identity}
  alt another build or other gameplay data
    H->>J: refuse {reason, detail}
    Note over H,J: both show why, no Start
  else the same
    loop 5 times
      H->>J: ping {t}
      J->>H: pong {t, j}
    end
    Note over H: shortest round trip, clock offset
    Note over H: Start (Link play)
    H->>J: start {MatchSetup, net_settings}
    Note over H,J: both load the level, hold the match at tick 0
    J->>H: ready {SimHash}
    Note over H: own hash ready too, compared
    H->>J: go {at: host now + 3 s + offset}
    Note over H,J: countdown 3, 2, 1, then both sessions start
  end
Loading

What counts as gameplay data

The hello's identity:

# addons/openfire_engine/game/net/net_identity.gd
static func of(pack: Pack) -> Dictionary:
	var m: Dictionary = pack.manifest if pack != null else {}
	return {"protocol": PROTOCOL, "build": build(), "gameplay": gameplay(pack),
		"pack": {"id": str(m.get("id", "")), "name": str(m.get("name", "")), "version": str(m.get("version", ""))}}

static func refusal(mine: Dictionary, theirs: Dictionary) -> String:
	if int(theirs.get("protocol", -1)) != int(mine.get("protocol", -2)) or str(theirs.get("build")) != str(mine.get("build")):
		return "build"
	if str(theirs.get("gameplay")) != str(mine.get("gameplay")):
		return "gameplay"
	return ""

The hash walks every script variable of the loaded pack and leaves out only the traced fields:

# addons/openfire_engine/game/net/net_identity.gd
const ART_VARS := [
	"pack_dir", "layers", "unsaved_files",                                          # this machine's paths and the mod tool's edits
	"sprites", "atlas_textures", "_page_images", "_shelf", "_dirty_pages", "_sprite_layer",   # the pictures (the match asks get_sprite only for
	"team_sets", "_team_set_of", "team_colours", "team_reference", "team_masks",            # flying pieces, which are out of the sim)
	"projectile_art", "death_skull_data", "palette",
	"audio", "music", "jingles",                                                    # sounds
	"ui_menus", "ui_strings", "ui_skin", "ui_progression", "controls", "controls_editor",   # the front end and this machine's keys
]
const DESCRIPTIVE_KEYS := ["id", "name", "title", "version", "author", "authors", "license", "description", "url", "credits", "base_pack",
	"engine_api_version", "overrides"]

static func gameplay(pack: Pack) -> String:
	...
	for p in pack.get_property_list():
		if not (p["usage"] & PROPERTY_USAGE_SCRIPT_VARIABLE) or ART_VARS.has(p["name"]):
			continue
		var v: Variant = pack.get(p["name"])
		if p["name"] == "manifest":
			var kept := {}
			for k in v:
				if not DESCRIPTIVE_KEYS.has(str(k)):
					kept[k] = v[k]
			v = kept
		buf.put_utf8_string(p["name"])
		_feed(buf, v)
	...

The trace. For each candidate field, every reader in the engine was searched for: the field by name, and Pack's methods that return it (get_sprite, team_variant, get_sound and the rest).

Field(s) Who reads them Verdict
sprites mine_view_3d; through get_sprite: the 3D views, and MatchController only to decide whether a flying piece (DebrisPiece) is made art: flying pieces are out of the sim since S5.6 (document 170), SimHash skips them
team_colours, team_masks, team_sets, _team_set_of, team_reference side_pick_screen and the recolouring of pictures art
audio, music, jingles the sound mixer, music_manager, win_ribbon sound
ui_menus, ui_skin, ui_strings, ui_progression, controls, controls_editor game_flow, placeholder_hud, progression, player_controls, controls_screen front end and this machine's keys
projectile_art, death_skull_data, palette projectile_billboard_3d, death_skull_view, the mod tool art
pack_dir, layers, unsaved_files, the atlas pages and packer state file loading, the mod tool this machine's own
kept: radar_data, hud_panels, selector_data MatchController reads them (the radar ping, panel slot 9, the hangar's choices) gameplay, though they sound like art
kept: manifest (minus its names) MatchController reads spawn_through_hangar gameplay

Three fields that sound like art (the radar's, the HUD panels', the hangar selector's) turned out to be read by the match, so they stay in. That is why the list names what is left out, after a trace, rather than what is put in.

The messages

NetHandshake works over the room channel, with JSON messages. Its poll sends the hello once a link is open and takes in the rest:

# addons/openfire_engine/game/net/net_handshake.gd
func _take(from: int, d: Dictionary) -> void:
	match String(d["kind"]):
		"hello":
			var theirs: Dictionary = d.get("identity", {}) if d.get("identity") is Dictionary else {}
			peers_identity[from] = theirs
			var why := NetIdentity.refusal(identity, theirs)
			if why != "":
				var detail := _detail(why, theirs)
				_send(from, {"kind": "refuse", "reason": why, "detail": _detail(why, theirs, true)})
				_refuse(from, why, detail)
				return
			agreed[from] = true
			hello_agreed.emit(from)
			if is_host():
				_send(from, {"kind": "ping", "t": clock.call()})
		...
		"pong":
			...
			var t0 := int(d.get("t", 0))
			var t1 := int(clock.call())
			var trip := t1 - t0
			if not rtt.has(from) or trip < int(rtt[from]):
				rtt[from] = trip
				offset[from] = int(d.get("j", 0)) - (t0 + t1) / 2
			_pings[from] = int(_pings.get(from, 0)) + 1
			if int(_pings[from]) < PINGS:
				_send(from, {"kind": "ping", "t": clock.call()})

The offset assumes the ping took as long out as back. On the shortest of five trips, any lopsidedness is small: in the check, with delays of one to three frames each way, it was off by 8 ms.

When every machine is ready, the host sets the moment:

# addons/openfire_engine/game/net/net_handshake.gd
func _maybe_go() -> void:
	if not is_host() or ready_hash == "" or go_at >= 0 or not refusal.is_empty():
		return
	var peers := transport.connected_peers()
	for p in peers:
		if not _ready_of.has(p):
			return
		if _ready_of[p] != ready_hash:
			...   # refused as "setup"
			return
	go_at = int(clock.call()) + COUNTDOWN_MS
	for p in peers:
		_send(p, {"kind": "go", "at": go_at + int(offset.get(p, 0))})

The level scene waits

The level scene makes the session as in N3, with the host's settings. Given a handshake, it holds the match and reports ready:

# addons/openfire_engine/game/terrain_view_3d.gd
		net_session = NetSession.new(controller, net_transport, match_setup.me, peers, owners)
		match_setup.apply_net(net_session)
		if net_handshake != null:
			controller.set_process(false)   # nothing runs before the "go"
			net_handshake.mark_ready(SimHash.of_match(controller)["hash"])
			_show_net_label()
		else:
			net_session.start()

Each frame until the session starts, it polls the handshake and shows what it waits for, the countdown, or the refusal:

# addons/openfire_engine/game/terrain_view_3d.gd
func _wait_for_go() -> void:
	net_handshake.poll()
	var no := net_handshake.first_refusal()
	if not no.is_empty():
		_net_label.text = "%s\n%s" % [_net_text("refused", "The other player cannot play this match:"), no[2]]
		return
	if net_handshake.go_due():
		net_session.start()
		controller.set_process(true)
		_net_label.get_parent().queue_free()
		_net_label = null
		return
	var left := net_handshake.countdown_ms()
	_net_label.text = _net_text("waiting", "Waiting for the other player") if left < 0 else str(ceili(left / 1000.0))

A pack can word the two texts with the ui_strings keys net_waiting and net_refused. On the Link play screen the handshake starts when the link opens. Start stays disabled until can_start() (agreed and timed), and a refusal shows its detail, for example different game data: yours is renamed 9.9 (gameplay 656e9e72), the other player's is Engine test fixture 0.1.0 (gameplay 5c360851).

The build id

# openfire-nettest addons/nettest_export/plugin.gd  (_PackExport)
	func _export_begin(_features: PackedStringArray, _is_debug: bool, _path: String, _flags: int) -> void:
		for f in files_under(PACK):
			add_file(f, FileAccess.get_file_as_bytes(f), false)
		# the build id two machines compare before they play together (netplay N4, openfire#152, wiki document 199; NetIdentity.build)
		add_file(NetIdentity.BUILD_FILE, build_id().to_utf8_buffer(), false)

	## OPENFIRE_BUILD_ID if set, otherwise this checkout's commit and the engine's ("game+engine"; a "*" marks uncommitted changes).
	static func build_id() -> String:
		...

The engine's docs/STARTING_A_GAME.md (step 5) now tells a new game to do the same.

First green run: nettest 1b4ec40. Over WebRTC in headless Chromium, each page found the other running the same build and gameplay data. The host timed the link (a 50 ms round trip: both pages share one machine, so most of that is frame timing). The two matches started 28 ms apart, inside the 50 ms the check allows: two pages in one browser get their frames at different moments, so up to about two frames apart is expected. Both pages' 600 hashes equal the recording's, with no desyncs.

Seen, not yet explained: each page stalled on about 212 ticks (waiting at the window's edge for the other's words), against 52 in N3's run, and took 13.3 s for 600 ticks instead of 10.6 s. The CI runners vary from run to run, and this run alone cannot say whether that is the cause. The try-out (N8) measures stalls on real machines.

How it was checked

Check What it proves
engine tests/net_handshake_check.gd Identity: the fixture pack loaded from a copy in another folder hashes the same. Another name and version, a new team colour, a moved sprite pivot, a new sound, a translated string and a key binding leave the hash alone. spawn_through_hangar in the manifest, a new vehicle value and a tile's water rule each change it; another build or protocol is refused as "build", other gameplay data as "gameplay". Two handshakes over LoopbackNet, the joiner's clock 987,654 ms ahead: hello agrees, the host finds the offset (987,646 ms), the start brings the joiner the same setup with the settings (d 3, w 6). The joiner is ready seven frames before the host. Both go at the same true moment after a 179-frame wait with nothing run, never drift apart by a tick, and agree on all 300 confirmed ticks. Refusals, on both sides with the reason: other gameplay data, another build, and a ready hash that differs ("setup", nothing starts)
engine tests/net_link_check.gd The two level scenes now go through the handshake. Both wait at tick 0 through the countdown and start in the same frame; then, as before, they agree on every confirmed tick
openfire-nettest CI (web.yml) The two browser pages run the whole handshake over WebRTC. web_pair.mjs checks they started within 50 ms of each other (one clock, one runner); both pages' 600 confirmed hashes equal the recording's
engine CI (determinism.yml) net_handshake_check and net_link_check on Linux

Not done here

  • The host's settings are not on a screen yet. net_settings takes the defaults (d 2, w 8, a hash every 30 ticks); the room (N5) shows and sets them.
  • Code is told apart only by the build id. A game whose export writes none says "dev", and two "dev" builds with different code would link. The id is the plugin's job, as STARTING_A_GAME says.
  • The offset is measured once, before the start. Clocks that drift during a long match are not corrected. N8's try-out shows whether they need to be.
  • A refusal ends the link. Nothing offers to fetch the other player's pack or build.
  • Still two machines, by link codes. More peers wait for the room server (N6); the handshake itself already handles any number of joiners.

Where the code is (today)

What Where
Identity addons/openfire_engine/game/net/net_identity.gd (NetIdentity: of, build, gameplay, refusal, ART_VARS)
The handshake game/net/net_handshake.gd (NetHandshake)
Settings game/match_setup.gd (net_settings, apply_net)
Link play and the level game/net_link_screen.gd (the handshake from the link's opening, Start when can_start), game/game_flow.gd (passes it on), game/terrain_view_3d.gd (net_handshake, _wait_for_go, the label)
Build id openfire-nettest addons/nettest_export/plugin.gd; the engine's docs/STARTING_A_GAME.md step 5
The checks engine tests/net_handshake_check.gd, tests/net_link_check.gd, tools/ci/web_pair.mjs; openfire-nettest tests/recorded_match/net_pair.gd

Next: N5, #153, document 200: the room. The side-pick screen gets remote rows (each machine's people, the host's computers) and the host's settings, which every machine sees as they change; Next when every machine is ready.

Clone this wiki locally