# moddio SDK > Multiplayer games for modd.io. A game is a deterministic simulation (sim.ts) that runs on > every player's machine and in the room, optional server hooks (server.ts), and a renderer in > any engine (client/). Players send only typed inputs; the room orders them into frames, runs > the sim as the authority and sends each frame's inputs to everyone. Your own inputs apply at > once (prediction); the room corrects anyone who disagrees with it. ## Folder my-game/ moddio.json { "name": "my-game", "title": "My Game", "game": "" } sim.ts export default defineSim({...}) the rules (players per room: its maxPlayers) server.ts export default defineServer({...}) optional server-only hooks client/ index.html + main.ts the renderer (index.html loads main.js, which is main.ts bundled by moddio dev/publish) assets/ images, sounds Use relative paths for every file a game loads: `main.js`, `assets/hero.png`, `client/style.css`, never `/main.js` or `/assets/...`. A published game may be served under a path (on a preview or behind a proxy, at /__g/--/), where a path starting with / points outside it. `moddio dev` and the site serve the same files at the same relative paths. Start: `npm create moddio my-game -- --template arena|soccer|legacy|marble [--game ]`, then `cd my-game && npm install`. Commands: `moddio dev` (local room + page; open ?player=a and ?player=b, or /__moddio/play?player=a for the play page's sandboxed frame), `moddio test` (run after every change), `moddio login`, `moddio publish`. Outputs go under the project's .moddio/. ## sim.ts import { defineSim } from '@moddio/sim'; export default defineSim({ name: 'my-game', // short id version: '1', // bump when the rules change tickRate: 20, // ticks per second (default 20) maxPlayers: 16, input: { move: ['i8', 'i8'], aim: 'u16', buttons: { flags: ['fire', 'jump'] } }, // the input SHAPE init(ctx) { return { players: {}, coins: [] }; }, // starting state; ctx.rng, ctx.seed, ctx.config join(state, id, ctx, info) { // info: { id, name, avatar, roles } from the player's ticket state.players[id] = { name: info.name, x: 0, y: 0, move: [0, 0], fire: false }; }, leave(state, id, ctx) { delete state.players[id]; }, disconnect(state, id, ctx) {}, // optional: connection lost, seat kept (default: nothing) reconnect(state, id, ctx) {}, // optional onInput(state, id, input, ctx) { // the player's latest input; store it, act in step const p = state.players[id]; p.move = [input.move[0] / 128, input.move[1] / 128]; p.fire = input.buttons.fire; }, event(state, e, ctx) {}, // a server event (from server.ts), on its frame predict: 'self', // the default; or 'world' (see Prediction below) step(state, ctx) { // one tick for (const id of Object.keys(state.players).sort()) { const p = state.players[id]; p.x += p.move[0] * 5; p.y += p.move[1] * 5; } }, }); ### Input shapes Scalars: `i8 u8 i16 u16 i32 u32 f32 bool`. Tuples: `['i8', 'i8']` (arrays). Bitfields: `{ flags: ['fire', 'jump'] }` (an object of booleans, up to 32). A record of fields is the top level. At most 64 bytes. Values are clamped and truncated to their type (f32 rounded, non-finite becomes 0); the room drops any input that is not exactly the shape. An input HOLDS until the next one: the client sends inputs only when they change. So store the latest input in the state in onInput and act on it in step; never treat an input as "this tick only". ### ctx ctx.frame ticks since the room began (seconds = frame / tickRate) ctx.tickRate ctx.rng() [0, 1), deterministic: the same on every client ctx.int(n) integer in [0, n) ctx.players player ids in the room, sorted ctx.out(effect) ask the platform for something: { save: data, player }, { coins: 'give', amount, player }, { offer: 'sword', player }, { text: 'ask', player }. Every client computes effects; only the room's are carried out. ctx.physics the physics world, if the sim declares `physics` ctx.config (init only) the room's settings ### Rules (the realm enforces them; the errors say what to use) - No Math.random (use ctx.rng), no Date or timers (count ctx.frame), no fetch/WebSocket (use ctx.out and server events), no Intl/toLocaleString/localeCompare (compare with < and >). These do not exist in the sim: it runs in its own realm with them removed. - Math.sin/cos/tan/exp/log/pow/atan2/hypot/cbrt... are deterministic replacements, the same bits in every browser. `**` is compiled to the same Math.pow. + - * / and Math.sqrt are exact. - State is plain data: objects, arrays, numbers, strings, booleans, null (and Uint8Array). No classes, Map, Set, Date, functions, and no object referenced from two places (store ids). - Iterate players in a fixed order: `Object.keys(state.players).sort()`. - Never branch on anything but the state, the input and ctx. - Secrets cannot live in the sim (every client has the whole state): hidden randomness comes from the server as an event when it happens. ### Physics Rapier (deterministic build), 2D or 3D: import RAPIER from '@dimforge/rapier2d-deterministic-compat'; import { rapier, bodyFingerprint, renderBodies } from '@moddio/sim/rapier'; defineSim({ physics: rapier(RAPIER, { gravity: { x: 0, y: 0 }, timestep: 1 / 20 }), init(ctx) { const world = ctx.physics; ... }, // typed: RAPIER.World, no casts step(state, ctx) { ... ctx.physics.step(); }, fingerprint: (state, id, { physics }) => bodyFingerprint(physics, state.players[id].body), render: (state, { physics }) => ({ ...state, bodies: renderBodies(physics) }) }) Keep body HANDLES (numbers) in the state; get bodies with `ctx.physics.getRigidBody(handle)`. `bodyFingerprint(world, handle)` is a body's pose to the centimetre (the usual 'self' fingerprint); `renderBodies(world)` lists every collider as plain data for render(): `{ h, x, y, a, r }` (ball) or `{ h, x, y, a, hx, hy }` (box) in 2D; `z`, quaternion `q` and box half extents `e` in 3D. `h` is the body handle. Planck.js 0.3.22 (moddio2's physics): import { planck, pl } from '@moddio/sim/planck'; defineSim({ physics: planck({ gravity: { x: 0, y: 0 } }), init(ctx) { const world = ctx.physics; const b = world.createBody({ type: 'dynamic', position: pl.Vec2(1, 2) }); b.createFixture(pl.Circle(0.5), { density: 1 }); return { ball: world.idOf(b) }; }, step(state, ctx) { const world = ctx.physics; world.step(1 / 20, 8, 3); for (const c of world.contacts()) { /* { type: 'begin'|'end', a, b, sensor } by body id */ } } }) Keep body ids (`world.idOf(body)`) in the state; look up with `world.bodyOf(id)`. Read contacts with `world.contacts()` right after `world.step()`. Contact listeners you add yourself must be registered in `planck({ setup(world, pl) { ... } })`, which runs on every rebuilt world. With the default `predict: 'self'`, a physics game returns its own body's pose from `fingerprint(state, id, { physics })`, rounded to centimetres (see Prediction). ### Any other physics library: write a driver Games may use any physics library, as long as it is deterministic. `moddio test` proves it: the sim must hash the same in V8, JavaScriptCore and SpiderMonkey every tick, or the game doesn't publish. Plug a library in with a `PhysicsDriver` (exported by `@moddio/sim`): const myPhysics: PhysicsDriver = { kind: 'mylib', canonicalEvery: 0, // 0 if save/load is exact; else rebuild every N frames (below) predict: 'self', // optional: the default prediction mode for games on it async ready() { /* load wasm etc. once */ }, create() { return new MyWorld(); }, // a fresh world, for init save(world) { return /* plain data: everything load needs */; }, load(data) { return /* a world that continues exactly like the saved one */; }, digest(world, h, q) { return /* fold every body's state into hash h; round numbers to 1/q when q is given */; }, free(world) { /* release wasm memory; called when a world is abandoned */ }, view(world) { return world; }, // optional: what the game sees as ctx.physics }; defineSim({ physics: myPhysics, ... }) When each is called: - `create`: once per room, before `init`. - `save`: for snapshots (joiners, corrections) and when the prediction is copied. - `load`: when a client joins mid-game, is corrected, or rolls back. It must be a pure function of what `save` returned. - `digest`: every frame for the room's hash and the cross-engine check; with `q`, for the prediction's fingerprint. **Exact or canonical.** If a world restored with `load(save(w))` steps bit-for-bit like `w`, set `canonicalEvery: 0` (Rapier, Box2dWeb with care). If it doesn't (a library whose contact cache or broad-phase tree is history, not data, like Planck), set `canonicalEvery` (e.g. 100): every world, the room's included, is rebuilt from its own save on those frames, so all of them agree again by construction, and snapshots are taken only on those frames. **Pitfall: state outside the world.** Some libraries keep settings in module- or class-level variables that only their world constructor sets (Box2dWeb does this for two settings). A client restored with `load` never runs that constructor, so it silently drifts from the room and keeps being corrected. `load` must set every such global itself. Node tests can't show this, because there the room and the clients share one realm; the browser test can. ### Prediction Your own player always has zero input delay. The default, `predict: 'self'`, predicts only your player: the renderer draws everyone else from the room's world, interpolated (smooth, about a playout delay behind), and itself from `self` (see client). Physics games return their own body's pose from `fingerprint(state, id, { physics })`, rounded to centimetres (used only in 'self' mode; 'world' always compares the whole world). Choose `predict: 'world'` only when the local player's actions on others must show at once - shoving another player's body, grabbing a shared item first, a melee hit that must land on screen the instant you press. The whole predicted world is then kept in step with the room and drawn as one (`state` and `self` are the same world); remote players can snap when the room corrects them, and it costs more CPU (a rebuild on about 40% of ticks, against 1%). ## server.ts import { defineServer } from '@moddio/server'; export default defineServer({ async join(player, room) { // player: { id, name, roles } room.event({ type: 'loaded', id: player.id, save: await room.save.get(player) }); }, async leave(player, room) {}, async effect(effect, room) { // the room's ctx.out effects if ('save' in effect) await room.save.set(effect.player, effect.save); }, tick(room) { // every frame; may be async (skipped while still running) if (room.frame % 600 === 0 && room.random() < 0.5) room.event({ type: 'boss', x: room.random() * 100 }); }, }); room: `id` (the room's name), `state` (a per-room object for anything the hooks keep), `event(e)` (plain data; returns the frame it applies on, a few frames ahead, the same frame for everyone), `private(player, data)` (to one player, outside the state), `save.get/set` (64 KB per player), `coins.give(player, amount, requestId)`, `random()`, `frame`, `players`, `log()`. Hooks never change the state directly: only through room.event. Every `ctx.out({...})` the sim makes, whatever its shape, reaches `effect` (from the room's own copy of the sim only). The hooks run in a sandbox, one per room: no require, process, fs, fetch or timers, a CPU limit per call (a hook stuck in a loop is stopped, and the room plays on), and module-level variables are per room. `moddio test` runs them that way and reports which hooks ran, which events they inserted, and fails if any hook threw. ## client (renderer) import { playInWorker, canvas2d, controls, mergeSelf } from '@moddio/client/browser'; const view = canvas2d(canvas); // sized to the window at screen density, resized only when it is const keys = controls(canvas); const game = await playInWorker({ input: () => ({ move: keys.move().map((v) => v * 127), aim: 0, buttons: { fire: keys.mouse.down, jump: keys.pressed(' ') } }), }); game.onFrame(({ state, self }) => { // every screen frame, interpolated const ctx = view.begin('#101418'); // transform reset to CSS pixels, background filled const s = mergeSelf(state, self, 'players', game.player); // everyone from state, you from self if (s) draw(ctx, s, view.width, view.height); }); game.onEffect((effect, frame) => {}); // confirmed effects game.onPrivate((data) => {}); game.player // your player id The sim, the netcode and the room connection run in a Web Worker; the page samples `input` continuously and draws. What onFrame hands over is the sim's `render(state, { physics })` output (or its state, if it has no render), interpolated between the two ticks around this instant (numbers blended, objects by key, arrays by item `id`/`h`): `state` is what to draw, `self` the local player's world at its own clock: draw everyone from `state` and yourself from `self` (in predict 'world' they are the same world). `mergeSelf(state, self, 'players', id)` does that for a record keyed by player id; for an array, name the item key: `mergeSelf(state, self, 'bodies', state.players[me].body, 'h')`. `controls(canvas)`: `keys` (held, lower-case `KeyboardEvent.key`), `move()` (WASD/arrows as [-1..1, -1..1]), `mouse` ({ x, y } in CSS pixels, `down`, `buttons` [main, middle, secondary]; no context menu over the canvas), `pressed(key)` (true once per press of a key or 'mouse0'..'mouse2', for one-shot actions), `world({ scale, ox, oy })` (the pointer in world units, given screen = world * scale + offset). `canvas2d(canvas, { size: 'element', hiDpi: false })` follows the element's CSS size or draws one canvas pixel per CSS pixel; `view.onResize(cb)`. A physics game must define `render` and return its bodies' poses as plain data: the physics world lives in the worker, out of the page's reach. render(state, { physics }) { return { players: state.players, bodies: [/* { x, y, angle, ... } */] }; } On the play page, the client asks the page for a ticket (postMessage), which names the room, the player and the room host; under `moddio dev` it uses room '/dev', ?player= from the URL, and this page's host. Pages are served as the site serves them: sandboxed (opaque origin), no eval, no inline scripts, no localStorage or cookies, no other hosts. /__moddio/play?player=a stands in for the play page. Load scripts with type="module". Your inputs apply at once (zero input delay). Never change the state in the renderer. Inspection, for tests, HUDs and the console: `game.inspect()` returns `{ confirmed: { frame, state }, predicted: { frame, state }, hashAt(frame), stats, report, mode }`; `report.desync` counts the room's hash checks (agreed / disagreed). `game.frameView()` returns what onFrame would draw now. A browser game is also on `window.moddioGame`. Spectators: `watch({ sim, url, room })` (from '@moddio/client') runs the sim on the room's ticks and sends nothing that counts; a relay (`serveRelay` from '@moddio/room/node') serves many viewers from one feed. `{ text: 'ask' }` and `{ offer }` effects for your player are shown by the play page; the answer comes back as a server event. Headless (Node, bots, tests): `import { play } from '@moddio/client'` runs Lockstep in-process with a sim loaded by `loadSimFile` from '@moddio/sim/node'. ## Publishing `moddio login` (once; the site shows a code to allow), then `moddio publish`: it builds, runs `moddio test` on the same bundle, writes it (sim.js, server.js, client/, assets/ under their own paths, manifest.json) and uploads it as a new version. The game's slug is recorded in moddio.json ("game"). `--public` makes the game playable by anyone with the link once the version passes review. `--local` only writes the bundle. MODDIO_SITE and MODDIO_TOKEN override the site and the token. ## Testing `moddio test` plays the game with bots (random inputs of your shape, joiners, dropped connections, lossy links) and checks that every client's state hash equals the room's on every frame; replays the round in V8, JavaScriptCore and SpiderMonkey and checks every tick's hash; and reports CPU per tick and per rollback, state size and bandwidth. A mismatch means the sim is not deterministic: look for randomness or time, iteration order that depends on history, or state kept outside the state object (module-level variables). # modd.io platform: publishing and playing Site: https://www.modd.io ## Commands npm create moddio@latest my-game -- --template arena # arena, soccer or legacy; with AGENTS.md npx moddio login --site https://www.modd.io # opens https://www.modd.io/cli/login to approve this computer npx moddio dev # the room on your machine, two browser windows as two players npx moddio test # bots, replays, and the sim in three JS engines npx moddio publish # build, check, test, upload, and print the play URL npx moddio publish --public # the same, and make the game playable by anyone with the link moddio.json may name the game: "game": "". Without it, publish creates a new game. ## What publish checks - sim.js may import only @moddio/sim; server.js only @moddio/sim and @moddio/server. Bundle the rest. - Neither may use require, eval, Function(), import() or import.meta. - server.js runs in the room's process, so it also may not use process, fetch, XMLHttpRequest, WebSocket, EventSource, importScripts, document, window, navigator, location or storage. - In sim.js those names, and Math.random, Date, performance, timers, Intl, crypto, WeakRef, FinalizationRegistry, SharedArrayBuffer, Atomics, toLocaleString and localeCompare, are warnings: the sim realm removes them, so code that reaches them throws. Fix the warnings in your own code. - Limits: 2000 files, 10 MB a file, 2 MB of code in sim.js plus 8 MB of inlined binary data (wasm as base64), 2 MB for server.js, 50 MB in all. - moddio.json: name (at most 30 characters), playersPerRoom 1-256, tickRate 1-120, products with id, name and price in coins. - Then an automatic review decides: publish, hold for a person, or reject. - Rooms already open keep the version they started with. New rooms get the new version. ## Where the game runs - client/ is served at the root of the game's own origin; assets/ at /assets/; sim.js at /sim.js. server.js is never sent to browsers. - The page is in