# Plain HTML5, Three.js and PixiJS

Rendering libraries need no wrapper and there is no plugin folder for them in `packages/sdk-engines`: the browser SDK (`window.ZokoGames.SDK`) is already the integration. What you add is a few lines that connect it to your render loop and audio. The same pattern works for Three.js, PixiJS, Babylon.js, p5.js, Kaboom and a bare `<canvas>`. For Phaser use the [Phaser page](https://docs.zokogames.com/engines/phaser), which has a plugin. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Which path

| You have | Start from |
| --- | --- |
| A finished game in plain JavaScript, no build step | The `html5-minimal` [starter kit](https://docs.zokogames.com/getting-started/starter-kits): one `index.html`, every SDK call commented. Copy the calls you need. |
| A bundled TypeScript game (Vite, Webpack, esbuild) | The `html5-vite-ts` starter kit: `src/zoko-sdk.d.ts` (types for `window.ZokoGames.SDK`) and `src/zoko.ts` (a safe wrapper). |
| Three.js, PixiJS, Babylon.js or similar | This page: the adapter, then the tab for your library. |

## 1. Load the SDK first

Put the script before your bundle so `window.ZokoGames` exists when your code runs. Keep the exact URL: the upload validator looks for it, and a bundled copy is flagged (`sdk_bundled`).

```html
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
<script type="module" src="./main.js"></script>
```

With a bundler, set the public base to a relative path (`base: "./"` in Vite) so every asset URL is relative. See [technical requirements](https://docs.zokogames.com/requirements/technical#relative-paths-only).

## 2. A small adapter

Wrap the SDK once so the game also runs when the SDK is missing or `disabled`, and so one failing call never breaks a frame. `SDK.init()` never rejects; when the environment is `disabled`, every other call throws `sdkDisabled`, which the adapter swallows.

```js
const SDK = window.ZokoGames?.SDK;           // undefined when the script was blocked
let online = false;

export async function startPlatform() {
  if (!SDK) return;
  await SDK.init();
  online = SDK.environment !== "disabled";   // "local", "zokogames" or "disabled"
}

export function call(fn, fallback = null) {
  if (!online) return Promise.resolve(fallback);
  return Promise.resolve().then(fn).catch((e) => { console.warn("sdk", e.code); return fallback; });
}
```

## 3. A complete working example (plain canvas)

This covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, a leaderboard score, settings and audio unlock. Library-specific pause code follows in section 4.

```js
let running = false, inAd = false;
let audioCtx;                                   // created on the first input (audio unlock)

function setMuted(m) { if (m) audioCtx?.suspend(); else audioCtx?.resume(); }   // the portal's mute, applied to your audio

function unlockAudio() {
  audioCtx ??= new AudioContext();
  setMuted(online && SDK.game.settings.muteAudio);   // resumes the context unless the portal has muted the game
  removeEventListener("pointerdown", unlockAudio);
  removeEventListener("keydown", unlockAudio);
}
addEventListener("pointerdown", unlockAudio);   // browsers keep audio suspended until a gesture
addEventListener("keydown", unlockAudio);

// Pause on adStarted; resume on adFinished AND adError. Resolves true only when the ad finished.
function showAd(type) {
  if (!online) return Promise.resolve(false);
  let finished = false;
  let wasRunning = false;
  const pause = () => { inAd = true; wasRunning = running; running = false; audioCtx?.suspend(); };
  const resume = () => {
    if (!inAd) return;
    inAd = false; running = wasRunning;   // a midgame ad at game over must not restart the loop
    if (!SDK.game.settings.muteAudio) audioCtx?.resume();
  };
  return SDK.ad.requestAd(type, {
    adStarted: pause,
    adFinished: () => { finished = true; resume(); },
    adError: (e) => { console.log("no ad:", e.code); resume(); },   // adCooldown, unfilled, adblock ...
  }).then(() => finished, () => { resume(); return false; });       // throws (for example sdkDisabled) instead of adError
}

async function boot() {
  await startPlatform();
  if (online) {
    await call(() => SDK.game.loadingStart());
    state.best = Number(SDK.data.getItem("best") ?? "0") || 0;      // load: synchronous after init
    await loadAssets();
    await call(() => SDK.game.loadingStop());
    SDK.game.addSettingsChangeListener((s) => { if (!inAd) setMuted(s.muteAudio); });   // an ad in progress keeps the sound off
  } else {
    await loadAssets();
  }
  showMenu();
}

function startRound() {                          // the player takes control: now, not at page load
  running = true;
  call(() => SDK.game.gameplayStart());
}

async function endRound(score) {
  running = false;
  call(() => SDK.game.gameplayStop());
  if (score > state.best) {                      // save
    state.best = score;
    try { if (online) SDK.data.setItem("best", String(score)); } catch (e) { console.warn(e.code); }  // dataLimitExceeded
  }
  await submitScore(score);                      // leaderboard
  await showAd("midgame");                       // natural break; then show the results screen
  showResults(score);
}

async function onRewardButton() {
  if (await showAd("rewarded")) grantReward();   // reward only after adFinished
}

addEventListener("visibilitychange", () => {     // a hidden tab is not play time
  if (document.hidden && running) call(() => SDK.game.gameplayStop());
  else if (!document.hidden && running) call(() => SDK.game.gameplayStart());
});
```

The leaderboard call. Only signed-in players are ranked; a score that breaks a board rule is dropped silently while the call still resolves. The `encryptScore` helper is on the [leaderboards page](https://docs.zokogames.com/sdk/leaderboards#client-submission); without an encryption key on the board, pass an empty string.

```js
async function submitScore(score) {
  const user = await call(() => SDK.user.getUser());
  if (!user) return;                             // guests are not ranked
  const encryptedScore = BOARD_KEY
    ? await encryptScore(score, BOARD_KEY, user.__dangerousUserId, GAME_ID)   // fresh payload per submit
    : "";
  await call(() => SDK.user.submitScore({ encryptedScore, score }));
}
```

## 4. Pause, mute and resume by library

<!-- search: headings-only -->

Pause what you own: the render loop, your clock, physics and audio. The loop must keep running only if it is a cheap "paused" screen. The `showAd` helper above works for any library once `pause` and `resume` call your library's own switches.

:::tabs
== Three.js
```js
import * as THREE from "three";

const renderer = new THREE.WebGLRenderer({ canvas });
const timer = new THREE.Timer();                // THREE.Clock is deprecated since r183 and logs a warning
let paused = false;

renderer.setAnimationLoop(() => {
  if (paused) return;
  timer.update();
  const dt = Math.min(timer.getDelta(), 0.1);   // clamp so a long pause does not teleport anything
  world.update(dt);
  renderer.render(scene, camera);
});

function setLibMuted(m) { listener.setMasterVolume(m ? 0 : 1); }
function setPaused(p) {
  paused = p;
  if (!p) timer.reset();                        // drop the time spent paused
  setLibMuted(p || (online && SDK.game.settings.muteAudio)); // keep the portal's mute
}
// In showAd: call setPaused(true) in pause and setPaused(false) in resume. In setMuted (section 3): add setLibMuted(m).
```
== PixiJS
```js
import { Application } from "pixi.js";
import { sound } from "@pixi/sound";            // PixiJS's audio library; it has its own AudioContext

const app = new Application();
await app.init({ resizeTo: window, resolution: Math.min(devicePixelRatio, 2), autoDensity: true });
document.body.append(app.canvas);

function setLibMuted(m) { if (m) sound.muteAll(); else sound.unmuteAll(); }
function setPaused(p) {
  app.ticker[p ? "stop" : "start"]();
  if (p) sound.pauseAll(); else sound.resumeAll();
  setLibMuted(p || (online && SDK.game.settings.muteAudio)); // keep the portal's mute
}
// In showAd: call setPaused(true) in pause and setPaused(false) in resume. In setMuted (section 3): add setLibMuted(m).
```
== Babylon.js
```js
import { Engine, Scene, CreateAudioEngineAsync } from "@babylonjs/core";

const engine = new Engine(canvas, true);
const scene = new Scene(engine);
const audio = await CreateAudioEngineAsync();   // the audio engine unlocks itself on the first input
let paused = false;

// Keep the loop registered while paused: Babylon measures frame time inside it, so a stopped loop
// would hand the scene one huge delta on resume (animations and physics jump).
engine.runRenderLoop(() => { if (!paused) scene.render(); });

function setLibMuted(m) { audio.volume = m ? 0 : 1; }
function setPaused(p) {
  paused = p;
  if (p) audio.pauseAsync(); else audio.resumeAsync();
  setLibMuted(p || (online && SDK.game.settings.muteAudio));   // keep the portal's mute
}
// In showAd: call setPaused(true) in pause and setPaused(false) in resume. In setMuted (section 3): add setLibMuted(m).
```
== Plain canvas
```js
let last = 0;
function frame(t) {
  if (running) {
    update(Math.min((t - last) / 1000, 0.1));
    draw();
  }
  last = t;
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
// showAd above already flips `running` and suspends the AudioContext.
```
:::

## Multiplayer, achievements and purchases

These need no adapter. Call `SDK.game.room` (the room data channel, SDK 1.3.0; `undefined` on older SDKs), `SDK.achievements` and `SDK.store` directly, behind the same `call` helper. See the [game module](https://docs.zokogames.com/sdk/game#room-data-channel), [achievements](https://docs.zokogames.com/sdk/achievements) and [in-game purchases](https://docs.zokogames.com/sdk/purchases).

## 5. Sizing

The game lives in a frame of unknown size that changes with fullscreen and rotation. Size the canvas from the window, not from constants:

```js
function resize() {
  const mobile = online && SDK.user.systemInfo.device.type === "mobile";
  const dpr = Math.min(window.devicePixelRatio, mobile ? 1 : 2);
  renderer.setPixelRatio(dpr);              // Three.js; PixiJS uses the `resolution` option
  renderer.setSize(innerWidth, innerHeight, false);
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
}
addEventListener("resize", resize);
resize();
```

Read `SDK.user.systemInfo` only after `init()` and only when the SDK is not disabled (it throws otherwise). Capping `devicePixelRatio` at 1 on phones avoids running out of memory; details are in [optimisation tips](https://docs.zokogames.com/guides/optimisation) and the [mobile guide](https://docs.zokogames.com/guides/mobile).

## Export settings that matter on the web

- **Relative paths only**, and `index.html` at the archive root.
- **Ship plain files.** Your page requests plain names, so do not rename assets to `.br` or `.gz`. The game origin serves a `.br` or `.gz` suffix with the matching `Content-Encoding`, but it works only for requests of those exact names. The initial-download estimate uses uncompressed sizes: minify, tree-shake, and use WebP or Basis/KTX2 textures. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile). See [first frame fast](https://docs.zokogames.com/guides/first-frame).
- **Audio unlock.** Create or resume your `AudioContext` from a pointer or key event, as above; resume it again after an ad, and honour `SDK.game.settings.muteAudio`.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame). The frame permits fullscreen, so `canvas.requestFullscreen()` works from an input event, but it fullscreens only your canvas; do not add a competing button.
- **Memory.** Dispose textures and geometry when a level unloads (`texture.dispose()` in Three.js, `destroy()` in PixiJS). No threads or `SharedArrayBuffer` are available in the portal frame (it sends no cross-origin isolation headers), so avoid libraries that require them.

## Test locally

Serve the folder from `localhost` (any static server, for example `npx http-server . -p 8080`). The SDK then starts in its own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second overlay for each ad, fake players, a `localStorage` cloud save, a test store. Things to try:

- `?sdk_debug=true` logs every call; `?ad_response=unfilled` forces ad failure; `?user_response=logged_out` tests the guest path.
- A second midgame ad within three minutes fails with `adCooldown`: the real rule, so your game must handle it.
- `submitScore` is accepted and does nothing visible; the local token is unsigned.
- Open the game from `file://` or another host without `?useLocalSdk=true` to see the `disabled` path: the game must still play.

Then open the [Preview tool](https://www.zokogames.com/preview), enter your local address, and watch the requirements checklist tick.

## Checklist for library games

<!-- search: headings-only -->

- [ ] SDK script loaded before the game script and every path relative.
- [ ] Game runs when `SDK` is `undefined` or `SDK.environment` is `"disabled"`.
- [ ] Render loop, clock and audio pause on `adStarted` and resume on both `adFinished` and `adError`.
- [ ] Rewards granted only after `adFinished`.
- [ ] Time deltas are clamped so a long pause does not teleport anything.
- [ ] `SDK.game.settings.muteAudio` is applied at start and on change.
- [ ] `gameplayStart` at first player control, `gameplayStop` at game over, pause and tab hidden.
- [ ] Canvas resizes with the window and caps `devicePixelRatio`.
- [ ] Textures and geometry are disposed when a level unloads.
- [ ] Tested in the [Preview tool](https://www.zokogames.com/preview).

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).
