Interactive Vision From Zero · Episode 22
Multiplayer Body
Multiplayer Body is Episode 22 of Interactive Vision From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Sit next to a friend, each on your own laptop, and open this page in two tabs. You raise your arm — and a moment later, their screen shows your arm go up. They wave back; you see the wave. You are sharing a room with another person's whole body, in real time. And here's the part that should feel a little magical: your camera feed never left your machine. No video was uploaded, no frame was streamed, no face was sent anywhere. The only thing that crossed the wire was about thirty numbers.
That's the whole trick of this episode. A body, to a vision model, is just 33 little dots — landmarks. If all you transmit is those dots, you can put two people in the same canvas while keeping every pixel of webcam strictly on-device. It's the rare case where the private thing and the cheap thing are the same thing: landmarks are tiny and they carry none of your likeness. Below, you're already in a populated space — synthetic bot bodies are milling around so the room is alive even solo. Open a second tab and a real shared body joins them.
· open a 2nd tab to truly join ·
What you're looking at
Every skeleton on screen is drawn by the same twelve lines of code — there
is no "me renderer" and "peer renderer" and "bot renderer." There is one
drawBody(), and it doesn't know or care where a body's 33 landmarks came
from. Your body comes from the synthetic driver (or your camera). The bot bodies come
from a function of time. The remote bodies come off a BroadcastChannel from
another tab. They all arrive as the same shape — [{x, y, z, visibility} × 33]
— and they all flow through one onLandmarks path. Hold that idea; it's why
the demo looks identical whether you have one tab open or three.
The badge bottom-left counts N in space: you, plus live remote tabs, plus the bots. Drag the bots slider and watch the room fill or empty. Step the stage dropdown to peel the system apart one layer at a time.
Stage 1 — Your body
The baseline: a single skeleton, yours. With no camera it's the
syntheticPose driver from Season 2 — a standing figure that idles and sways,
its 33 landmarks emitted in exactly MediaPipe's format. Move your mouse and you puppet
where the body stands. Because this is a selfie view, we mirror the X axis
(screenX = (1 - x) · width) so moving your mouse right moves the body right.
That mirror flip is the single most common "why is everything backwards" bug in the whole
series — say it out loud now and you'll never chase it later. Nothing is broadcast yet;
this is just you, in an empty room.
Stage 2 — Broadcast your landmarks
Now we start shipping those dots. Every ~40ms (≈25Hz) we take your 33
landmarks, round them down to a flat array of small numbers, and
postMessage them onto a BroadcastChannel. That's the entire
upload: not a video, not an image, not even JSON objects — a flat list of rounded floats.
A body pose is around 30 numbers after we drop the joints we don't draw.
Watch the status line tick the send count. You're broadcasting into the void for now (no
one's listening yet) — but the cost of being "online" just became a rounding error.
Stage 3 — Render remote bodies
Open a second tab (button up top). Each tab is a separate participant on the same
channel, so tab A's broadcasts arrive in tab B's onmessage and vice versa.
We keep a Map of peers keyed by a per-tab id; when a packet arrives we
decode the flat array back into 33 landmarks and store them. Then we draw every peer with
the same drawBody we used for ourselves. Suddenly there are two real people
in the canvas — and the second one is genuinely a different browser tab, reacting to a
different mouse (or a different camera). No server was involved.
Stage 4 — Smoothing
Raw remote bodies look jumpy. We only send ~25 packets a second, but we draw
at 120fps, so between packets a remote skeleton would simply freeze, then teleport to its
next pose. The fix is the same one streaming engines use: store each peer's incoming pose
as a target, keep a separate rendered pose, and every
frame ease the rendered pose a fraction of the way toward the target — a per-landmark
lerp. Toggle this stage on and off and the difference is stark: raw is a
strobe, smoothed is a person. (Episode 23 upgrades this to a proper One-Euro filter.)
Stage 5 — Bot bodies
A multiplayer space that's empty when you arrive feels broken — you assume nothing is
working and leave. So we populate the room with bots: synthetic peers
driven by time, each a syntheticPose with its own phase, position, and a
little walk cycle. The crucial discipline: a bot is not a special case. It's
just another entry in the same peers map, drawn by the same drawBody. They
are deliberately indistinguishable from real tabs on screen — which means if the room
looks alive with bots, it'll look exactly that alive the instant a real second tab joins.
Slide bots from 0 to 6 to feel the room breathe.
Stage 6 — Shared interaction: the high-five
Two bodies in one coordinate space can touch. In this stage we watch the wrists (landmarks 15 and 16) of every pair of bodies; when two people's hands come close enough, a bright link snaps between them and a spark blooms — a high-five. Because bots are first-class bodies, you'll catch a high-five with a bot now and then; do it with a real tab and you've built genuine shared interaction over zero backend. This is the seed of every co-op gesture: a shared whiteboard, a tug-of-war, a handshake-to-connect.
How the code works
Four pieces carry the whole episode: a compact broadcast, a
peers map + remote rendering, interpolation, and
bots + presence. Everything is wrapped so the synthetic baseline keeps
running even if BroadcastChannel doesn't exist.
(a) The compact landmark broadcast
The privacy and the bandwidth win live here. We never touch the camera frame.
We take the 33 landmarks, keep only the joints we draw, round to ~3 decimals (a body
doesn't need micrometer precision), pack them into a flat Float array, and
send at most ~25× a second. Local rendering stays at full framerate; only the
broadcast is throttled.
// (a) Round + send ONLY what we draw, throttled to ~25Hz. No video, ever.
const SEND_HZ = 25, SEND_MS = 1000 / SEND_HZ;
const SENT = [0,11,12,13,14,15,16,23,24,25,26,27,28]; // 13 joints we render
let lastSent = 0;
function broadcastBody(pose) { // pose = [{x,y,z,visibility}×33]
const now = performance.now();
if (now - lastSent < SEND_MS) return; // throttle — don't flood the channel
lastSent = now;
const a = [];
for (const i of SENT) {
const p = pose[i];
a.push(Math.round(p.x * 1000) / 1000, // x,y to 3 decimals…
Math.round(p.y * 1000) / 1000); // …z is a hint we can skip here
}
send({ k: 'pose', id: me.id, c: me.color, a }); // ~30 numbers total
}
That array is the entire footprint of your presence. Thirteen joints × two coordinates is 26 numbers, plus an id and a color. Compare that to even one 320×240 JPEG frame (tens of kilobytes) thirty times a second. The landmark stream is roughly a thousand times smaller — and it can't be reassembled into your face.
(b) The peers map + rendering remote skeletons
Receivers keep a Map from peer id to that peer's state. The golden rule of
BroadcastChannel: ignore packets from your own id (it doesn't
echo to the sender, but bots and re-entry can still confuse you). We unpack the flat array
back into landmark objects and stash them as a target — rendering will chase it.
// (b) peers: id → { color, target[], pose[], last }. ONE drawBody for everyone.
const peers = new Map();
function unpack(a) { // flat [x,y,…] → sparse 33-slot pose
const pose = new Array(33);
for (let j = 0; j < SENT.length; j++)
pose[SENT[j]] = { x: a[j*2], y: a[j*2+1], z: 0, visibility: 1 };
return pose;
}
function onPosePacket(m) {
if (m.id === me.id) return; // never render our own echo
let p = peers.get(m.id);
if (!p) p = { color: m.c, pose: null, target: null, last: 0 }, peers.set(m.id, p);
p.target = unpack(m.a); // store TARGET; the loop lerps toward it
p.color = m.c || p.color;
p.last = performance.now(); // liveness clock for pruning
}
// each frame, after lerping: for (const p of peers.values()) drawBody(p.pose, p.color);
(c) Interpolating remote landmarks
The target is where the peer is; pose is where we currently
draw them. Every frame we nudge each landmark a fraction toward its target. At
120fps a factor around 0.2 hides the 25Hz packet rate completely while still
feeling responsive.
// (c) Per-landmark lerp: chase the target a little each frame → buttery remote bodies.
const lerp = (a, b, t) => a + (b - a) * t;
function smoothPeer(p, t) { // t ≈ 0.2; raw=jumpy, lerped=alive
if (!p.target) return;
if (!p.pose) { p.pose = p.target.map(l => l && { ...l }); return; } // snap on first packet
for (const i of SENT) {
const tgt = p.target[i], cur = p.pose[i];
if (!tgt) continue;
if (!cur) { p.pose[i] = { ...tgt }; continue; }
cur.x = lerp(cur.x, tgt.x, t);
cur.y = lerp(cur.y, tgt.y, t);
}
}
(d) Synthetic bots + presence prune + leave
Bots are entries in the same map, refreshed every frame from time. Real peers get a
heartbeat so they stay listed while idle, a prune sweep
that drops anyone silent past a timeout, and an explicit leave on
pagehide (the reliable close event — unload is not). Heartbeat +
explicit-leave + timeout-prune is the classic presence recipe.
// (d) Bots fill the room solo; presence keeps the real roster honest.
function tickBots(t) {
for (const b of botList) {
const pos = { x: 0.5 + b.ax * Math.sin(t * 0.4 + b.px), y: 0.55 };
const pose = syntheticPose(t * b.speed + b.px, pos, { walk: true });
peers.set(b.id, { color: b.color, pose, target: null, last: performance.now(), bot: true });
}
}
setInterval(() => send({ k: 'beat', id: me.id, c: me.color }), 1500); // HEARTBEAT
setInterval(() => { // PRUNE stale peers
const now = performance.now();
for (const [id, p] of peers)
if (!p.bot && now - p.last > 4000) peers.delete(id);
}, 1000);
addEventListener('pagehide', () => send({ k: 'leave', id: me.id })); // say goodbye
And the transport glue, wrapped so a browser without the API still runs the synthetic baseline with bots — it just won't see other tabs:
let room = null;
function send(msg) { if (room) try { room.postMessage(msg); } catch (e) {} }
try {
if (typeof BroadcastChannel === 'undefined') throw new Error('no channel');
room = new BroadcastChannel('vision-body-room-22');
room.onmessage = (e) => { try { route(e.data); } catch (err) {} };
send({ k: 'hello', id: me.id, c: me.color }); // announce to existing tabs
} catch (err) { room = null; /* synthetic + bots still run */ }
The camera swap (real bodies, still private)
Click use my camera and the demo lazy-imports MediaPipe's
PoseLandmarker, grabs your webcam, and feeds the detected pose into the
same onLandmarks path the synthetic driver used. Crucially, the
camera frame goes only to the on-device model; what gets postMessage'd is
still just the 33 landmarks. You appear in your friend's tab without a single pixel of
your face crossing the wire. The import lives inside enableCamera() and is
wrapped in try/catch — no webcam, denied permission, or a
file:// page all fall back silently to the synthetic body. The page never
errors on a camera-less load.
Common pitfalls
- BroadcastChannel is same-origin, same-browser, cross-tab only. It's perfect for two tabs on one machine (and great for a demo with a friend who has the page open on their own laptop, each seeing their own bots). But it does not reach across devices or browsers — there's no network hop at all. Real cross-device multiplayer needs a signaling server and WebRTC; that's the whole point of the streaming series (Eps 03–08). BroadcastChannel is the serverless stand-in that lets you build and feel the entire architecture first.
- Bandwidth: send compact, send throttled. The naïve version
broadcasts all 33 full
{x,y,z,visibility}objects every frame — that's ~120 numbers × 120Hz of needless traffic. Drop to the joints you draw, round to 3 decimals, and throttle to ~25Hz. Render locally at full speed; only the send is rate-limited. - Raw remote landmarks jump. You send at 25Hz but draw at 120Hz, so
an un-interpolated peer freezes then teleports. Keep a target and a rendered pose and
lerpbetween them every frame (Stage 4). Episode 23 replaces this with a One-Euro filter for jitter and lag. - Stale peers never leave. Tabs crash, sleep, or get force-quit
without firing
pagehide. If you only remove peers on an explicit leave message, ghosts pile up forever. Pair the leave with a heartbeat-and-timeout prune so silence eventually cleans itself up. (Bots are exempt — they're driven locally.) - Echoing your own packets. Always
if (m.id === me.id) return. BroadcastChannel won't echo to the sender, but a stray re-broadcast or a duplicated tab id will draw a phantom "you." - The privacy win is the whole story — protect it. The instant you
postMessagea canvas frame, a data-URL, or a video track "just to make it richer," you've thrown away the entire advantage. The contract is: landmarks leave, video never does. Keep it. - Mirrored axis. Selfie view flips X:
screenX = (1 - x) · widthon both the synthetic and camera paths, or your body waves the wrong way.
Exercises
- Send a gesture/emoji event. Detect a simple pose (both wrists above
the nose = "🙌") and broadcast
{ k: 'emoji', id, e: '🙌' }— separate from the throttled pose stream. Float the emoji over that peer's head for a second in every tab. You've added an event channel alongside the state channel. - A shared fingertip whiteboard. Switch to
HandLandmarker, track the index tip (landmark 8), and when a pinch is held, broadcast line segments{ k: 'ink', id, x0, y0, x1, y1 }. Keep a history array so a late-joining tab can be sent the existing strokes. Now two people draw on one board with their fingers. - Compress the landmarks further. Quantize each coordinate to a single
byte (0–255) instead of a 3-decimal float, and pack the whole pose into a
Uint8Array—BroadcastChannelcan carry typed arrays directly. Measure the byte count before and after. How few bytes can a recognizable body survive on?
What's next
Episode 23 — Robustness & performance. We've been polite to our tracker: good light, one clear body, a fast machine. Next we make it survive the real world. We'll build the One-Euro filter (the right way to kill jitter without adding lag), inject synthetic jitter to prove raw-vs-smoothed, handle lost tracking with a hold-and-recover policy instead of a flicker, and set hard perf budgets so the pipeline holds framerate on a laptop, not just your desktop.