Game packages in three.js
Load a .jpkg game package exported from JAMI into your own three.js game with the open-source runtime @jami3d/three: loadPackage, a world, its look and your frame loop, in Vite or Next.js.
What a game package is
A game package is a scene made in JAMI and exported for a game you write yourself: one .jpkg file that holds the scene's worlds (or a kit as a prefab), its models at up to three levels of detail, its instances and terrain, its living bodies' behaviours, its colliders and navmesh, its sky, fog, wind, water and effects, and the credits a game must show. Your game loads it into its own three.js scene with @jami3d/three, an open-source runtime (MIT). Nothing in a package is fetched from JAMI: a game plays it offline, for as long as it is played.
| Who | What it does |
|---|---|
The runtime, @jami3d/three | Builds each world under world.root, draws its things in your scene, moves its living bodies and clips, sways its vegetation, animates its water, sky and effects, answers its ground, colliders and navmesh, and sends events when something happens. |
| Your game | Owns the renderer, the camera, the frame loop, input, the player, physics, the interface, sound output and saving. |
Making the package yourself? It is File › Export game package… in JAMI's Studio: see Exporting a package.
Get the runtime
npm install @jami3d/three three@0.186
npm install -D @types/three@0.186three is a peer of the runtime: your game's own three.js, one copy of it on the page (two copies are reported as three_duplicate). The runtime runs on three.js 0.180 to 0.186; 0.187 and later are not supported yet (the runtime says so as a peer warning at install). The second line is for a game written in TypeScript: the runtime ships its own types, and @types/three gives three's.
@jami3d/three is another package than jami3d, the SDK that embeds JAMI's player in a page, and each has versions of its own: see Versions.
A whole game with Vite
In a Vite project (its vanilla-ts template, or your own), put the package in public/ — here public/scene.jpkg, which Vite serves at /scene.jpkg — and give the page a canvas:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My game</title>
<style>
body { margin: 0; }
canvas { display: block; width: 100vw; height: 100vh; }
</style>
</head>
<body>
<canvas></canvas>
<script type="module" src="/src/main.ts"></script>
</body>
</html>Then the game itself, the smallest whole one:
import { isPackageError, loadPackage, type GamePackage } from "@jami3d/three";
import { PerspectiveCamera, Scene, WebGLRenderer } from "three";
// Yours, not the runtime's: it never makes a renderer and never moves your camera.
const canvas =
document.querySelector("canvas") ?? document.body.appendChild(document.createElement("canvas"));
const renderer = new WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true; // the package's lights cast shadows once you switch them on
const scene = new Scene();
const camera = new PerspectiveCamera(55, 1, 0.1, 500);
camera.position.set(0, 8, 24);
camera.lookAt(0, 0, 0);
function resize(): void {
renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
camera.aspect = canvas.clientWidth / Math.max(1, canvas.clientHeight);
camera.updateProjectionMatrix();
}
resize();
addEventListener("resize", resize);
const loading = new AbortController();
let pkg: GamePackage | undefined;
async function start(): Promise<void> {
const loaded = await loadPackage("/scene.jpkg", { renderer, signal: loading.signal });
if (loading.signal.aborted) return loaded.dispose(); // stopped while it loaded
pkg = loaded;
const world = await pkg.createWorld(); // the package's first world
world.on("degraded", (report) => console.warn(report.reason, report.detail));
scene.add(world.root);
world.applyLook({ renderer, scene }); // its tone mapping, exposure and sky light
let last = performance.now();
renderer.setAnimationLoop((now: number) => {
// Seconds since the last frame: never negative, at most 0.1 after a pause.
world.update(Math.min(0.1, Math.max(0, now - last) / 1000), camera);
last = now;
renderer.render(scene, camera);
});
}
/** Stops the game and gives its memory back: leaving for a menu, or a hot reload. */
function stop(): void {
loading.abort();
renderer.setAnimationLoop(null);
removeEventListener("resize", resize);
pkg?.dispose(); // every world made from it, and its models' GPU memory
renderer.dispose();
}
start().catch((error: unknown) => {
if (loading.signal.aborted) return;
if (!isPackageError(error)) throw error;
const file = error.path === undefined ? "" : ` (${error.path})`; // the package's file at fault
console.error(`The package did not load: ${error.code}${file}`);
});
import.meta.hot?.dispose(stop);- The renderer, the scene and the camera are yours. Switch
shadowMap.enabledon to draw the shadows the package's lights cast. The camera stands 24 m back and 8 m up, looking at the world's origin, and never moves: your game adds its own controls, or three'sOrbitControlswhile you look round a package. loadPackagereads the package's directory and manifest;pkg.createWorld()builds its first world, orcreateWorld(key)another ofpkg.worlds. Addworld.rootto your scene.world.applyLook({ renderer, scene })sets your renderer's tone mapping and exposure to the package's look and, when the world has a sky, puts the sky's light on your scene (scene.environment).world.update(dt, camera)moves the world's time on bydtseconds every frame, and uses your camera to choose levels of detail. Hand it seconds, never a negative step.- Listen right after
createWorld: what a world reports while it is built (degraded) comes at your firstupdate. pkg.dispose()releases every world made from the package and its models' GPU memory;world.dispose()releases one world.- A load that fails throws a
PackageError:isPackageError(error)tells one, anderror.codesays why. See When a package does not play.
Start Vite's dev server and open the page: the package's world stands in your canvas and moves on its own time — its living bodies walk, its water and sky move. Then put your player in it (Colliders, physics and navigation) and drive it (The game runtime's API).
A package draws with the lights and the sky its scene had, and no others. A scene made with neither draws black in your game, with no error (world.stats().scenery.sky is false): add a light of your own.
import { HemisphereLight } from "three";
// For a package whose scene had no light and no sky: a light of your game's own.
scene.add(new HemisphereLight(0xffffff, 0x445566, 2.5));The same in Next.js
The runtime needs a browser: WebGL to draw and fetch to read. With the App Router, make the game a client component ("use client") and do everything in an effect, which runs only in the browser, never while the server renders. Put the package in public/, as with Vite.
"use client";
import { isPackageError, loadPackage, type GamePackage } from "@jami3d/three";
import { useEffect, useRef } from "react";
import { PerspectiveCamera, Scene, WebGLRenderer } from "three";
/** The game, in the browser only: everything runs in the effect, never while the server renders. */
export default function GameView({ src }: { src: string }) {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (canvas === null) return;
const renderer = new WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
const scene = new Scene();
const camera = new PerspectiveCamera(55, 1, 0.1, 500);
camera.position.set(0, 8, 24);
camera.lookAt(0, 0, 0);
const resize = new ResizeObserver(() => {
renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
camera.aspect = canvas.clientWidth / Math.max(1, canvas.clientHeight);
camera.updateProjectionMatrix();
});
resize.observe(canvas);
const loading = new AbortController();
let pkg: GamePackage | undefined;
const start = async (): Promise<void> => {
const loaded = await loadPackage(src, { renderer, signal: loading.signal });
if (loading.signal.aborted) return loaded.dispose(); // unmounted while it loaded
pkg = loaded;
const world = await pkg.createWorld();
world.on("degraded", (report) => console.warn(report.reason, report.detail));
scene.add(world.root);
world.applyLook({ renderer, scene });
let last = performance.now();
renderer.setAnimationLoop((now: number) => {
world.update(Math.min(0.1, Math.max(0, now - last) / 1000), camera);
last = now;
renderer.render(scene, camera);
});
};
start().catch((error: unknown) => {
if (loading.signal.aborted) return;
if (isPackageError(error)) console.error(`The package did not load: ${error.code}`);
else throw error;
});
// Unmounting (and React's second mount in development) stops it and gives its memory back.
return () => {
loading.abort();
renderer.setAnimationLoop(null);
resize.disconnect();
pkg?.dispose();
renderer.dispose();
};
}, [src]);
return <canvas ref={canvasRef} style={{ display: "block", width: "100%", height: "100vh" }} />;
}import GameView from "./game-view";
/** /game: a server component that renders the client component (public/scene.jpkg). */
export default function GamePage() {
return <GameView src="/scene.jpkg" />;
}The effect's cleanup stops the loop and disposes the package when the component unmounts. In development React mounts a component twice: the first mount's load is aborted (signal) and its package disposed, so nothing is left behind.
The runtime touches no browser object as it is imported, so the server may import the component while it renders the page. If your game's own modules do touch window or document as they are imported, load the component with next/dynamic and ssr: false, from another client component.
Where the package comes from
loadPackage takes:
- a URL of the
.jpkgfile. The runtime reads it by byte ranges — the archive's end, its directory, its manifest, then each file when a world needs it — where the server answers ranges, and otherwise fetches it whole, once; - a URL ending in
/: the package unpacked into a folder, each file fetched by its path; - bytes your game already holds: an
ArrayBuffer, a typed array, or aBlob, such as aFilea player picked.
import { loadPackage } from "@jami3d/three";
// A URL: read by byte ranges where the server answers them, else fetched whole, once.
const fromCdn = await loadPackage("https://cdn.example.com/games/scene.jpkg", { renderer });
// A URL that ends in "/": the package unpacked into a folder, each file fetched by its path.
const fromFolder = await loadPackage("/games/scene/", { renderer });
// Bytes you hold: an ArrayBuffer, a typed array or a Blob, such as a File the player picked.
const picked = document.querySelector<HTMLInputElement>("input[type=file]")?.files?.[0];
const fromDisk = picked === undefined ? null : await loadPackage(picked, { renderer });
// Your own fetch receives the runtime's request options and may change them. Spreading ...init
// keeps a ranged read's cache: "no-store" (Chrome and Edge refuse concurrent cached range reads).
const signedIn = await loadPackage("https://api.example.com/packages/scene.jpkg", {
renderer,
fetch: (url, init) => fetch(url, { ...init, credentials: "include" }),
onProgress: ({ loaded, total }) => console.log(`${loaded} of ${total || "?"} bytes`),
});Its options: renderer (read for its limits and its kind, never driven), quality (see Tiers), signal (stops the load: aborted), onProgress, sha256 (holds every file to its SHA-256), ktx2 (see KTX2 pictures) and fetch. Nothing a package names is ever fetched: a model that names an outside file is refused as corrupt.
Your own fetch replaces the browser's, for credentials or headers of your own. It receives the request options the runtime would hand the browser's, and may change them. A ranged read asks cache: "no-store", because Chrome and Edge refuse concurrent range reads of one cached file; a fetch that spreads ...init, as the sample does, keeps it.
Serving it from another origin. A page on another origin than the package reads it only when the server answers with these headers (CORS):
Access-Control-Allow-Origin: your page's origin (or*). Without it the browser hands your page nothing.Access-Control-Allow-Headers: Range, in the answer to a preflight (OPTIONS) request, for a browser that sends one before a cross-origin ranged read. A request for a single byte range is CORS-safelisted, so Chrome sends none; allow it for the others.Access-Control-Expose-Headers: Content-Range. It lets the runtime read which bytes came back and how large the file is; without it the runtime fetches the whole file, once.
For a bucket with an S3-compatible API (Amazon S3, Cloudflare R2, MinIO), one CORS rule:
{
"CORSRules": [
{
"AllowedOrigins": ["https://game.example.com"],
"AllowedMethods": ["GET", "HEAD"],
"AllowedHeaders": ["range"],
"ExposeHeaders": ["Content-Range"],
"MaxAgeSeconds": 86400
}
]
}A plain static server or CDN: switch CORS on for your page's origin, allow the Range request header and expose Content-Range. Most already answer byte ranges (206 Partial Content); from one that does not, the runtime fetches the file whole.
Tiers
A package carries up to three tiers, high, medium and low: its models' levels of detail and its pictures' sizes (at most 4,096, 2,048 or 1,024 pixels on a side). Colliders, navigation, behaviours and controls are the same in every tier.
With quality: "auto", the default, the runtime picks by your renderer's largest texture (4,096 or more: high; 2,048: medium; else low), then the best tier at or below it that the package carries; pkg.tier says which. Pass quality: "low" to loadPackage for a lighter game, createWorld(key, { quality }) for one world, or call world.setQuality(tier) later.
What to read next
- The game runtime's API: entities by key, clips, params, actions and events, host targets, instances, time and snapshots, prefabs, ambient sound and credits.
- Colliders, physics and navigation: the package's colliders in Rapier, a walking player, the ground's height and the navmesh.
- Reference and troubleshooting: sizes and limits, error codes, what “degraded” means, versions and the compatibility promise, licences, bundlers, exporting a package, and what to do when a package does not play.