# DriftEngine manual
The manual of DriftEngine, as published at https://driftengine.dev/docs, one chapter after another, then the articles published at https://driftengine.dev/blog.
---
# Introduction
Getting started. https://driftengine.dev/docs/start/introduction
What DriftEngine is, what ships in it, how its packages divide, and where to start reading this manual.
DriftEngine is a 3D game engine written in strict TypeScript. It draws with WebGPU, and falls back
to WebGL2 when a browser can't give it a usable WebGPU device. Your game code doesn't change between
the two: you ask for a renderer, and the engine tells you which backend it got and why.
A game built on it ships as a web page. The same build can also be packaged as a desktop app for
Linux, Windows or macOS, or as an Android app, and it can run on a native window with no browser in
the process at all.
You write a game as a program. You create a renderer on a canvas, build or load meshes, step a
simulation on a fixed clock and draw frames. There is an editor, with a scene tree, an inspector and
a timeline you can scrub backwards, but nothing in the engine requires you to use it.
## What ships
**Rendering.** A forward renderer with clustered lighting, cascaded sun shadows, point and spot
lights with their own shadows, rectangular area lights, physically based materials, ambient
occlusion, bloom, colour grading and motion blur. On WebGPU there is more: a GPU-driven path that
culls instances and clusters on the device and draws them with one indirect call, DriftTR temporal
reconstruction, which renders below output resolution and resolves back up, DriftRay traced indirect
light, and DriftLight, which lets thousands of fixed lights reach a frame.
**Worlds.** Heightfield terrain whose levels of detail meet without cracks, worlds larger than
single precision can address, hierarchical detail for distant geometry, streaming that does its
work in slices of a frame, Gaussian splats, and DriftTexture, where a texture is a small compiled program over a
learned field instead of an image.
**Simulation.** A deterministic physics engine of its own: rigid bodies, seven kinds of joint, a
character controller, raycast vehicles, ragdolls, cloth and buoyancy. Skeletal animation with blend
trees, state machines, two-bone IK and retargeting. Navigation meshes, an entity component system,
and agents.
**Content.** Models import from glTF, OBJ, FBX, USD, STL, 3MF and Blender files, and bake into the
`.drft` container, which streams a coarse outline of a model while its geometry downloads. Audio has
a mix tree, positional sources, reverb zones, and a synthesised stand-in for every sound you haven't
recorded yet.
**Interaction.** Keyboard, mouse, touch and gamepads behind one action map. Cameras, including a
third-person rig that won't put its lens inside a wall. A 2D layer for sprites and interface, and
WebXR.
**Systems.** The simulation runs on a fixed step with seeded randomness, so a run can be replayed
exactly, and the networking is built on that: lockstep, and an authoritative host with prediction
and rollback. Video capture, saves, and DriftScript, a scripting language whose modules reload while
the game keeps running.
**Shipping.** Desktop and Android apps from one manifest, Steam cloud saves and achievements, and a
native host.
## Packages
Install what you use and nothing else. `@driftengine/core` is the runtime every game needs: the
loop, the renderer, input, cameras, the scene graph and geometry. It also re-exports the whole of
`@driftengine/physics`. Every other package is optional and takes core as a peer dependency, so
one you never install costs you nothing.
## The shape of the API
The engine takes positions, colours, sizes and time, and it doesn't know what your game is. You
won't find a player class to subclass or a level format to adopt: the rules, the world and the HUD
are yours. That makes the first program a little longer than in an engine that decides those things
for you, and it means you can replace any one piece when you outgrow it.
Three rules run through every page of this manual, and the examples follow all of them.
1. **Import only from a package's top level.** `@driftengine/core` is the public surface. Anything
you can't import from there is internal and can change without notice.
2. **Don't allocate in the frame.** Build meshes, nodes and buffers once, and rewrite them in place.
3. **Interpolate on `alpha`.** The simulation advances in fixed steps and the display doesn't, so
anything that moves is drawn between its last two states.
## Where to start
Read [Installation](https://driftengine.dev/docs/start/installation), then [Hello world](https://driftengine.dev/docs/start/hello-world), which puts a lit, turning
cube on the screen in about a hundred lines. [The loop](https://driftengine.dev/docs/start/the-loop) and
[Moving things](https://driftengine.dev/docs/start/moving-things) explain the two ideas every game here is built on, and
[Your first game](https://driftengine.dev/docs/start/first-game) puts them together into a complete game you can play in this page.
---
# Installation
Getting started. https://driftengine.dev/docs/start/installation
Add DriftEngine to a project, set up the page, TypeScript and DriftScript, pick a backend for testing, and know what the licence asks of you.
DriftEngine is published to npm as separate packages under the `@driftengine` scope. Every game
needs `@driftengine/core`; the rest you add when you reach for them.
```sh
npm install @driftengine/core
```
## What it needs
- **A browser with WebGL2**, which is every current desktop and mobile browser. The engine uses
WebGPU where the browser offers a device that can draw, and WebGL2 everywhere else.
- **Node 22.12 or newer** for your toolchain. Nothing in the engine runs in Node at play time; Node
is what builds and serves your game.
- **An ES module bundler.** The examples in this manual use Vite, and webpack 5 and Parcel work the
same way. The engine starts its workers with `new Worker(new URL('./worker.ts', import.meta.url))`,
which those three bundle without configuration.
## A new project
The quickest start is a project made for the engine, ready to run:
```sh
npm create @driftengine@latest my-game
cd my-game
npm install
npm run dev
```
It is a Vite and TypeScript project with the engine, DriftScript and the page below already set up,
a test runner, and a command that looks at the game on both backends. It is also set up for a coding
agent to work in, which [Working with a coding agent](https://driftengine.dev/docs/start/with-an-agent) describes.
To add the engine to a project of your own instead, start from Vite's TypeScript template:
```sh
npm create vite@latest my-game -- --template vanilla-ts
cd my-game
npm install @driftengine/core
npm run dev
```
Replace the template's `index.html` with a page that holds one canvas. The engine reads the canvas's
CSS size and sizes its drawing buffer to match, so the canvas only needs to be laid out.
```html
My game
```
Then write `src/main.ts`. [Hello world](https://driftengine.dev/docs/start/hello-world) is the whole of a first one.
## TypeScript
The template's settings are fine. What the engine relies on is a target that allows top-level
`await`, since creating a renderer is asynchronous, and the DOM library:
```json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"noEmit": true
}
}
```
The packages ship compiled JavaScript with declaration files, so nothing else is needed to get
types.
## DriftScript
A game's rules are written in DriftScript, the engine's scripting language, and a project needs two
packages beside the engine for it:
```sh
npm install @driftengine/script driftscript
```
`driftscript` is the language: its compiler, its runtime and the Vite plugin. `@driftengine/script`
is what connects it to the engine. The plugin goes in the Vite config:
```ts
import { fileURLToPath } from 'node:url';
import { driftScript } from 'driftscript/vite';
import { defineConfig } from 'vite';
export default defineConfig(({ command }) => ({
plugins: [
driftScript({
/* The engine's capabilities, as data: every `drift/*` function, its types and its effects. */
capabilities: fileURLToPath(import.meta.resolve('@driftengine/script/capabilities.json')),
/* The engine modules a script in this game may import. Add one here when a script needs it;
an import of a module not named is refused when the file compiles, naming the module. */
manifest: { name: 'my-game', provides: ['drift/random', 'drift/scene', 'drift/input'] },
/* `vite build` compiles for shipping: the editor's metadata stays out of the bundle. */
mode: command === 'build' ? 'production' : 'development',
}),
],
build: {
target: 'es2022',
/* Just above the engine's WebGPU renderer, one module of about 2,100 kB minified that loads only
where WebGPU does. Vite warns past 500 kB by default; anything larger than the renderer still
warns. */
chunkSizeWarningLimit: 2200,
},
}));
```
`capabilities` is the engine's description of every function a script can call, as data, which is
what the compiler checks a call and infers its effects against. `manifest.provides` names the engine
modules this game's scripts may import; a script that imports one not named is refused when it
compiles, and the error names the module. [What a script can reach](https://driftengine.dev/docs/scripting/reach) lists
them all.
TypeScript resolves a `.drs` import through one declaration file anywhere in the project:
```ts
///
```
The editor extension for VS Code, `DriftTech.driftscript-vscode` on the marketplace, highlights
`.drs` files and reports the build's own errors as you type. [Setting up scripts](https://driftengine.dev/docs/scripting/setting-up)
covers loading, binding and hot reload.
## Choosing a backend while you test
`createRenderer` picks the backend. You can force one from the address bar, which is the quickest
way to check that a game looks the same on both:
```text
http://localhost:5173/?backend=webgl2
http://localhost:5173/?backend=webgpu
```
`createRenderer` returns which backend it built and a `reason` in words. Show both somewhere while
you develop: the first question about any picture is what drew it.
## Headers
None are required. A plain static host serves a DriftEngine game.
One feature asks for more: solving physics islands on worker threads needs `SharedArrayBuffer`,
which browsers only offer to a cross-origin isolated page. If you turn that on, serve the page with
`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`. Without
them physics still runs, on the main thread, and the world says why it didn't start the workers.
## Working against a checkout of the engine
If you're changing the engine itself, or tracking its `main` branch, depend on it by path and npm
will link it:
```json
{
"dependencies": {
"@driftengine/core": "file:../driftengine/packages/core"
}
}
```
Add the `drift-source` condition to your bundler so it reads the engine's TypeScript, and an edit to
the engine is live in your game with no build in between. In Vite, spread the defaults back in,
because setting `resolve.conditions` replaces them:
```js
import { defaultClientConditions, defineConfig } from 'vite';
export default defineConfig({
resolve: { conditions: ['drift-source', ...defaultClientConditions] },
});
```
Reading the source also needs `"allowImportingTsExtensions": true` in the tsconfig that checks your
project, because the engine's own imports name their `.ts` files.
## The engine badge
`createRenderer` shows a small DriftEngine badge over the page while the game boots, and holds it
for three seconds after the first frame reaches the screen. The fixed-step loop is held for that
time too, so an intro or a music cue doesn't play behind it.
**Keeping it is a request, and the licence doesn't require it.** Pass `{ splash: false }` as the
third argument to `createRenderer` to turn it off, which is the right choice for anything that isn't a game booting:
a canvas that is one section of a web page, an embed, a tool, a product page, a benchmark. `?splash=0` turns it off from the
address bar without a code change.
## Licence
Apache-2.0. You can use the engine for anything, including commercial games, and modify it.
What the licence asks is that you reproduce the contents of the engine's `NOTICE` file somewhere a
person can read it: in your source, your documentation, or a screen the game shows, such as a
credits or licences page. Every package's entry point already carries that notice in a comment
minifiers keep, so a bundled game includes it without any work on your part.
Only one dependency anywhere in the engine is copyleft, and it reaches only the native host, which
ships it as a separate, replaceable file. [Shipping to the web](https://driftengine.dev/docs/start/shipping-to-the-web) covers what
goes into a web build.
---
# Working with a coding agent
Getting started. https://driftengine.dev/docs/start/with-an-agent
Start a project a coding agent can build on, give the agent the engine's skill, and check every change by looking at the game on both backends.
DriftEngine is built to be written by a coding agent as well as by a person. Each package has one
typed entry point, and its exports carry their documentation with them as comments. A game's rules run in Node with no GPU, so a test
of a rule is a test of the game. And a project can look at its own game on both backends and say
in words what it saw. This page sets a project up so that an agent, such as Claude Code, Codex or
Cursor, works with all three.
## Start a project
```sh
npm create @driftengine@latest my-game
cd my-game
npm install
npm run dev
```
That starts from a lit cube turning at a rate a DriftScript rule decides. For a complete 3D game
to build on, with physics, a character, sound, shadows and a HUD, name the other template:
```sh
npm create @driftengine@latest my-game -- --template first-game
```
The command asks nothing and installs nothing, so an agent can run it unattended. It writes a Vite
and TypeScript project, its program under `src/`, and three things for an agent:
```text
my-game/
AGENTS.md how this project works, and when a change is done
.agents/skills/driftengine/ the engine's skill, where Codex, Cursor and others look
.claude/skills/driftengine/ the same skill, where Claude Code looks
scripts/look.mjs npm run look: the game photographed on both backends
```
`AGENTS.md` is the file most coding agents read on their own when they open a project, Claude Code
among them unless the project gives it an instructions file of its own. It lists the commands, the rules the compiler
cannot check, and what done means here. The skill is longer and is read when the work needs it:
the shape of a program, the traps that look like problems in the engine, and where every page of this
manual and every example is, at the version the project installed.
## Check every change
```sh
npm run check
```
`check` runs `typecheck`, then `test`, which runs the project's tests in Node, then `look`. `look`
starts the game, opens it once with `?backend=webgpu` and once with `?backend=webgl2` in Chrome, or
in Edge where Chrome is not installed, on the machine's own GPU, and writes what it saw:
```text
.driftengine/look/webgpu.png what a player sees on WebGPU
.driftengine/look/webgl2.png and on WebGL2
.driftengine/look/look.json the report, with every console line
```
It fails on a console error or warning, on a canvas of one flat colour, and when the backend it
asked for is not the one that drew. It exits with 2 when it cannot look at all: when it finds no
browser, which `CHROME_PATH` answers, or no hardware GPU, which it refuses rather than trust a
software rasteriser's picture. `npm run look -- --headed` opens a real browser window, which reaches
the GPU on a machine where a headless browser does not.
A report can say a frame is not empty. Only looking says it is the right frame, so the project's
`AGENTS.md` tells the agent to open both pictures before it says a change works. Most agents can
read an image.
`look` runs on Windows, macOS and Linux. It has been measured on Linux; on Windows and macOS it uses
each system's own graphics path through ANGLE, Direct3D 11 and Metal, and reports the GPU it found
on its second line, which is the line to read the first time.
## Add the skill to a project you already have
From the project's directory:
```sh
npm create @driftengine@latest . -- --skill
```
That writes the skill into both folders and replaces an older copy of it, touching nothing else.
Run it again after upgrading the engine, so the skill describes the version installed.
The skill is also in the engine's repository, in `skills/driftengine/`, where tools that install
skills from a repository find it:
```sh
npx skills add drftrun/driftengine
```
That copy follows the repository's main branch rather than the version a project installed. To
make the skill available in every project, copy the `driftengine` folder into
`~/.claude/skills/` for Claude Code, or `~/.agents/skills/` for Codex and Cursor.
## What the agent can read
- **The installed types.** `node_modules/@driftengine/core/dist/index.d.ts` names every export of
the version the project runs and the module each comes from, whose own declarations document it,
and so does each other package's. DriftScript's own reference is
`node_modules/driftscript/docs/LANGUAGE.md`.
- **This manual, at that version.** Each page is Markdown in the engine's repository, at the tag of
every release, and the skill lists every page's address.
- **The examples**, one capability each, at the same tag. [Hello world](https://driftengine.dev/docs/start/hello-world) and
[Your first game](https://driftengine.dev/docs/start/first-game) are the two templates, explained.
- **The whole manual as one file**, for an agent that searches rather than browses:
`https://driftengine.dev/llms-full.txt`, with an index of every page at
`https://driftengine.dev/llms.txt`.
## What still needs a person
`look` sees the first seconds after the game starts. It does not play the game, so a level reached
by playing, a menu behind a key press, and how the controls feel are not in its pictures. Nor is how
fast the game runs on a phone, which only a phone can say: [Shipping to the web](https://driftengine.dev/docs/start/shipping-to-the-web)
covers testing on one.
---
# Hello world
Getting started. https://driftengine.dev/docs/start/hello-world
A complete first program. A renderer on a canvas, light, two meshes, a camera, a loop that turns a cube on a fixed clock, and a rule in DriftScript.
The smallest DriftEngine program that is still a game draws a lit cube on a ground plane and turns
it on a fixed clock. It's about a hundred lines, and every later page builds on the same pieces: a
renderer, an environment, meshes, a scene, a loop, and a rule in DriftScript that the loop asks how
fast to turn.
(This chapter runs the `starter` example at https://driftengine.dev/docs/start/hello-world.)
The program is `examples/starter/main.ts` and one rule beside it in `examples/starter/spin.drs`, and
it is the folder to copy when you begin a project. This page walks through it from the top.
## The imports
The engine comes from its packages' top level: `@driftengine/core` for everything drawn and
simulated, `@driftengine/script` for binding scripts to it. `loadModule` and `patchModule` are
DriftScript's own, and the `.drs` file is imported like any other module.
```ts
import {
Camera,
MeshBuilder,
SceneNode,
createEnvironment,
createRenderer,
srgbColor,
startLoop,
} from '@driftengine/core';
import { bindModule } from '@driftengine/script';
import { loadModule, patchModule } from 'driftscript';
import * as spinScript from './spin.drs';
```
## A renderer on the canvas
```ts
const canvas = document.querySelector('#stage');
if (canvas === null) throw new Error('the page must carry