# The skill's reference files: plain three.js, React Three Fiber and Rapier
https://paprika3d.com/docs/templates

The `threejs-game` skill's reference files: the shape it follows when it writes a game, each a small game in the form the [convention](https://paprika3d.com/docs/convention) describes. They ship inside the plugin for the agent to read; there is nothing to copy or install.
## plain.html

One page, an import map and no build step. Arrow keys move a box over a ground in x and z, with the camera above and behind; touching the coin scores and moves it. fx.js `stage()` sets up tone mapping, lighting, shadows and resizing, so its first look flags nothing. The state lives in plain variables, `step(dt)` runs once per frame, keys and `act()` share one input path, and `window.__game` is set at the end.

```html
<!doctype html>
<!-- Plain three.js template: one page, no build. Arrow keys move a box over the ground; touching the coin scores and moves the coin.
     Needs `bun add three` (the import map points into node_modules); the `open` tool puts geo.js (shapes) and fx.js (stage, sound,
     particles) in the project, so open it with `open { cwd: <this folder's absolute path>, url: "index.html" }`. Replace the rules, keep the shape:
     state in plain variables, step(dt) once per frame, one input path for keys and act(), window.__game at the end. -->
<html><head><meta charset="utf-8"><title>Game</title>
<style>html,body{margin:0;background:#1a2030;overflow:hidden}</style></head>
<body>
<div id="hud" style="position:fixed;top:12px;left:16px;color:#fff;font:600 20px system-ui;pointer-events:none">Score 0</div>
<!-- Rapier: add "@dimforge/rapier3d-compat":"./node_modules/@dimforge/rapier3d-compat/dist/rapier.mjs" to imports, then import RAPIER from '@dimforge/rapier3d-compat'; await RAPIER.init(); -->
<script type="importmap">{"imports":{"three":"./node_modules/three/build/three.module.js","three/addons/":"./node_modules/three/examples/jsm/"}}</script>
<script type="module">
import * as THREE from 'three';
import { geo } from './geo.js';
import { stage, tex, sfx, burst } from './fx.js';

const SPEED = 4;                       // units per second
const EDGE = { x: 7.5, z: 5.5 };       // the play area; the ground runs well past it, so its edge never shows
const clamp = (v, e) => Math.max(-e, Math.min(e, v));
const held = new Set();
const hud = document.getElementById('hud');
let score = 0;
let player = { x: 0, z: 0 }, coin = { x: 2, z: -2 };

function step(dt) {
  const dx = (held.has('ArrowRight') ? 1 : 0) - (held.has('ArrowLeft') ? 1 : 0);
  const dz = (held.has('ArrowDown') ? 1 : 0) - (held.has('ArrowUp') ? 1 : 0);   // ArrowUp is away from the camera, -z
  const len = Math.hypot(dx, dz) || 1;   // a diagonal at SPEED too, not 1.41x
  player.x += dx / len * SPEED * dt; player.z += dz / len * SPEED * dt;
  player.x = clamp(player.x, EDGE.x); player.z = clamp(player.z, EDGE.z);
  if (Math.hypot(player.x - coin.x, player.z - coin.z) < 0.8) {
    score++; hud.textContent = `Score ${score}`;
    sfx.play('coin');                  // a synthesized sound, no file
    sparks.emit(new THREE.Vector3(coin.x, 1.1, coin.z), { count: 24, speed: 3, spread: Math.PI / 2, color: 0xffe14d });   // above the player's box, where the chase camera sees it
    // the next coin 1.5 to 3 units ahead of the player (away from the camera), so it stays in view; Math.random: the harness seeds it
    coin = { x: clamp(player.x + Math.random() * 4 - 2, EDGE.x), z: clamp(player.z - 1.5 - Math.random() * 1.5, EDGE.z) };
  }
}

// stage(): tone mapping, sRGB output, a studio environment, a key light with a shadow and a resize handler, in one call
const { renderer, scene, camera, fit } = stage(document.body, { background: 0x1a2030, ground: false, key: 3 });
scene.environmentIntensity = 0.4;      // the studio light at full strength washes out the key light's shadows
const mat = (color) => new THREE.MeshStandardMaterial({ color });
const grass = tex.noise({ colors: [0x1f5a2e, 0x5a9a4a], scale: 16, seed: 2 }); grass.repeat.set(10, 8);   // seeded canvas texture, tagged sRGB
const ground = new THREE.Mesh(new THREE.PlaneGeometry(40, 32).rotateX(-Math.PI / 2), new THREE.MeshStandardMaterial({ map: grass }));
ground.name = 'ground'; ground.receiveShadow = true; scene.add(ground);
const box = new THREE.Mesh(new THREE.BoxGeometry(0.8, 0.8, 0.8), mat(0xffa040));
box.name = 'player'; box.castShadow = true; scene.add(box);   // names show in `look`'s on-screen list
const { boolean } = await geo();       // Manifold booleans, hull, extrude, revolve: a coin with a hole cut through it
const disc = (r, h) => new THREE.CylinderGeometry(r, r, h, 32).rotateX(Math.PI / 2);
const gem = new THREE.Mesh(boolean('difference', disc(0.35, 0.08), disc(0.12, 0.2)), mat(0xffe14d));
gem.name = 'coin'; gem.castShadow = true; scene.add(gem);
const sparks = burst({ max: 100, seed: 1, size: 0.08 }); sparks.name = 'sparks';   // staged: added after the first frame
// Load time: the first frame draws only what play needs, on materials that compile fast. Every effect that compiles its own
// shader (scan or PBR materials, a noise sky, shadows, foliage(), water(), GPU particles or simulation, post()) joins after
// it, one effect to a compileAsync batch (one batch of everything held a game's water back 545 s on a software renderer).
// Play never waits on it: no await before the loop or window.__game, and no __clock.hold (compileAsync needs frames to finish).
const later = [sparks];                // one entry per batch, in the order a player should see them: e.g. sky, sea, grass, post
async function stageIn() {
  // WebGL without KHR_parallel_shader_compile (software renderers) compiles either way; compile() skips three's warning
  const parallel = renderer.extensions?.has('KHR_parallel_shader_compile') ?? true;
  for (const effect of later) {
    if (parallel) await renderer.compileAsync(effect, camera, scene); else renderer.compile(effect, camera, scene);
    scene.add(effect);
  }
}
fit(new THREE.Box3(new THREE.Vector3(-EDGE.x, 0, -EDGE.z), new THREE.Vector3(EDGE.x, 1, EDGE.z)));   // the key light's shadow over the play area

let last = null, staged = null;
function loop(now) {
  requestAnimationFrame(loop);
  // elapsed game time, never more than 0.1 s a frame; the first frame counts as one (time before it was the page loading)
  const dt = last === null ? 1 / 60 : Math.min((now - last) / 1000, 0.1);
  step(dt);
  sparks.update(dt);
  last = now;
  box.position.set(player.x, 0.4, player.z);
  gem.position.set(coin.x, 0.4, coin.z);
  // above and behind the player, further back on a portrait screen: the view's width is what keeps the coin in it
  const d = 4.5 / Math.min(1, camera.aspect);
  camera.position.set(player.x, d, player.z + d); camera.lookAt(box.position);
  renderer.render(scene, camera);
  staged ??= stageIn();                // once, after the first frame has drawn
}
requestAnimationFrame(loop);

// One input path for real keys and the harness's act().
const act = ({ key, down = true }) => { if (down) held.add(key); else held.delete(key); };
addEventListener('keydown', e => act({ key: e.code }));
addEventListener('keyup', e => act({ key: e.code, down: false }));
addEventListener('blur', () => held.clear());   // a key let go in another window never sends keyup here

const copy = (p) => ({ x: +p.x.toFixed(3), z: +p.z.toFixed(3) });
window.__game = {
  subject: 'player',                   // the object `look` and `interact`'s Motion line follow
  describe: () => ({ name: 'coin collector', units: 'world units, y up, the player moves in x and z', keys: { ArrowLeft: 'hold to move left', ArrowRight: 'hold to move right', ArrowUp: 'hold to move away (-z)', ArrowDown: 'hold to move nearer (+z)' } }),
  observe: () => ({ score, player: copy(player), coin: copy(coin) }),
  act,
  setState: (s) => {   // every schema key, applied at once
    if (s.score !== undefined) { score = s.score; hud.textContent = `Score ${score}`; }
    if (s.player) player = { ...player, ...s.player };
    if (s.coin) coin = { ...coin, ...s.coin };
  },
};
</script>
</body></html>
```

## r3f.tsx

React Three Fiber under vite. The game state lives in a plain module object outside React, so `setState` and `observe()` never wait for a render; components only draw it. One `useFrame` advances the rules by the frame's delta, at most 0.1 s, and `window.__game` is set in the Canvas's `onCreated`.

```tsx
// React Three Fiber template (vite: `bun create vite . --template react-ts`, then `bun add three @react-three/fiber`).
// The game state lives in a plain module object outside React, so setState and observe() never wait for a render;
// components only draw it. One useFrame advances the rules by the frame's delta, at most 0.1 s, and the first frame by
// one frame.
// Replace the rules, keep the shape.
import { useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { Canvas, useFrame } from '@react-three/fiber';
import type { Mesh } from 'three';

type Vec = { x: number; y: number };
const SPEED = 4;   // units per second
const game = { score: 0, player: { x: 0, y: 0 } as Vec, coin: { x: 3, y: 2 } as Vec };
const held = new Set<string>();
let started = false;

function step(dt: number) {
  const p = game.player;
  p.x += ((held.has('ArrowRight') ? 1 : 0) - (held.has('ArrowLeft') ? 1 : 0)) * SPEED * dt;
  p.y += ((held.has('ArrowUp') ? 1 : 0) - (held.has('ArrowDown') ? 1 : 0)) * SPEED * dt;
  if (Math.hypot(p.x - game.coin.x, p.y - game.coin.y) < 0.8) {
    game.score++;
    game.coin = { x: Math.round(Math.random() * 8 - 4), y: Math.round(Math.random() * 6 - 3) };   // the harness seeds Math.random
  }
}

// One input path for real keys and the harness's act().
const act = ({ key, down = true }: { key: string; down?: boolean }) => { if (down) held.add(key); else held.delete(key); };
addEventListener('keydown', e => act({ key: e.code }));
addEventListener('keyup', e => act({ key: e.code, down: false }));

const copy = (v: Vec) => ({ x: +v.x.toFixed(3), y: +v.y.toFixed(3) });
// Installed from the Canvas's onCreated, not here: the harness starts stepping frames once __game exists, and before
// the Canvas has mounted those frames would draw nothing and run no useFrame.
const bridge = {
  subject: 'player',   // the mesh named 'player' below, which `look` and `interact`'s Motion line follow
  describe: () => ({ name: 'coin collector', stack: 'react-three-fiber', keys: { ArrowLeft: 'hold', ArrowRight: 'hold', ArrowUp: 'hold', ArrowDown: 'hold' } }),
  observe: () => ({ score: game.score, player: copy(game.player), coin: copy(game.coin) }),
  act,
  setState: (s: Partial<typeof game>) => {   // every schema key, applied at once
    if (s.score !== undefined) game.score = s.score;
    if (s.player) game.player = { ...game.player, ...s.player };   // fields left out keep their values
    if (s.coin) game.coin = { ...game.coin, ...s.coin };
  },
};

function Scene() {
  const player = useRef<Mesh>(null), coin = useRef<Mesh>(null);
  useFrame((_, delta) => {
    step(started ? Math.min(delta, 0.1) : 1 / 60);   // the first delta also spans the page's load: count it as one frame
    started = true;
    player.current!.position.set(game.player.x, game.player.y, 0);
    coin.current!.position.set(game.coin.x, game.coin.y, 0);
  });
  return (
    <>
      <hemisphereLight args={['#ffffff', '#334455', 2]} />
      {/* names show in `look`'s on-screen list */}
      <mesh ref={player} name="player"><boxGeometry args={[0.8, 0.8, 0.8]} /><meshStandardMaterial color="orange" /></mesh>
      <mesh ref={coin} name="coin"><sphereGeometry args={[0.3]} /><meshStandardMaterial color="gold" /></mesh>
    </>
  );
}

createRoot(document.getElementById('root')!).render(
  <Canvas camera={{ position: [0, 0, 12], fov: 50 }} onCreated={() => { (window as any).__game = bridge; }}><Scene /></Canvas>,
);
```

## rapier.ts

The `window.__game` bridge for a game whose bodies live in a Rapier world, with `@react-three/rapier` or plain `@dimforge/rapier3d-compat`. `observe()` reads positions from the bodies, rounded so a check's exact values are stable; `setState` teleports a body and stops it unless the state gives its velocity.

```ts
// Rapier template: the window.__game bridge for a game whose bodies live in a Rapier world, with
// @react-three/rapier (`installGame(useRapier().world, ...)` in an effect) or plain @dimforge/rapier3d-compat.
// observe() reads positions from the bodies, rounded so exact values are stable; setState teleports a body
// and stops it unless the state gives its velocity, so a set state starts at rest by default. Keep the physics step fixed at 1/60 s (@react-three/rapier's default
// timeStep) so stepped frames are exact. Replace the rules, keep the shape.
// With world.createCharacterController(offset) instead of a dynamic player: the controller applies no
// gravity and does not carry the player on a moving platform. Move a platform by position (setNextKinematicTranslation on
// a kinematicPositionBased body) and add its move this step to the player's wanted move once; a platform moved by
// velocity carried a player about 1.4x its move, so measure the ride with `interact`. A capsule resting at
// exactly the offset can get zero movement back with collisions listed: lift it a hair (offset / 4) and compute the
// horizontal and vertical moves in two computeColliderMovement calls.
import type { RigidBody, World } from '@dimforge/rapier3d-compat';

type Vec = { x: number; y: number; z: number };
const SPEED = 4, JUMP = 7;   // units per second
const held = new Set<string>();
let jump = false, score = 0;
const round = (v: Vec) => ({ x: +v.x.toFixed(2), y: +v.y.toFixed(2), z: +v.z.toFixed(2) });

/** One input path for real keys and the harness's act(); Space jumps once per press. */
export function act({ key, down = true }: { key: string; down?: boolean }) {
  const k = key === ' ' ? 'Space' : key;
  if (k === 'Space' && down && !held.has(k)) jump = true;
  if (down) held.add(k); else held.delete(k);
}

/** Call once per physics step, before the world steps: held keys set the player's velocity. */
export function tick(player: RigidBody) {
  const vx = ((held.has('ArrowRight') ? 1 : 0) - (held.has('ArrowLeft') ? 1 : 0)) * SPEED;
  // shortcut: "grounded" is a near-zero vertical speed, so a press at the top of an arc still jumps; cast a ray down for a real ground check
  const grounded = Math.abs(player.linvel().y) < 0.05;
  player.setLinvel({ x: vx, y: jump && grounded ? JUMP : player.linvel().y, z: 0 }, true);
  jump = false;
}

/** Installs window.__game and the key listeners for the named bodies; returns the cleanup. */
export function installGame(world: World, bodies: { player: RigidBody }) {
  const down = (e: KeyboardEvent) => act({ key: e.code });
  const up = (e: KeyboardEvent) => act({ key: e.code, down: false });
  addEventListener('keydown', down);
  addEventListener('keyup', up);
  (window as any).__game = {
    subject: 'player',   // the mesh `look` and `interact`'s Motion line follow: name the player's mesh 'player'
    describe: () => ({ name: 'platformer', stack: 'rapier', units: 'metres, y up', keys: { ArrowLeft: 'hold', ArrowRight: 'hold', Space: 'jump' } }),
    observe: () => ({ score, bodies: world.bodies.len(), player: round(bodies.player.translation()), velocity: round(bodies.player.linvel()) }),
    act,
    setState: (s: { score?: number; player?: Vec; velocity?: Vec }) => {   // every schema key but bodies (a count), applied at once
      if (s.score !== undefined) score = s.score;
      if (s.player) bodies.player.setTranslation({ ...bodies.player.translation(), ...s.player }, true);   // fields left out keep their values
      if (s.player) world.propagateModifiedBodyPositionsToColliders();   // a character controller's next query sees the collider at its new place
      if (s.player || s.velocity) bodies.player.setLinvel(s.velocity ?? { x: 0, y: 0, z: 0 }, true);
    },
  };
  return () => { removeEventListener('keydown', down); removeEventListener('keyup', up); delete (window as any).__game; };
}
```

Updated 2026-11-14.
