How NetWars Works Chapter 18 of 21, plus appendices

18. A browser multiplayer protocol

Chapter 8 described how the original's computers talk on a 1993 office network, and chapter 13 sketched how browsers could do the same over the internet. This chapter turns that sketch into a complete specification: every identifier and who hands it out, how connections are set up, how players agree on slots, every message byte by byte, how each message is applied, what happens in every step, and how much bandwidth it costs. Two implementations written from this chapter alone should be able to play together.

This chapter is a design, not the original

Nothing in this chapter exists in NetWars 2.06. The original has no ids, no handshake, no acknowledgements and no server (chapter 8). Where this protocol behaves differently from the original, the text says so and says what the original did. The game rules themselves (what a hit costs, what a satellite gives) are not changed here; chapters 4 to 8 and 14 to 17 define them. The choice between the original's behaviour and a fix is made per room by the preset of chapter 20: Modern and Custom rooms use the protocol of this chapter; Authentic rooms use the variant at the end ("Authentic rooms").

Words used in this chapter

The pieces

Every page in a room has one of three roles: lobby (connected to the service only, sees the slot table), player (holds a slot, connected to every other player and every spectator), spectator (no slot, connected to every player, never to another spectator; sends no game state). A room has at most 4 players and 4 spectators; lobby pages are limited only by the service (16 is a sensible cap).

Identifiers

NameTypeAssigned by, whenStartRules
room id16 random bytes, 22 characters of base64urlthe inviter's browser (crypto.getRandomValues), once—In the link's fragment: https://example.org/netwars#room=k7Qx2mZp9aLw4f0NqT1v8w. A fragment never reaches the web server; the page passes it to the service in join. Anyone with the link can join.
session id16 random bytes, base64urlthe tab, the first time it opens the room; kept in sessionStorage—Survives a reload of that tab. A secret between the tab and the service ("I am the tab that held slot 2"); never sent to peers. A duplicated tab copies sessionStorage, so a page must check that no other tab uses its session id (service rules below).
peer idu32the service, at random, at each join of a new page (a reload gets a new one)never 0Unique among the room's present members and those of the last 10 minutes. Names a peer in every game message. Compared as unsigned numbers (who is "polite", tie-breaks); the comparison says nothing about who came first.
slotu8 0..3 (PLAYER 1..4)the service, on claim—Fixes ship model, start corner, radar colour and collision push (chapter 8).
slot generation (gen)u16, wrapsthe service: +1 each time the slot gets a new holder0; first holder gets 1(slot, gen) names one holding of a slot.
grant numberu32the service: +1 per grant in the room0; first grant 1 Orders holdings in time: larger = newer.
roster versionu32the service: +1 per change of the slot tablefirst roster 1 Pages apply rosters in increasing version only; the roster inside welcome always replaces the page's roster, whatever its version (after an empty restart the numbers start again).
life idu16, wrapsthe slot holder: +1 when it enters flight from the name screen and at each respawn0 = no life yet; first life 1Hits name the victim's life.
stepu32each page, its own counter, +1 per simulation step0 at join; first step 1Not shared, not synchronised: it orders one sender's messages and dates its events.
satellite idu16, wrapsthe owner: +1 at every spawn0 = never had one; first spawn 1(owner peer id, satellite id) names one satellite. Never reset while the page lives.
shot idu16, wrapsthe shooter: +1 at every shot firedfirst shot 1 (shooter peer id, shot id) names one laser shot. At most 8 of a peer's shots exist at a time, so wrapping never makes two live shots share an id.
event numberu32each sender, one counter for all its HIT and SAT messagesfirst event 1(sender, event number) names one event. Never wraps in practice (60 events per second for 2 years).

For every sender a receiver keeps lastStep and lastEvent, both 0 until the first message. Wrapping u16 counters are compared with serial-number arithmetic: a is newer than b when (a − b) mod 65,536 is between 1 and 32,767.

Clock and step rate

The signalling service

Messages to and from the service are JSON text, one object per WebSocket message, field t = type. The service handles all messages of a room one at a time, in arrival order, and sends to each page in order (one WebSocket per page keeps that order). Integers are JSON numbers; peer ids, slots and counters are as in the identifier table.

Page to service

tFields (type)Meaning
joinroom (string), session (string), proto ([major, minor]), optional settings ({preset: "authentic" | "modern" | "custom", periodNs: int, rules: 8 lowercase hex digits}), name (string), optional resume ({peer: int, role: "player" | "spectator" | "lobby", slot: int or null, gen: int, grant: int, rosterV: int, reload: bool})Enter the room. The first page of an empty room fixes its settings (its own, or the defaults). A page opening a link sends settings only if the link carries them; without it, it follows the room's settings from welcome.
claimslot (int)Ask for a slot.
spectate—Ask to become a spectator.
release—Give up slot or spectator place; back to lobby.
signalto (int), data: either {description: {type: "offer" | "answer", sdp: string}} or {candidate: RTCIceCandidateInit or null}Relay set-up to one peer. candidate: null = end of candidates.
linkslive ([int])The peers this page's links to are live (definition under "Liveness"), plus peers whose last message had the away flag, for up to 10 minutes. Sent right after every welcome and resumed, then on change (at most once per second) and every 10 s.
namename (string)Name changed.
ice—Ask for fresh STUN/TURN servers.
ping—Every 10 s. A page that has received nothing from the service (pong or anything else) for 5 s after a ping considers the WebSocket dead, closes it and reconnects: a page notices a dead service within 15 s.

Service to page

tFields (type)Meaning
welcomepeer (int), settings, roster, members ([{peer, role, name}]), ice ([RTCIceServer: {urls: string or [string], username?, credential?}]), iceTtl (int, seconds), recovering (bool)Joined.
resumedok (bool), role, slot, gen, grant, reason ("conflict" | "expired") if not okAnswer to a resume, right after welcome.
memberpeer, event ("joined" | "left" | "role"), role, nameSomeone joined, left, or changed role.
rosterv (int), slots (4 entries, each null or {peer, gen, grant, name, state: "held" | "reserved"}), spectators ([int])The slot table, to every page after each change.
claimedslot (int or null for spectate), gen, grantClaim or spectate granted.
deniedslot, reason ("taken" | "reserved" | "full" | "recovering" | "unreachable")Claim or spectate refused.
revokedslot, reason ("unreachable" | "conflict"), partner (int, for unreachable)The service took the slot back.
signalfrom (int), dataRelayed set-up message.
iceice, iceTtlFresh STUN/TURN servers.
errorcode ("version" | "settings" | "room-full" | "session-in-use" | "recovering" | "no-peer" | "peer-away" | "bad-message"), peer (for no-peer)The first four end the join (the WebSocket is closed); "no-peer" answers a signal to a peer that is gone (the page then closes its connection to it).
pong—Answer to ping.
Exact rules: the service

Connections

Who connects to whom

STUN, TURN and candidates

Glare: perfect negotiation

"Glare" is when both sides send an offer at the same time (two newcomers who find each other at once, or a renegotiation). Every connection uses the standard perfect negotiation pattern; in each pair the peer with the larger peer id is polite (it gives way), the other is impolite.

makingOffer = false; ignoreOffer = false; isSettingRemoteAnswerPending = false

pc.onnegotiationneeded = async () =>
    try:
        makingOffer = true
        await pc.setLocalDescription()                       // creates an offer
        signal(to, {description: pc.localDescription})
    catch e: log(e)
    finally: makingOffer = false

pc.onicecandidate = (e) => signal(to, {candidate: e.candidate})   // null at the end

on signal from the peer, data:
    try:
        if data.description:
            d = data.description
            readyForOffer = not makingOffer and
                            (pc.signalingState == "stable" or isSettingRemoteAnswerPending)
            offerCollision = d.type == "offer" and not readyForOffer
            ignoreOffer = (not polite) and offerCollision
            if ignoreOffer: return
            isSettingRemoteAnswerPending = (d.type == "answer")
            await pc.setRemoteDescription(d)                  // the polite side rolls back here
            isSettingRemoteAnswerPending = false
            if d.type == "offer":
                await pc.setLocalDescription()                 // creates the answer
                signal(from, {description: pc.localDescription})
        else if "candidate" in data:
            try:
                if data.candidate == null: await pc.addIceCandidate()   // end of candidates
                else: await pc.addIceCandidate(data.candidate)
            catch e: if not ignoreOffer: log(e)
    catch e: log(e)

negotiation timeout: if signalingState stays "have-local-offer" for 10 s,
    await pc.setLocalDescription({type: "rollback"}) and count a failed attempt

ICE restart, giving up, and meshing again

Exact rules: repairing a connection
  1. When iceConnectionState has been "disconnected" for 2 s, or becomes "failed", the impolite side calls pc.restartIce(). The polite side calls it only if no new offer has arrived 5 s after its own detection (a fallback, so normally only one side starts).
  2. At most 3 restarts within 30 s. Then close the connection.
  3. Meshing again never stops. Whenever the roster shows both pages of a required pair as present and their link is not up and no attempt is running, the page with the smaller peer id creates a new connection and offers, after 2 s; after each failed attempt the wait doubles, up to 60 s; it returns to 2 s once a link has stayed up for 60 s.
  4. While the service is unreachable, no offer can be delivered: repairs wait for it.

Slots

The service sees every page in the room, handles one claim at a time and answers each claim itself. That makes it the natural authority for slots: whatever order messages arrive in at the peers, there is never more than one granted holder per slot.

Exact rules: holding a slot
  1. A lobby page shows the roster: each slot with its name, "Free" or "reconnecting".
  2. Enter on a Free slot sends claim. On denied nothing happens.
  3. On claimed: connect to the required partners; show the name screen (status "not in play", as in the original). Enter flight when every player link is up, or after 5 s at the latest.
  4. Accepting a player's messages: a page accepts STATE from peer p for slot s when its latest roster lists p as holder of s (held or reserved) with the STATE's gen. A STATE with a newer gen than the roster shows is kept as pending for up to 1 s and used when the roster arrives. A STATE from a peer whose link is live but who is missing from the roster (the service is recovering or briefly lost it) is still accepted, as long as no roster names another holder of that slot.
  5. While the service is unreachable no slot changes hands. Holders keep their slots, spectators and lobby pages wait, newcomers cannot join.
  6. Changing role: player → lobby: BYE (reason 1) on all links, release, close all connections. Player → spectator: BYE (reason 1) to spectators and close those links, release, spectate, then a new HELLO (role spectator) on the remaining player links. Spectator → player: release, claim; on claimed a new HELLO (role player, slot, gen) on the player links and new connections, as newcomer, to the spectators. A second HELLO on a link replaces the role, slot and gen of the first.

Why "the lowest peer id wins" is not enough

Chapter 13 mentioned a simpler idea: every page announces its claim to the others, and if two claim the same slot, the lower peer id keeps it. That works only if every claimer hears every other claimer, and in a mesh that is not guaranteed. Example: Ann (peer id 5) and Cid (peer id 9) both claim slot 2. Bo is connected to both; Ann and Cid cannot reach each other. Bo hears both claims and decides "Ann holds slot 2". Ann never hears Cid's claim and flies as slot 2; Cid never hears Ann's and also flies as slot 2. Bo ignores Cid's ship and Cid's hits, but Cid believes they count. Three pages, three different pictures, and no rule applied locally can fix it, because a page can never know whether there is a claim it has not heard. Agreement needs one place that hears every claim: the service.

Partial mesh

"Partial mesh" means some required pair has no live link: A sees B, B sees C, A not C. Players cannot play with a missing link (A's hits on C would never arrive, A would not see C), so one player must go. Care is needed not to evict healthy players because of the one whose network broke.

Exact rules: a missing player–player link (decided by the service)
  1. The pair X–Y (both holders) is down while either X's or Y's latest links report does not list the other as live. The service evaluates a pair only when it has a links report from both sent after their latest welcome or resumed, and never while recovering.
  2. The service counts how long a pair has been down, starting no earlier than the roster that first listed both as holders, and only while both are present. (A partner that silently died is not present: nobody yields to it; its WebSocket times out after 25 s, its slot is reserved for 60 s and then freed.)
  3. When some pairs have been down for 20 s (longer than a negotiation timeout of 10 s plus the first retry), the service revokes one holder: the one that is in the most such pairs; on a tie, the newer grant. It sends that page revoked(unreachable, partner) and frees its slot; the page sends BYE (reason 4) and returns to the lobby with "Could not connect to name". Then it evaluates again. Example: A has lost all its links but keeps its WebSocket; A–B and A–C are down, B–C is up; A is in two pairs, B and C in one each: A is revoked, B and C play on.
  4. Against loops: for 60 s, while the partner is still present, the service answers that page's claim with denied unreachable (it may spectate).
  5. While the service is unreachable nobody is revoked; the game simply goes on with the missing link.
  6. A spectator without a live link to some player shows "no connection" for that slot; nobody else is affected.

Data channel messages

All game messages are binary, little-endian (like the original packet), one message per data channel message, byte 0 = type. Types below 0x80 go on ev, 0x80 and above on st. A receiver ignores unknown types and the bytes after the length it knows (this is how minor versions extend messages). A message shorter than its known length is dropped and logged. Every drop of any message is logged with its reason.

TypeNameChannelBytesSender → receiverWhen
0x01HELLOev48both waysfirst message on a new link; again after a role change
0x02BYEev4leaver → its linksleaving, changing role, revoked, refusing
0x03NAMEev18player → its linksright after each HELLO, and when the name changes
0x10HITev20shooter → victim onlymy shot hit a player
0x20SATev20collector or shooter → owner onlyI collected or shot a satellite
0x80STATEst111 + 44·nplayer → its linksafter every step (to spectators after every 2nd)
0x81PINGst20everyone → its linksevery 500 ms, from a timer
0x82PONGst20answer to PINGat once, in the message handler

A STATE, PING or event that arrives on a link before its HELLO is dropped.

HELLO (0x01), 48 bytes

OffsetTypeFieldMeaning
0u8type0x01
1u8protoMajor1
2u8protoMinor0
3u8role1 player, 2 spectator
4u32periodNsthe room's step period
8u8preset0 Authentic, 1 Modern, 2 Custom
9u8reserved0
10u16reserved0
12u32rulesHashsee "Versions and settings"
16u32peerIdsender's peer id
20i8slot0..3, or −1 for a spectator
21i8statusas in STATE
22u16genslot generation (0 for a spectator)
24u16lifeIdcurrent life (0 if none yet)
26u16satIdid of the current or last satellite (0 if none yet)
28u32stepsender's current step
32u32nextEventthe event number it will use next (≥ 1)
36i32scoreits score
40u8 × 8reserved0

Applying HELLO: if protoMajor, periodNs, preset or rulesHash differ from mine, send BYE (reason 3), close the connection and show "This player runs a different version or settings". If peerId is not the peer the service introduced on this connection, close it. Otherwise: lastStep := max(lastStep, step − 1), lastEvent := max(lastEvent, nextEvent − 1) (a second link from the same peer id must not reopen old numbers), and take role, slot, gen, life, satellite id and score.

BYE (0x02), 4 bytes

0 u8 type 0x02; 1 u8 reason (0 leaving the room, 1 changing role or back to the lobby, 3 incompatible, 4 revoked); 2 u16 reserved. Applying: remove the sender's ship, shot copies and satellite copy at once (no explosion). Its name and last score stay in the score table until the slot gets a new holder.

NAME (0x03), 18 bytes

0 u8 type 0x03; 1 u8 length (0..15); 2 u8 × 16 the name in UTF-8, zero-padded. At most 15 bytes, like the original's 15 characters, cut only between whole characters. The game draws names with the original 8×8 font: 256 glyphs in the order of the PC character set (code page 437, as far as we can tell H; assets/fonts/font8x8.txt). Map each character to that code page; characters it does not have are drawn as ?.

STATE (0x80), 111 + 44·n bytes

The successor of the original's 130-byte packet (chapter 8): the same fields in the same units, plus ids.

OffsetTypeFieldMeaning
0u8type0x80
1u8slot0..3
2u16genslot generation
4u32stepthe sender's step after which this state was taken
8u16lifeIdcurrent life
10i8status0 alive, −1 cloaked, 1 killed, 2 not in play (the original's status word)
11u8flagsbit 0 away (below); other bits 0
12i64 × 3positionx, y, z: world units × 65,536 (the original's 64-bit coordinate, middle word = world unit)
36i64 × 3velocityper step, same format
60i16 × 9axesa (forward), b (right), c (the game's "up" arrow, which points to the bottom of the screen, chapter 3), each x, y, z in Q14 (16,384 = 1.0)
78i32scorethe sender's score
82u16satIdid of the sender's satellite
84i8satKind0 none, 1 shields, 2 cloak, 3 thrust, 4 fire power, −1 exploding
85u8recordSizebytes per shot record: 44 in version 1.0; receivers read the 44 bytes they know and skip the rest
86i64 × 3satPositionas position
110u8nnumber of shot records, 0..8
111recordSize × nshot recordsbelow; fields added by later minor versions go after the records

Shot record, 44 bytes

OffsetTypeFieldMeaning
0u16shotIdshooter's shot id
2u32fireStepthe shooter's step in which it was fired
6u8flagsbit 0 powered, bit 1 exploded
7u8hitMoveif exploded: the move (0..23) after which it hit; else 0
8i64 × 3startposition before its first move: ship position + axis c × 64 world units (so the shot appears just below the centre of the view; player_fire, src/shots.c)
32i32 × 3velocityper step, world units × 65,536: ship velocity + axis a × 1,024 (always fits 32 bits)

The original sent 8 flags (none, flying, flying powered, exploding), and the receiver started its copy from the sender's position when it first saw the flag, so a lost or late packet started the copy in the wrong place and a newcomer never knew when a shot began. Here each shot record goes into the next 4 STATE messages actually sent on each link after the shot was fired, and into the next 4 after it exploded (with bit 1 set). Four copies make a single lost message harmless; a shot whose copies are all lost is simply not drawn, which costs nothing because copies of other players' shots are pictures only (chapter 8).

Exact rules: shot copies
senderStepNow(p) = r_p * (myStepTime - o_p)      // p's current step as I estimate it ("Showing other peers")
t_p              = the sender step at which I draw p's ship now (fractional)

on a shot record r from peer p:
    c = copy (p, r.shotId)
    if c exists and r.flags has "exploded": c.hitMove = r.hitMove, c.exploded = true
    if c does not exist:
        k = floor(t_p) - r.fireStep
        finished = (not exploded and k > 23) or (exploded and k > r.hitMove + 7)
        if not finished: create c from r

drawing copy c at t = t_p:  k = floor(t) - c.fireStep,  m = t - c.fireStep + 1   (moves done)
    k < 0                                   : not drawn yet
    not exploded and k <= 23                : flying at c.start + min(m, 24) * c.velocity
    exploded and k <= c.hitMove             : flying at c.start + min(m, c.hitMove + 1) * c.velocity
    exploded and c.hitMove < k <= hitMove+7 : explosion at c.start + (c.hitMove + 1) * c.velocity
    otherwise                               : delete c
also delete every copy with fireStep < senderStepNow(p) - 64

24 moves and 7 explosion steps match the shooter's own shot (lifetime 0x18; explosion state 0xFFF8 counted up to 0 and drawn while negative, src/shots.c). A copy already drawn past its hit point jumps back to the explosion when the exploded record arrives late. Copies never hit anything.

HIT (0x10), 20 bytes

OffsetTypeFieldMeaning
0u8type0x10
1u8flagsbit 0 powered (costs 2 shields instead of 1)
2u16shotIdthe shot that hit
4u32eventshooter's event number
8u32victimPeervictim's peer id
12u16victimLifevictim's life id in the STATE the shooter drew
14u8victimSlotfor logs and checks
15u8reserved0
16u32stepshooter's step of the hit

The shooter adds 50 points at once, as the original does, and sends HIT to the victim only; the others see only the shot explode (through its record), as in the original.

Exact rules: applying HIT (victim, in the step's hit phase)
  1. The sender must be an accepted slot holder (the roster names it, with its gen, as a player; or the live-link rule of "Holding a slot" applies). HITs and SATs from anyone else (a spectator, a page that lost its slot) are ignored and logged. The killer, if the hit kills, is the slot the sender holds in my accepted state.
  2. victimPeer ≠ my peer id, or victimLife ≠ my current life: ignore. (A hit on my previous life, or on the previous holder of my slot, never touches me.)
  3. I am not in flight (name screen, away) or my shields are 0: ignore (chapter 20, D3). The original applied hits on the name screen too (name_entry calls net_sync_frame, src/namentry.c).
  4. Excess delay over 1 s: ignore. Excess delay = my step time at arrival − (o_p + step ÷ r_p), i.e. how much later than the shooter's fastest messages this one came. A constant delay, however large, is part of o_p and does not count, so a player with a slow connection is still hit; only a hit held up by a stall (a broken path, a congested queue) is dropped.
  5. Otherwise apply it exactly as the original applies a hit word (chapter 8, "Exact rules: applying hit reports"): −1 shield (−2 if powered), flash, cloak lost with "Cloak Destroyed!", at 0 shields status killed, killer = the shooter's slot, death countdown 64.

SAT (0x20), 20 bytes

OffsetTypeFieldMeaning
0u8type0x20
1u8action1 collected, 2 shot
2u16satIdthe satellite, as in the owner's STATE
4u32eventsender's event number
8u32ownerPeerowner's peer id
12u32stepsender's step
16u16shotIdfor action 2, else 0xFFFF
18u16reserved0

Who decides a satellite pick-up

In an owner-confirmed design the collector asks the owner and gets the bonus only if the owner answers "yours". In a collector-decides design the collector takes the bonus at once and tells the owner, who removes the satellite; ids make sure each satellite is taken at most once per collector and that a late message cannot remove a newer satellite. This protocol uses collector-decides with ids:

Exact rules: satellites

Owner:

  1. Spawn as the original: every 128th step of the flight loop (also while dead), only if it has no satellite (an exploding one counts as having one): satId := satId + 1, kind and position as chapter 5.
  2. Queued SATs are applied at the start of the satellite part of my step, before my own touch test, as the original handles the event word at the start of satellite_update (src/satellite.c). So when a remote collect is queued and I touch my own satellite in the same step, the remote collect wins. SAT for me with satId = my satId and my kind > 0: action 1 → kind 0; action 2 → kind −1 (exploding; kind 0 once its age passes 64, as the original). Any other SAT (old id, already gone, already exploding) is ignored. So the first SAT for a satellite wins.
  3. Collecting or shooting my own satellite is local and immediate, as in the original.
  4. Leaving flight (name screen, away): my satellite becomes kind 0 at once. (The original keeps sending it from the name screen without handling events, and removes it only when the next life starts, satellites_clear in src/main.c; meanwhile others can collect it every frame, chapter 8.)

Everyone else, for each owner's copy (owner, satId, kind, position from its latest STATE):

  1. A set taken of (owner, satId). A copy in the set is not drawn as a satellite, cannot be touched and cannot be shot. An entry is removed when the owner's STATE shows a different satId, or the owner is gone.
  2. My shots are tested against copies with kind > 0, not taken, after the tests against ships (src/shots.c order), in owner slot order, also when the same shot hit a ship in that step (the original does not stop between the two loops). Each copy a shot overlaps in that step: SAT action 2 for it, add it to taken, draw its explosion locally; the shot explodes; no points. (The original tests every copy too, but has one event word, so only the last is reported.)
  3. Touch (the original's test: close enough to collide and not within 8 steps after a bump), in flight, not spectating, copy kind > 0 and not taken: apply the pick-up of that kind at once (chapter 5, multiplayer values), send SAT action 1, add to taken. So exactly once per (owner, satId).
  4. A copy whose owner has status 2 is ignored (its owner has removed it anyway).

The original (Authentic): no ids; the event names only the owner's slot; the collector's copy stays until the owner's next packet, so the bonus is applied on 1–2 frames, and on every frame while the owner is on the name screen; two collectors both get it; a late or stale event removes whatever satellite the owner has now (chapter 8, "Satellites between players").

PING (0x81) and PONG (0x82), 20 bytes each

OffsetTypeFieldMeaning
0u8type0x81 or 0x82
1u8flagsbit 0 away
2u16reserved0
4u32noncechosen by the PING sender, echoed in PONG
8f64timePING: sender's performance.now() in ms; PONG: copied
16u32stepthe sender's current step

Every page sends PING to each link every 500 ms from setInterval and answers each PING with a PONG directly in the channel's onmessage handler. Round-trip time: now − time when the PONG arrives; smoothed rtt := 0.875·rtt + 0.125·sample.

Receiving

Exact rules: intake, duplicates, order

Showing other peers

The original drew another ship exactly where its last packet put it. Over the internet messages arrive unevenly and the other page's clock runs at a slightly different rate, so each page maps every sender's steps onto its own clock and draws other ships a little in the past.

Exact rules: the step mapping and interpolation
  1. For each STATE accepted from p, record (s = its step, m = my step time at arrival).
  2. Rate r_p (sender steps per my step): 1 at first; once 5 s of samples exist, the slope of a straight line fitted to the (m, s) pairs of the last 10 s, clamped to 0.5..1.05. This follows a slow device (running at 90 % say) and clock drift (10–100 parts per million) without a sawtooth.
  3. Offset o_p = the smallest (m − s ÷ r_p) over the last 2 s: the fastest delivery, so jitter does not move it. Without samples in the last 2 s (the sender is away or silent), keep the last o_p and r_p. Before the first STATE from p: r_p = 1 and o_p = (my step time at HELLO) − HELLO's step, and the HIT excess-delay check is skipped (the hit is applied). Lateness of a message = (m − s ÷ r_p) − o_p.
  4. Delay D = 3 steps + the 90th percentile of the lateness over the last 2 s, at most 10 steps.
  5. The sender step to draw: t_p = r_p × (myStepTime − o_p − D).
  6. Position: linear between the two stored states around t_p (in floating point, world units = value ÷ 65,536). Axes: blend a and b linearly, then a := a ÷ |a|; b := b − (a·b)·a, b := b ÷ |b|; c is computed from a and b the way the original does it (vec3_cross(a, b, c), chapter 3). If t_p is beyond the newest state, extrapolate with its velocity for at most 4 steps, then hold.
  7. If a sender's step jumps by more than 35 against senderStepNow, drop its samples and start the fit again.
  8. Hit tests and collisions use the ship as drawn at t_p, taken at my integer step time (chapter 13: "the shooter decides" means "what the shooter saw").

Worked example. A STATE with step 8,000 from Bob arrives at my step time 9,253.2; over the last 2 s the fastest one gave o = 1,252.9 (r = 1). Lateness of this one: 9,253.2 − 8,000 − 1,252.9 = 0.3 steps. The 90th percentile of the lateness is 1.5, so D = 4.5. At my step time 9,260.0 I draw Bob at t = 9,260.0 − 1,252.9 − 4.5 = 8,002.6: 60 % of the way from his state 8,002 to 8,003. His shot fired in step 8,002 has made m = 8,002.6 − 8,002 + 1 = 1.6 moves.

Liveness

Exact rules: is a link live?

Away: a hidden tab

Spectators and late joiners

One step, exactly

every step period (from the accumulator; at most 5 per animation frame):
    step := step + 1

    1. intake: everything received since the last step, in arrival order
       roster from the service           -> apply if v > applied version
       HELLO, BYE, NAME                   -> applied in the message handler already
       HIT, SAT                           -> de-duplicated in the handler, waiting in the queue
       STATE                              -> accept or drop (above), into the history

    2. simulate my world in the original frame order (chapters 2 and 14), with other ships as
       drawn at their t_p:
       my ship; my shots (hits on ships -> HIT, +50; hits on satellite copies -> SAT);
       other ships (collisions decided locally); shot copies;
       satellites: first the queued SATs for my satellite, in arrival order; then spawn
       (every 128th step) and touches (-> pick-up + SAT)
       every HIT and SAT is sent on ev when created, to its one receiver

    3. hit phase: queued HITs for me, in arrival order

    4. liveness of every link

    5. for each live link to a player, and to a spectator when step is even:
           if st.bufferedAmount > 1,024 or the link is congested: skip it this step
           else build and send STATE (the state after this step, with the shot records due)

    6. draw (independently of the steps, interpolated)

Difference from the original's order: the original sends at the start of a frame the state of the end of the previous frame. Sending after the step is the same state one step earlier. Satellite events and hits are applied where the original applies them: satellite events at the start of satellite_update, hits in net_sync_frame after drawing.

Congestion

Bandwidth

Overhead per data channel message: IPv4 20 + UDP 8 + DTLS record 13 + AES-GCM nonce and tag 24 + SCTP common header 12 + SCTP data chunk 16 = 93 bytes (113 over IPv6). SCTP acknowledges every second packet with a SACK, also on the unreliable channel; a SACK packet is about 93 bytes too.

CaseSTATE payloadOn the wirePer link at 70/s
not firing (typical)111 B204 B114 kbit/s
holding fire (one shot every 3rd step), missing111 + 44 × 1.33 = 170 B263 B147 kbit/s
worst case: 8 records in every message463 B556 B311 kbit/s

Versions and settings

Authentic rooms

An Authentic room must reproduce the original's network behaviour, bugs included (chapter 20). It uses the same service, connections, HELLO, NAME, BYE and PING, with periodNs 14,268,123 (the VGA refresh of the 640 × 350 mode: 25.175 MHz ÷ (800 × 449) = 70.086 per second, chapter 20's 70.09), and replaces STATE, HIT and SAT by one message on st:

OffsetTypeFieldMeaning
0u8type0x84 STATE_A
1u8slot0..3
2u16genslot generation
4u32stepsender's step
8u8 × 130packetbytes 30..159 of the original packet (chapter 8: name, orientation, position, velocity, event record, score, satellite, 8 shot flags)
  1. Step order as the original (chapter 17): re-arm the receive buffers, send STATE_A with the state of the end of the previous step (only if st.bufferedAmount is 0, like "previous send finished"), simulate and draw, then wait.
  2. Players send STATE_A to spectators too, in every step (the original's spectators heard every broadcast).
  3. The page keeps one 130-byte buffer per peer. The first STATE_A from that peer arriving after the re-arm is copied in; later ones in the same step are dropped. Only live peers are re-armed each step; an inactive peer's buffer stays armed across steps and takes the first STATE_A that arrives whenever it comes, which makes that peer live again (net_post_peer_listens, net_sync_frame). One deviation: a STATE_A whose step is not greater than the last one latched is dropped too, because the unordered channel reorders far more often than the original's LAN did, and the original would latch the old packet.
  4. Waiting: a browser cannot busy-wait. The step's end is deferred: the page keeps checking (on each message and each animation frame) and finishes the step when every live peer's buffer has been filled this step, or when the original's limit has passed: the 5th tick of the 18.2-per-second timer after the step began, 219.7–274.6 ms depending on where in a tick it began (chapter 20). The next step starts no earlier than one period after this one began.
  5. Liveness is the original's counter (4, −1 per step without a message, 0 = not waited for); the event words in the buffers are applied every step, as the original does, repeats and all.
  6. Speed: each step needs the other peers' messages, so the step rate is about 1 ÷ max(14.27 ms, one-way delay to the slowest peer). At 40 ms one way that is 25 steps per second, 36 % of the original speed, and every lost message stalls everyone for up to 275 ms. Authentic rooms are for a LAN or players in the same city.
  7. Known difference: slots come from the service, so "two players in one slot" (chapter 20, D7) cannot happen.

Timers and limits at a glance

WhatValue
step period14,285,714 ns (70/s) or 54,925,401 ns; Authentic 14,268,123 ns
steps per animation frame, at most5
STATE to players / spectatorsafter every step / every 2nd step
shot record repeatsnext 4 STATEs sent per link after firing, next 4 after exploding
PING interval; PONG needed within500 ms; 3 s
link not live after1,000 ms without a message (10,000 ms when away)
HIT excess delay, at most1 s
pending STATE with an unknown gen1 s
enter flight after claiming, at the latest5 s
claim or spectate without an answer10 s, then treated as denied
partial mesh: revoke after; re-claim refused for20 s down while both present; 60 s
ICE: "disconnected" before restart; polite fallback; restarts2 s; 5 s; 3 within 30 s
meshing again: first wait, doubling up to2 s, 60 s
negotiation timeout; queued signals kept10 s; 30 s
page ping to the service; service declares a page dead after10 s; 25 s
reservation after a dead WebSocket60 s
service recovery window after an empty restart45 s
service reconnect back-off1, 2, 4, 8, 15, 15 … s, each ±20 % random
frozen page: rejoin if more than5 s passed
st buffered limit; ev congested / clear / give up1,024 B; 65,536 B / 16,384 B / 5 s
interpolation delay D3 steps + jitter, at most 10 steps
TURN credential lifetime (recommended)12 hours

A whole session, in one picture

Alice (inviter) service Bob (newcomer) join(room R, session, proto 1.0, settings) welcome(peer 7, roster v0, ice) claim(slot 0) claimed(0, gen 1); roster v1 flies alone, STATE to nobody join(room R from the link) welcome(peer 12, members [7], roster v1) claim(slot 1) claimed(1, gen 1) roster v2 (both) signal(to 7, offer) signal(from 12, offer) signal(to 12, answer) signal(from 7, answer) ICE candidates both ways through the service; STUN, TURN if needed data channels ev + st open (direct) HELLO (version, period, slot, life, …) links [12] links [7] STATE every step, both ways (st, unreliable) Bob's shot hits Alice: +50 HIT(event 1, victim 7, life 1, shot 4) on ev applied once: shields −1, flash BYE(reason 0) release; WebSocket closed member left 7; roster v3 (slot 0 free) Alice's ship gone; Bob plays on
Black: through the service (JSON over WebSocket). Blue: directly between the browsers (dashed: unreliable state). Red: a reliable event. Alice invited Bob and then left; nothing depended on her.
For a rebuild