Skip to content

3D engine that AI agents drive

Add peer-to-peer authority and a WebRTC browser sample to netcode (#778)

Nguyen Xuan Ane6b84bfd3e49
diff --git a/changes/778.md b/changes/778.md
new file mode 100644
index 00000000..b0699d44
--- /dev/null
+++ b/changes/778.md
@@ -0,0 +1 @@
+- The netcode addon gains peer-to-peer authority (`authority: 'peer'`: every peer owns its entities, an owner term with a lower-peer-id tie break settles conflicts, `claimEntity` takes one over), and the browser sample runs over a WebRTC data channel (`?transport=webrtc`), checked in two headless Chrome pages with measured lag (#778)
diff --git a/changes/778.size.md b/changes/778.size.md
new file mode 100644
index 00000000..598c327c
--- /dev/null
+++ b/changes/778.size.md
@@ -0,0 +1 @@
+- entry:netcode: 1108 bytes gzip for peer-to-peer authority (owner terms with a deterministic tie break, claims, per-peer message ordering, interpolation of remote-owned entities), the last authority choice named in #778; the addon loads only when imported
diff --git a/docs/netcode.md b/docs/netcode.md
index 0cebcd20..92fd62e7 100644
--- a/docs/netcode.md
+++ b/docs/netcode.md
@@ -25,12 +25,27 @@ createRuntime(renderer, { fixedRate: 50, systems: [client] }).start();
## Authority
-`authority: 'server'` is a dedicated authority with no player. `authority: 'host'` is a player who also runs the world: give it `readInput` and an entity it owns (`owner` is its own transport id) and it plays with no prediction. `'peer'` (peer to peer) is reserved and throws until it exists.
+`authority: 'server'` is a dedicated authority with no player. `authority: 'host'` is a player who also runs the world: give it `readInput` and an entity it owns (`owner` is its own transport id) and it plays with no prediction. `'peer'` has no single authority: see Peer to peer below.
The authority methods are `addEntity(id, { owner, tag, state })`, `removeEntity(id)` and `setEntityState(id, partialState)`. `owner` is the transport peer id whose input drives the entity (one entity per peer). An entity without an owner is driven by game code: a physics prop, a door, a score. Write its state with `setEntityState` each step. Parts left out keep their value.
An entity state is `{ position: [x, y, z], rotation: [x, y, z, w], velocity: [x, y, z], variables: { name: number } }`. Parts you leave out start at zero, identity rotation and no variables.
+## Peer to peer
+
+`authority: 'peer'` (leave `role` out) has no server and no host. Every peer owns the entities it adds, runs them itself with no prediction or reconciliation, and sends their full state to every peer in the transport every `snapshotEveryTicks` steps. The other peers draw those entities `interpolationDelaySeconds` in the past, as a client does. Give a peer `localEntityId` and `readInput` to drive its own player with `simulate`; write any other entity it owns with `setEntityState`.
+
+```js
+const peer = createNetcode({ authority: 'peer', transport, localEntityId: 'alice', readInput });
+peer.addEntity('alice', { tag: 'player' }); // owned by this peer, its transport id
+peer.getEntityState('bob'); // arrives from bob once he is connected
+peer.claimEntity('ball'); // take over an entity another peer owns
+```
+
+An entity has one owner and a term that starts at 0. When two peers claim the same entity, the higher term wins, and on equal terms the lower peer id, so every peer settles on the same owner whatever the arrival order. `claimEntity(id)` raises the term by one and starts from the state this peer sees, so a later claim beats the earlier owner. A peer that loses stops sending the entity, and `setEntityState` on an entity you do not own throws and names its owner (`getEntityOwner(id)`). An entity whose owner leaves the transport's `peers()` is dropped; `stats.ownershipChanges` counts owner changes. Each peer numbers its messages and tags them with a run id, so a late or reordered message is dropped as stale and a restart on the same id is followed.
+
+Peers trust each other: nothing stops a peer from writing a state the game rules forbid, so use a server or host authority where cheating matters. There is no join handshake, since each message carries full state. Every peer must be on the transport's `peers()` list, a full mesh, so give each pair its own channel. Use the same `fixedRate` on every peer.
+
## Simulation and input
Client and authority run the same pure function `simulate(state, input, stepSeconds) -> state` for each input, so the client can predict. The default is `createPlanarMovement({ speed: 5 })`: input `{ moveX, moveZ }` from -1 to 1 sets a flat velocity. Pass your own `simulate` for jumping, collisions or anything else, and keep it deterministic. An input is an object of at most 16 numbers and booleans.
@@ -66,7 +81,7 @@ A transport is a plain object `{ id, peers(), send(peerId, message), receive(cal
| Option | Default | Meaning |
| --- | --- | --- |
| `role` | `'client'` | `'authority'` or `'client'` |
-| `authority` | `'server'` | `'server'` or `'host'` |
+| `authority` | `'server'` | `'server'`, `'host'` or `'peer'` |
| `transport` | required | The transport above |
| `serverId` | required for a client | Peer id of the authority |
| `localEntityId` | none | The entity a client predicts |
@@ -78,16 +93,16 @@ A transport is a plain object `{ id, peers(), send(peerId, message), receive(cal
`NETCODE_LIMITS` holds the hard bounds: 256 entities, 32 peers, 16 variables per entity, names up to 64 characters, 8 inputs per message, 64 queued inputs per peer, 64 snapshots of history. Network input is untrusted: a bad message is counted in `stats.rejectedMessages` and ignored, never thrown. Option and call errors say what to pass.
-`stats` reports `snapshotsSent`, `fullSnapshotsSent`, `bytesSent`, `inputsProcessed`, `snapshotsReceived`, `staleSnapshots`, `missingBaseSnapshots`, `authorityRestarts`, `reconciliations`, `lastCorrection`, `maximumCorrection` and `rejectedMessages`.
+`stats` reports `snapshotsSent`, `fullSnapshotsSent`, `bytesSent`, `inputsProcessed`, `snapshotsReceived`, `staleSnapshots`, `missingBaseSnapshots`, `authorityRestarts`, `reconciliations`, `lastCorrection`, `maximumCorrection`, `rejectedMessages` and `ownershipChanges`.
## Sample game and relay
-`scripts/netcode-sample.html` is a two-player sample: one page is the host (`?role=host`, plays `alice`, owns the truth) and the other is a client (`?role=client`, plays `bob` with prediction and reconciliation). Move with the arrow keys or WASD. `?transport=broadcast` (default) uses two tabs of one browser; `?transport=websocket` uses the relay on the machine that serves the page: the socket goes to the page's own host, `ws` or `wss` to match the page, and `?relayPort=` (default 8787) picks the port. To play across a LAN, run the relay with `--host 0.0.0.0` on the machine that serves the sample and open the page from the other machine by that machine's address. `?delay=50` adds that many milliseconds to everything a page sends. The sample sends a snapshot every tick and draws remote players 40 ms behind (`?snap=` and `?interp=` change them), which shows a move on the other page about 95 ms after the key with 50 ms of injected latency each way. Serve the repository root (for example with `npx vite`) and open both URLs.
+`scripts/netcode-sample.html` is a two-player sample: one page is the host (`?role=host`, plays `alice`, owns the truth) and the other is a client (`?role=client`, plays `bob` with prediction and reconciliation). Move with the arrow keys or WASD. `?transport=broadcast` (default) uses two tabs of one browser; `?transport=webrtc` connects the two pages with a WebRTC data channel, trading the offer and answer over a BroadcastChannel, so the two pages must be tabs of one browser (a real game sends those two messages through its own signalling service); `?transport=websocket` uses the relay on the machine that serves the page: the socket goes to the page's own host, `ws` or `wss` to match the page, and `?relayPort=` (default 8787) picks the port. To play across a LAN, run the relay with `--host 0.0.0.0` on the machine that serves the sample and open the page from the other machine by that machine's address. `?delay=50` adds that many milliseconds to everything a page sends. The sample sends a snapshot every tick and draws remote players 40 ms behind (`?snap=` and `?interp=` change them), which shows a move on the other page about 95 ms after the key with 50 ms of injected latency each way. Serve the repository root (for example with `npx vite`) and open both URLs.
`node scripts/netcode-relay.mjs --port 8787 [--host 0.0.0.0] [--latency 50]` is a reference relay of about 80 lines. Players connect to `/?id=<name>`; it forwards `{ to, data }` as `{ from, data }`, announces `{ from, left: true }`, refuses a repeated name and keeps no game state, so it runs on any free Node host. It needs the `ws` package, a dev dependency of this repository only; the library itself gains no dependency.
-`tests/netcode-two-browsers.test.js` opens the host and client in two headless Chrome pages over each transport with 50 ms injected per direction. It asserts that both pages end within 0.05 units of each other and that a move shows on the other page in under 450 ms. Measured on a loaded machine: a host move shows on the client after about 200 to 230 ms and a client move shows on the host after about 130 to 150 ms, the same over both transports. The client's own player never waits, since it is predicted, and the largest correction was 0. The host-to-client figure holds the 50 ms line, up to one snapshot interval (40 ms) and the 100 ms interpolation delay.
+`tests/netcode-two-browsers.test.js` opens the host and client in two headless Chrome pages over each of the three transports with 50 ms injected per direction. It asserts that both pages end within 0.05 units of each other and that a move shows on the other page in under 450 ms. Measured on a loaded machine: a host move shows on the client after about 200 to 230 ms and a client move shows on the host after about 130 to 150 ms, the same over every transport. The 2026-11-18 run of this test, with the sample's 20 ms snapshots and 40 ms interpolation delay, measured a host move showing on the client after 80 to 88 ms and a client move showing on the host after 127 to 134 ms from the key press, over BroadcastChannel, WebSocket and WebRTC alike. The client's own player never waits, since it is predicted, and the largest correction was 0. The host-to-client figure holds the 50 ms line, up to one snapshot interval (40 ms) and the 100 ms interpolation delay.
## Not yet
-A WebTransport transport, peer-to-peer authority, a browser sample over WebRTC and a relay on a real free host come in later work on #778. The data channel test covers a host with two clients and an ownerless prop driven by game code. Use the same `fixedRate` on the authority and every client.
+A WebTransport transport and a relay on a real free host come in later work on #778. The data channel test covers a host with two clients and an ownerless prop driven by game code. Use the same `fixedRate` on the authority and every client.
diff --git a/scripts/netcode-sample.js b/scripts/netcode-sample.js
index 7dc3287e..f36aa93e 100644
--- a/scripts/netcode-sample.js
+++ b/scripts/netcode-sample.js
@@ -4,6 +4,7 @@
import { createRuntime } from '../src/runtime.js';
import {
createBroadcastChannelTransport,
+ createDataChannelTransport,
createNetcode,
createWebSocketTransport,
} from '../src/netcode.js';
@@ -64,6 +65,80 @@ export function withInjectedLatency(transport, delayMilliseconds) {
return delayed;
}
+// WebRTC in one browser needs no server: the two pages trade the offer and the answer over a BroadcastChannel. A real game
+// sends the same two messages through its own signalling service. Candidates are gathered before the description is sent, so
+// there is no trickle. The client says hello until the host answers, so either page may load first.
+const SIGNALLING_CHANNEL_NAME = 'crucible-netcode-signalling';
+const SIGNALLING_RETRY_MILLISECONDS = 250;
+const ICE_GATHERING_TIMEOUT_MILLISECONDS = 2000;
+
+function describeWhenGathered(connection) {
+ return new Promise(resolve => {
+ const finish = () => resolve(connection.localDescription.toJSON());
+ if (connection.iceGatheringState === 'complete') {
+ finish();
+ return;
+ }
+ connection.addEventListener('icegatheringstatechange', () => { if (connection.iceGatheringState === 'complete') finish(); });
+ setTimeout(finish, ICE_GATHERING_TIMEOUT_MILLISECONDS);
+ });
+}
+
+function waitForOpen(channel) {
+ return new Promise((resolve, reject) => {
+ if (channel.readyState === 'open') {
+ resolve();
+ return;
+ }
+ channel.addEventListener('open', () => resolve(), { once: true });
+ channel.addEventListener('error', () => reject(new Error('The WebRTC data channel failed to open.')), { once: true });
+ });
+}
+
+async function createWebRtcTransport(playerId, remoteId, isHost) {
+ const transport = createDataChannelTransport({ id: playerId });
+ const signalling = new BroadcastChannel(SIGNALLING_CHANNEL_NAME);
+ const connection = new RTCPeerConnection({ iceServers: [] });
+ const channelOpen = new Promise(resolve => {
+ if (isHost) {
+ const channel = connection.createDataChannel('netcode', { ordered: false, maxRetransmits: 0 });
+ transport.addChannel(remoteId, channel);
+ resolve(waitForOpen(channel));
+ } else {
+ connection.addEventListener('datachannel', event => {
+ transport.addChannel(remoteId, event.channel);
+ resolve(waitForOpen(event.channel));
+ });
+ }
+ });
+ let offerSent = false;
+ signalling.onmessage = async event => {
+ const message = event.data;
+ if (message.to !== playerId) return;
+ if (isHost && message.type === 'hello' && !offerSent) {
+ offerSent = true;
+ await connection.setLocalDescription(await connection.createOffer());
+ signalling.postMessage({ to: remoteId, type: 'offer', description: await describeWhenGathered(connection) });
+ } else if (isHost && message.type === 'answer' && connection.signalingState === 'have-local-offer') {
+ await connection.setRemoteDescription(message.description);
+ } else if (!isHost && message.type === 'offer' && connection.signalingState === 'stable') {
+ await connection.setRemoteDescription(message.description);
+ await connection.setLocalDescription(await connection.createAnswer());
+ signalling.postMessage({ to: remoteId, type: 'answer', description: await describeWhenGathered(connection) });
+ }
+ };
+ const helloTimer = isHost ? null : setInterval(() => signalling.postMessage({ to: remoteId, type: 'hello' }), SIGNALLING_RETRY_MILLISECONDS);
+ await channelOpen;
+ clearInterval(helloTimer);
+ const closeChannels = transport.close;
+ transport.close = () => {
+ closeChannels();
+ connection.close();
+ signalling.close();
+ };
+ return transport;
+}
+
async function createSampleTransport(options, playerId, remoteId) {
if (options.transport === 'broadcast') {
return createBroadcastChannelTransport(new BroadcastChannel('crucible-netcode-sample'), { id: playerId });
@@ -72,7 +147,8 @@ async function createSampleTransport(options, playerId, remoteId) {
const socket = await openWebSocket(options.relayPort ?? DEFAULT_RELAY_PORT, playerId);
return createWebSocketTransport(socket, { id: playerId, remoteId, multiplexed: true });
}
- throw new RangeError(`Sample transport must be "broadcast" or "websocket", got ${JSON.stringify(options.transport)}.`);
+ if (options.transport === 'webrtc') return createWebRtcTransport(playerId, remoteId, options.role === 'host');
+ throw new RangeError(`Sample transport must be "broadcast", "websocket" or "webrtc", got ${JSON.stringify(options.transport)}.`);
}
function readKeyboard(pressedKeys) {
@@ -104,7 +180,7 @@ function drawPlayers(canvas, netcode, localId) {
}
}
-// options: { role: 'host' | 'client', transport: 'broadcast' | 'websocket', relayPort, delayMilliseconds, canvas,
+// options: { role: 'host' | 'client', transport: 'broadcast' | 'websocket' | 'webrtc', relayPort, delayMilliseconds, canvas,
// snapshotEveryTicks, interpolationDelaySeconds }
export async function startSample(options) {
const isHost = options.role === 'host';
diff --git a/src/netcode.js b/src/netcode.js
index 8f62489a..e107dbb1 100644
--- a/src/netcode.js
+++ b/src/netcode.js
@@ -5,7 +5,7 @@
// { id, peers(), send(peerId, message), receive(callback) }. This file ships an in-memory loopback for tests and a wrapper
// for a socket-like object. Nothing here opens a connection or a timer. See docs/netcode.md.
-export const NETCODE_AUTHORITIES = Object.freeze(['server', 'host']);
+export const NETCODE_AUTHORITIES = Object.freeze(['server', 'host', 'peer']);
export const NETCODE_ROLES = Object.freeze(['authority', 'client']);
export const NETCODE_LIMITS = Object.freeze({
@@ -331,24 +331,24 @@ function sampleAt(samples, time, maximumExtrapolationSeconds) {
function validateNetcodeOptions(options) {
if (!isPlainObject(options)) throw new TypeError('createNetcode needs an options object like { role: "client", transport, serverId: "server" }.');
validateTransport(options.transport, 'createNetcode');
- const role = options.role ?? 'client';
- if (!NETCODE_ROLES.includes(role)) {
- throw new RangeError(`createNetcode role must be one of ${NETCODE_ROLES.join(', ')}, got ${String(role)}.`);
- }
const authority = options.authority ?? 'server';
- if (authority === 'peer') {
- throw new RangeError(`createNetcode authority "peer" (peer to peer) is not supported yet. Use one of ${NETCODE_AUTHORITIES.join(', ')}.`);
- }
if (!NETCODE_AUTHORITIES.includes(authority)) {
throw new RangeError(`createNetcode authority must be one of ${NETCODE_AUTHORITIES.join(', ')}, got ${String(authority)}.`);
}
+ if (authority === 'peer' && options.role !== undefined && options.role !== 'peer') {
+ throw new RangeError(`createNetcode authority "peer" has no authority or client role: every peer owns its own entities. Leave role out, got ${String(options.role)}.`);
+ }
+ const role = authority === 'peer' ? 'peer' : (options.role ?? 'client');
+ if (role !== 'peer' && !NETCODE_ROLES.includes(role)) {
+ throw new RangeError(`createNetcode role must be one of ${NETCODE_ROLES.join(', ')}, got ${String(role)}.`);
+ }
if (role === 'client') requireName(options.serverId, 'createNetcode serverId');
for (const name of ['simulate', 'readInput']) {
if (options[name] !== undefined && typeof options[name] !== 'function') {
throw new TypeError(`createNetcode ${name} must be a function or left out, got ${describe(options[name])}.`);
}
}
- if (role === 'client' && options.localEntityId !== undefined) requireName(options.localEntityId, 'createNetcode localEntityId');
+ if (role !== 'authority' && options.localEntityId !== undefined) requireName(options.localEntityId, 'createNetcode localEntityId');
return {
role,
authority,
@@ -777,8 +777,201 @@ function createClient(settings, stats) {
};
}
+// ----- The peer to peer side -----
+
+// Every peer owns the entities it adds and sends their full state to all peers. When two peers claim one entity, the
+// higher term wins, and on equal terms the lower peer id, so every peer settles on the same owner whatever the arrival order.
+function claimBeats(candidateTerm, candidateOwner, currentTerm, currentOwner) {
+ if (candidateTerm !== currentTerm) return candidateTerm > currentTerm;
+ return candidateOwner < currentOwner;
+}
+
+function createPeerSide(settings, stats) {
+ const { transport, steps } = settings;
+ const selfId = transport.id;
+ const entities = new Map(); // id -> { owner, term, tag, state, samples }
+ const senders = new Map(); // peer id -> { session, lastTick }
+ const sessionId = createSessionId();
+ let tick = 0;
+ let clock = 0;
+
+ function isLocal(entity) {
+ return entity.owner === selfId;
+ }
+
+ function listPresent() {
+ return [...entities.keys()].join(', ') || 'none';
+ }
+
+ function requireLocalEntity(id, action) {
+ const entity = entities.get(id);
+ if (!entity) throw new RangeError(`${action}: no entity named "${String(id)}". Present: ${listPresent()}. Use addEntity first.`);
+ if (!isLocal(entity)) throw new RangeError(`${action}: "${id}" is owned by peer "${entity.owner}". Call claimEntity("${id}") to take it over first.`);
+ return entity;
+ }
+
+ // The record of a sender, null when there is no room for another, undefined when the message is of an older run.
+ function senderRecord(peerId, session) {
+ let record = senders.get(peerId);
+ if (!record) {
+ if (senders.size >= NETCODE_LIMITS.maximumPeers) return null;
+ record = { session, lastTick: -1 };
+ senders.set(peerId, record);
+ }
+ if (record.session !== session) {
+ if (session < record.session) return undefined;
+ record.session = session;
+ record.lastTick = -1;
+ }
+ return record;
+ }
+
+ function acceptRemoteEntity(peerId, id, raw) {
+ const delta = isPlainObject(raw) ? readWireEntityDelta(raw, true) : null;
+ if (!delta || !Number.isSafeInteger(raw.m) || raw.m < 0) {
+ stats.rejectedMessages += 1;
+ return;
+ }
+ const known = entities.get(id);
+ if (known && known.owner !== peerId) {
+ if (!claimBeats(raw.m, peerId, known.term, known.owner)) return;
+ stats.ownershipChanges += 1;
+ known.samples = [];
+ } else if (!known) {
+ if (entities.size >= NETCODE_LIMITS.maximumEntities) return;
+ stats.ownershipChanges += 1;
+ } else if (raw.m < known.term) {
+ return;
+ }
+ const entity = known ?? { samples: [] };
+ entity.owner = peerId;
+ entity.term = raw.m;
+ entity.tag = delta.t ?? null;
+ entity.state = dequantizeEntity(delta, steps);
+ entity.samples.push({ time: clock, state: cloneState(entity.state) });
+ if (entity.samples.length > NETCODE_LIMITS.maximumSamplesPerEntity) entity.samples.shift();
+ entities.set(id, entity);
+ }
+
+ function receiveMessage(peerId, message) {
+ const valid = isPlainObject(message) && message.type === 'peer-state' && isValidSession(message.session)
+ && Number.isSafeInteger(message.tick) && message.tick >= 0 && isPlainObject(message.entities)
+ && Object.keys(message.entities).length <= NETCODE_LIMITS.maximumEntities;
+ const record = valid ? senderRecord(peerId, message.session) : null;
+ if (!valid || record === null) {
+ stats.rejectedMessages += 1;
+ return;
+ }
+ if (record === undefined || message.tick <= record.lastTick) {
+ stats.staleSnapshots += 1;
+ return;
+ }
+ record.lastTick = message.tick;
+ stats.snapshotsReceived += 1;
+ for (const [id, raw] of Object.entries(message.entities)) {
+ if (id.length > NETCODE_LIMITS.maximumNameLength) {
+ stats.rejectedMessages += 1;
+ continue;
+ }
+ acceptRemoteEntity(peerId, id, raw);
+ }
+ }
+
+ function dropEntitiesOfGonePeers() {
+ const present = new Set(transport.peers());
+ for (const [id, entity] of entities) {
+ if (!isLocal(entity) && !present.has(entity.owner)) entities.delete(id);
+ }
+ }
+
+ function sendOwnedEntities() {
+ const owned = {};
+ for (const [id, entity] of entities) {
+ if (isLocal(entity)) owned[id] = { ...quantizeEntity(entity.state, entity.tag, steps), m: entity.term };
+ }
+ const message = { type: 'peer-state', session: sessionId, tick, entities: owned };
+ const bytes = JSON.stringify(message).length;
+ if (bytes > settings.maximumMessageBytes) {
+ throw new RangeError(`A netcode peer message is ${bytes} bytes, over maximumMessageBytes ${settings.maximumMessageBytes}. Own fewer entities or variables, or raise maximumMessageBytes (up to ${NETCODE_LIMITS.maximumMessageBytes}).`);
+ }
+ for (const peerId of transport.peers()) {
+ if (peerId === selfId) continue;
+ transport.send(peerId, message);
+ stats.snapshotsSent += 1;
+ stats.bytesSent += bytes;
+ }
+ }
+
+ function drawnState(entity) {
+ if (isLocal(entity) || entity.samples.length === 0) return cloneState(entity.state);
+ return sampleAt(entity.samples, clock - settings.interpolationDelaySeconds, settings.maximumExtrapolationSeconds);
+ }
+
+ function moveLocalPlayer(step) {
+ const player = settings.localEntityId ? entities.get(settings.localEntityId) : null;
+ if (!settings.readInput || !player || !isLocal(player)) return;
+ const input = readInput(settings.readInput(), 'readInput result');
+ player.state = readState(settings.simulate(player.state, input, step), 'simulate result');
+ stats.inputsProcessed += 1;
+ }
+
+ return {
+ receiveMessage,
+ fixedUpdate(step) {
+ clock += step;
+ dropEntitiesOfGonePeers();
+ moveLocalPlayer(step);
+ tick += 1;
+ if (tick % settings.snapshotEveryTicks === 0) sendOwnedEntities();
+ },
+ addEntity(id, definition = {}) {
+ requireName(id, 'addEntity id');
+ if (entities.has(id)) throw new RangeError(`addEntity: an entity named "${id}" already exists. Use setEntityState to change it, or claimEntity to take over a remote one.`);
+ if (entities.size >= NETCODE_LIMITS.maximumEntities) {
+ throw new RangeError(`A netcode world syncs at most ${NETCODE_LIMITS.maximumEntities} entities. Remove some, or sync only what players see.`);
+ }
+ if (definition.owner !== undefined && definition.owner !== selfId) {
+ throw new RangeError(`addEntity: in peer to peer a peer adds only entities it owns. Leave owner out or pass "${selfId}", got ${String(definition.owner)}.`);
+ }
+ const tag = definition.tag === undefined ? null : requireName(definition.tag, 'addEntity tag');
+ entities.set(id, { owner: selfId, term: 0, tag, state: readState(definition.state ?? {}, `addEntity "${id}" state`), samples: [] });
+ },
+ removeEntity(id) {
+ requireLocalEntity(id, 'removeEntity');
+ entities.delete(id);
+ },
+ setEntityState(id, partialState) {
+ const entity = requireLocalEntity(id, 'setEntityState');
+ entity.state = readState(partialState, `setEntityState "${id}" state`, entity.state);
+ },
+ // Take over an entity another peer owns, starting from the state this peer sees. The raised term beats the old owner on every peer.
+ claimEntity(id) {
+ const entity = entities.get(id);
+ if (!entity) throw new RangeError(`claimEntity: no entity named "${String(id)}". Present: ${listPresent()}.`);
+ if (isLocal(entity)) return;
+ entity.state = drawnState(entity);
+ entity.owner = selfId;
+ entity.term += 1;
+ entity.samples = [];
+ stats.ownershipChanges += 1;
+ },
+ getEntityState(id) {
+ const entity = entities.get(id);
+ return entity ? drawnState(entity) : null;
+ },
+ getEntityOwner: id => entities.get(id)?.owner ?? null,
+ entityIds: () => [...entities.keys()],
+ get tick() { return tick; },
+ };
+}
+
// ----- createNetcode: the runtime system -----
+function createSide(settings, stats) {
+ if (settings.role === 'peer') return createPeerSide(settings, stats);
+ return settings.role === 'authority' ? createAuthority(settings, stats) : createClient(settings, stats);
+}
+
export function createNetcode(options) {
const settings = validateNetcodeOptions(options);
const stats = {
@@ -794,12 +987,13 @@ export function createNetcode(options) {
lastCorrection: 0,
maximumCorrection: 0,
rejectedMessages: 0,
+ ownershipChanges: 0,
};
- const side = settings.role === 'authority' ? createAuthority(settings, stats) : createClient(settings, stats);
+ const side = createSide(settings, stats);
let unsubscribe = null;
function requireAuthority(action) {
- if (settings.role !== 'authority') throw new TypeError(`${action} is only for the authority. This netcode is a client; the authority owns the entities.`);
+ if (settings.role === 'client') throw new TypeError(`${action} is only for the authority. This netcode is a client; the authority owns the entities.`);
}
const netcode = {
@@ -807,7 +1001,7 @@ export function createNetcode(options) {
get role() { return settings.role; },
get authority() { return settings.authority; },
get stats() { return { ...stats }; },
- get tick() { return settings.role === 'authority' ? side.tick : side.latestTick; },
+ get tick() { return settings.role === 'client' ? side.latestTick : side.tick; },
get pendingInputCount() { return side.pendingInputCount ?? 0; },
init(context) {
@@ -848,6 +1042,15 @@ export function createNetcode(options) {
getEntityState(id) {
return side.getEntityState(id);
},
+ // Peer to peer: take over an entity another peer owns. The raised term beats the old owner on every peer.
+ claimEntity(id) {
+ if (settings.role !== 'peer') throw new TypeError('claimEntity is only for peer to peer netcode (authority: "peer"). A server or host owns every entity already.');
+ side.claimEntity(id);
+ return netcode;
+ },
+ getEntityOwner(id) {
+ return side.getEntityOwner?.(id) ?? null;
+ },
get entityIds() { return side.entityIds(); },
};
return netcode;
diff --git a/tests/netcode-peer.test.js b/tests/netcode-peer.test.js
new file mode 100644
index 00000000..b3588d5a
--- /dev/null
+++ b/tests/netcode-peer.test.js
@@ -0,0 +1,116 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createRuntime } from '../src/runtime.js';
+import { createLoopbackNetwork, createNetcode } from '../src/netcode.js';
+
+const FRAME_MILLISECONDS = 20;
+const idleScheduler = { request: () => 1, cancel: () => {} };
+
+function createPeer(network, id, extraOptions = {}) {
+ const netcode = createNetcode({ authority: 'peer', transport: network.createTransport(id), snapshotEveryTicks: 1, ...extraOptions });
+ const runtime = createRuntime({ render() {} }, { mode: 'both', fixedRate: 50, scheduler: idleScheduler, systems: [netcode] });
+ return { netcode, runtime };
+}
+
+function run(network, peers, frames, onFrame) {
+ for (let frame = 0; frame < frames; frame += 1) {
+ network.advance(FRAME_MILLISECONDS);
+ peers.forEach(peer => peer.runtime.step(FRAME_MILLISECONDS));
+ onFrame?.(frame);
+ }
+}
+
+test('each peer owns and moves its own player and sees the other one', () => {
+ const network = createLoopbackNetwork({ seed: 3, latencyMilliseconds: 60 });
+ const alice = createPeer(network, 'alice', { localEntityId: 'alice', readInput: () => ({ moveX: 1, moveZ: 0 }) });
+ const bob = createPeer(network, 'bob', { localEntityId: 'bob', readInput: () => ({ moveX: 0, moveZ: -1 }) });
+ alice.netcode.addEntity('alice', { tag: 'player' });
+ bob.netcode.addEntity('bob', { tag: 'player', state: { position: [0, 0, 10] } });
+ run(network, [alice, bob], 150);
+
+ assert.equal(alice.netcode.role, 'peer');
+ assert.equal(alice.netcode.getEntityOwner('bob'), 'bob');
+ assert.deepEqual(alice.netcode.entityIds.sort(), ['alice', 'bob']);
+ const ownOnBob = bob.netcode.getEntityState('alice');
+ const truth = alice.netcode.getEntityState('alice');
+ assert.ok(truth.position[0] > 5, 'the owner moved its own entity at once');
+ assert.ok(Math.abs(ownOnBob.position[0] - truth.position[0]) < 1.5, `the remote view trails by the delay, got ${truth.position[0] - ownOnBob.position[0]}`);
+ assert.ok(bob.netcode.getEntityState('bob').position[2] < 5);
+ assert.ok(alice.netcode.stats.snapshotsReceived > 50);
+});
+
+test('two peers that claim one entity settle on the same owner whatever the arrival order', () => {
+ const outcomes = [];
+ for (const seed of [1, 2, 3, 4]) {
+ const network = createLoopbackNetwork({ seed, latencyMilliseconds: 40, jitterMilliseconds: 30 });
+ const alpha = createPeer(network, 'alpha');
+ const zulu = createPeer(network, 'zulu');
+ alpha.netcode.addEntity('crate', { state: { position: [1, 0, 0] } });
+ zulu.netcode.addEntity('crate', { state: { position: [9, 0, 0] } });
+ run(network, [alpha, zulu], 60);
+ outcomes.push([alpha.netcode.getEntityOwner('crate'), zulu.netcode.getEntityOwner('crate')]);
+ assert.throws(() => zulu.netcode.setEntityState('crate', { position: [2, 0, 0] }), /owned by peer "alpha".*claimEntity/);
+ assert.ok(zulu.netcode.stats.ownershipChanges >= 1);
+ }
+ assert.deepEqual(outcomes, outcomes.map(() => ['alpha', 'alpha']), 'equal terms: the lower peer id wins on both sides');
+});
+
+test('claimEntity raises the term, beats the lower-id owner and starts from the state the claimer saw', () => {
+ const network = createLoopbackNetwork({ seed: 5, latencyMilliseconds: 40 });
+ const alpha = createPeer(network, 'alpha');
+ const zulu = createPeer(network, 'zulu');
+ alpha.netcode.addEntity('ball', { state: { position: [4, 0, 0], velocity: [0, 0, 0] } });
+ run(network, [alpha, zulu], 40);
+ zulu.netcode.claimEntity('ball');
+ zulu.netcode.setEntityState('ball', { position: [7, 0, 0] });
+ run(network, [alpha, zulu], 40);
+
+ assert.equal(alpha.netcode.getEntityOwner('ball'), 'zulu');
+ assert.equal(zulu.netcode.getEntityOwner('ball'), 'zulu');
+ assert.ok(Math.abs(alpha.netcode.getEntityState('ball').position[0] - 7) < 0.01);
+ assert.throws(() => alpha.netcode.setEntityState('ball', { position: [0, 0, 0] }), /owned by peer "zulu"/);
+ alpha.netcode.claimEntity('ball');
+ run(network, [alpha, zulu], 40);
+ assert.equal(zulu.netcode.getEntityOwner('ball'), 'alpha', 'a later claim has a higher term and takes the entity back');
+});
+
+test('an entity of a peer that left is dropped, and bad messages and options are refused', () => {
+ const network = createLoopbackNetwork({ seed: 8, latencyMilliseconds: 20 });
+ const alice = createPeer(network, 'alice');
+ const bob = createPeer(network, 'bob');
+ bob.netcode.addEntity('bob');
+ run(network, [alice, bob], 20);
+ assert.deepEqual(alice.netcode.entityIds, ['bob']);
+ assert.equal(alice.netcode.getEntityState('nobody'), null);
+
+ const transport = { id: 'x', peers: () => ['y'], send() {}, receive() { return () => {}; } };
+ assert.throws(() => createNetcode({ authority: 'peer', role: 'client', transport }), /Leave role out/);
+ assert.throws(() => alice.netcode.addEntity('hers', { owner: 'bob' }), /adds only entities it owns/);
+ assert.throws(() => createNetcode({ authority: 'server', role: 'authority', transport }).claimEntity('a'), /only for peer to peer/);
+
+ const before = alice.netcode.stats.rejectedMessages;
+ const mallory = network.createTransport('mallory');
+ for (const message of [null, { type: 'peer-state' }, { type: 'peer-state', session: 's', tick: 1, entities: { crate: { m: 0 } } }, { type: 'peer-state', session: 's', tick: 2, entities: { crate: { p: [1, 2, 3], r: [0, 0, 0, 1000], v: [0, 0, 0], x: {}, m: -1 } } }]) {
+ mallory.send('alice', message);
+ }
+ run(network, [alice, bob], 5);
+ assert.equal(alice.netcode.stats.rejectedMessages - before, 4);
+ assert.deepEqual(alice.netcode.entityIds, ['bob']);
+});
+
+test('an older run of a peer is stale and a restart on the same id is followed', () => {
+ const network = createLoopbackNetwork({ seed: 9, latencyMilliseconds: 10 });
+ const observer = createPeer(network, 'observer');
+ const sender = network.createTransport('sender');
+ run(network, [observer], 1);
+ const entity = (x, term) => ({ p: [x * 100, 0, 0], r: [0, 0, 0, 1000], v: [0, 0, 0], x: {}, m: term });
+ sender.send('observer', { type: 'peer-state', session: 'b', tick: 5, entities: { ball: entity(2, 0) } });
+ sender.send('observer', { type: 'peer-state', session: 'a', tick: 9, entities: { ball: entity(8, 0) } });
+ sender.send('observer', { type: 'peer-state', session: 'b', tick: 4, entities: { ball: entity(8, 0) } });
+ run(network, [observer], 5);
+ assert.equal(observer.netcode.stats.staleSnapshots, 2);
+ assert.ok(Math.abs(observer.netcode.getEntityState('ball').position[0] - 2) < 0.01);
+ sender.send('observer', { type: 'peer-state', session: 'c', tick: 0, entities: { ball: entity(5, 0) } });
+ run(network, [observer], 20);
+ assert.ok(Math.abs(observer.netcode.getEntityState('ball').position[0] - 5) < 0.01);
+});
diff --git a/tests/netcode-two-browsers.test.js b/tests/netcode-two-browsers.test.js
index 87d74002..bf0decc1 100644
--- a/tests/netcode-two-browsers.test.js
+++ b/tests/netcode-two-browsers.test.js
@@ -147,7 +147,7 @@ async function playTogether(context, transport, relayPort) {
return { hostToClientLag, clientToHostLag, positions };
}
-for (const transport of ['broadcast', 'websocket']) {
+for (const transport of ['broadcast', 'websocket', 'webrtc']) {
test(`two browser pages converge and show a move within bounded lag over ${transport}`, async testContext => {
let chromium;
try {
diff --git a/tests/netcode.test.js b/tests/netcode.test.js
index b275a03d..dab1f179 100644
--- a/tests/netcode.test.js
+++ b/tests/netcode.test.js
@@ -183,7 +183,7 @@ test('invalid options and calls throw errors that say what to pass', () => {
assert.throws(() => createNetcode({ transport: { id: 'x' } }), /transport\.peers must be a function/);
assert.throws(() => createNetcode({ transport, role: 'spectator' }), /role must be one of authority, client/);
assert.throws(() => createNetcode({ transport, role: 'client' }), /serverId/);
- assert.throws(() => createNetcode({ transport, role: 'authority', authority: 'peer' }), /peer to peer\) is not supported yet/);
+ assert.throws(() => createNetcode({ transport, role: 'authority', authority: 'peer' }), /authority "peer" has no authority or client role/);
assert.throws(() => createNetcode({ transport, role: 'authority', authority: 'cloud' }), /authority must be one of server, host/);
assert.throws(() => createNetcode({ transport, role: 'authority', snapshotEveryTicks: 0 }), /snapshotEveryTicks/);
assert.throws(() => createNetcode({ transport, role: 'authority', simulate: 3 }), /simulate must be a function/);