# Multiplayer Room State Sync & 60 Hz Avatars in Three.js

> Solo-first multiplayer with smooth 60 Hz remote avatars, host-owned shared state, reliable host claims, and deterministic two-peer room tests.

- **Canonical page:** https://gamecrew.ai/techniques/three/multiplayer-room-state-interpolation
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** gameplay
- **Tags:** `multiplayer`, `networking`, `rooms`, `interpolation`, `host-migration`, `net`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

Browser multiplayer breaks down when startup blocks waiting for a second tab or when raw 20 Hz WebSocket pose packets visibly stutter on a 60–120 Hz screen. Using the studio's `game.net` API solves both cleanly:

1. **Solo-First Startup (`isHost === true` Alone)**: Immediately run the loop when `game.net.players` only contains `game.net.me`. Remote teammates join live through `bindAvatar(...)` without restarting the level.
2. **Throttled Pose Send + 60 Hz Snapshot Interpolation**: Call `game.net.setMyPose(...)` each step; `game.net` transmits deltas at 20 Hz and exposes smooth 60 Hz interpolated poses on `game.net.poseOf(peer.id)` and bound avatars.
3. **Host-Authoritative Claims + Automatic Host Migration**: Never mutate shared pickups locally as truth for everyone. Send `'host'`-routed events (`game.net.send('claim_beacon', { index }, 'host')`), let `isHost` validate once, publish `game.net.setState(...)`, and keep `onHostChange` ready if Peer 1 disconnects.

## Mathematical & Algorithmic Core

- **Circular Yaw Blending**: Interpolate headings over shortest angular delta $\Delta\psi \in [-\pi, \pi)$:
  $$\Delta\psi = ((\psi_1 - \psi_0 + \pi) \bmod 2\pi) - \pi, \qquad \psi(t) = \psi_0 + t\,\Delta\psi$$
- **Monotonic Claim Version**: Store a monotonically increasing claimed mask or array in `game.net.state` so late-joining guests converge immediately to current world state without replaying old events.

## Engine Implementation

### Host-Authoritative Co-Op Beacons & Avatars (`Assets/Game/coop-beacons.ts`)

```ts
import * as THREE from 'three';
import type { Game } from 'ccgd';

export interface BeaconClaimEvent {
  readonly index: number;
}

export interface BeaconFxEvent {
  readonly index: number;
  readonly byName: string;
}

export function setupCoopBeacons(
  game: Game,
  beacons: readonly THREE.Object3D[],
  getPlayerPose: () => { x: number; y: number; z: number; yaw: number; moving: boolean },
  onScoreChange: (scores: Readonly<Record<string, number>>) => void,
): () => void {
  const claimed = new Set<number>();
  const scores: Record<string, number> = {};

  const applyClaimedMask = (indices: unknown): void => {
    if (!Array.isArray(indices)) return;
    claimed.clear();
    for (const raw of indices) {
      if (typeof raw === 'number' && Number.isInteger(raw)) {
        claimed.add(raw);
      }
    }
    for (let i = 0; i < beacons.length; i++) {
      beacons[i].visible = !claimed.has(i);
    }
  };

  // Spawn and 60 Hz-interpolate a capsule avatar per remote peer automatically.
  const unbindAvatars = game.net.bindAvatar((peer) => {
    const group = new THREE.Group();
    const torso = new THREE.Mesh(
      new THREE.CapsuleGeometry(0.32, 0.78, 6, 12),
      new THREE.MeshStandardMaterial({ color: peer.color, roughness: 0.45 }),
    );
    torso.position.y = 0.72;
    torso.castShadow = true;
    group.add(torso);
    return group;
  });

  const unsubState = game.net.onState((state) => {
    applyClaimedMask(state.claimedBeacons);
    if (state.scores && typeof state.scores === 'object') {
      onScoreChange(state.scores as Record<string, number>);
    }
  });

  const unsubClaim = game.net.on<BeaconClaimEvent>('claim_beacon', (data, from) => {
    if (!game.net.isHost) return;
    if (data.index < 0 || data.index >= beacons.length || claimed.has(data.index)) return;

    claimed.add(data.index);
    const key = String(from.id);
    scores[key] = (scores[key] ?? 0) + 1;
    beacons[data.index].visible = false;

    game.net.setState({
      claimedBeacons: [...claimed],
      scores: { ...scores },
    });
    game.net.send('beacon_fx', { index: data.index, byName: from.name }, 'all');
  });

  const unsubFx = game.net.on<BeaconFxEvent>('beacon_fx', () => {
    game.audio.play('pickup', { volume: 0.7 });
  });

  const unsubHost = game.net.onHostChange((isNowHost) => {
    if (isNowHost) {
      // Rehydrate local tracking structures immediately upon promotion
      applyClaimedMask(game.net.getState('claimedBeacons', []));
    }
  });

  game.onUpdate(() => {
    const pose = getPlayerPose();
    game.net.setMyPose({
      x: pose.x,
      y: pose.y,
      z: pose.z,
      yaw: pose.yaw,
      anim: pose.moving ? 'run' : 'idle',
    });
  });

  return () => {
    unbindAvatars();
    unsubState();
    unsubClaim();
    unsubFx();
    unsubHost();
  };
}
```

### Deterministic Two-Peer & Host-Migration Test (`Assets/Game/Tests/play/net-coop.test.ts`)

```ts
import { test } from 'ccgd';

test('remote pose interpolation and host migration keep room state intact', async (t) => {
  const rival = t.game.net.sim.addPeer({ name: 'RIV1' });
  rival.setPose({ x: 3.5, y: 0, z: -2.0, yaw: 0.75 });
  await t.steps(6);

  const interpolated = t.game.net.poseOf(rival.peer.id);
  t.ok(interpolated !== undefined, 'remote peer pose tracked');
  if (interpolated) {
    t.near(interpolated.x, 3.5, 0.05, 'interpolated x matches peer');
  }

  const hostPeer = t.game.net.sim.addPeer({ asHost: true, name: 'HOST' });
  t.eq(t.game.net.isHost, false, 'client yields host role to lower peer id');
  t.game.net.sim.pushHostState({ round: 2 });
  t.eq(t.game.net.getState<number>('round', 0), 2, 'host state replicated');

  t.game.net.sim.dropHost();
  t.eq(t.game.net.isHost, true, 'surviving client promoted to host cleanly');
  void hostPeer;
});
```

## Browser & Bandwidth Guardrails

- **Bounded State Keys**: Store compact arrays/objects inside `game.net.setState(...)` rather than full frame histories so join snapshots fit comfortably in one WebSocket message.
- **Always Test Solo + Drop-In**: Verify play tests pass before any `sim.addPeer` call so the single-player default stays responsive on first paint.

## Verification Checklist

1. Run `ccgd mp-check` (or `net.sim` play test) to verify two simulated peers sync state cleanly and survive host departure.
2. Confirm every `setState` mutation sits behind an `isHost` check so guests never overwrite authoritative world state.

## Official references

- Glenn Fiedler (Gaffer on Games — State Synchronization & Snapshot Interpolation)
- GameCrew Multiplayer Room Protocol Reference
