---
url: /pawn/docs/guide/engine.md
description: Creating an Engine, frame phases, systems, the clock and loop drivers.
---

# Engine and frame

`Engine` runs one koota world: it ticks systems phase by phase and draws the
scene into every view.

## Creating an engine

```ts
import { Engine } from "@pawnjs/core";

const engine = new Engine({
  canvas,              // creates a WebGLRenderer for this canvas
  // renderer,         // or pass your own WebGLRenderer
  // enableTransparency: true // page shows through where no view draws
  // pixelRatio: 1     // defaults to devicePixelRatio
  // driver,           // when to tick; defaults to RafDriver
  // enablePauseWhenHidden: false, // keep ticking while the page is hidden
  // onContextLost, onContextRestored, // the GPU dropped the WebGL context
  // world,            // an existing koota world; defaults to a new one
  // seed: 42,         // seed for engine.random, so runs repeat
  // camera: { position: { y: 2, z: 5 } }, // a full-canvas view
  // background: "#09090b",                // clear color of the canvas
  // lights: "studio",                     // hemisphere light and a sun
  // toneMapping: "aces", exposure: 1,     // how bright colors fit the screen
  // enableShadows: true,                  // lights with enableShadow cast them
  // environment: "room",                  // reflections and light all around
  // fit: false,       // the drawing buffer follows the canvas; false for none
  // fixedTimeStep, maxDelta, maxFixedSteps, timeScale (clock options)
});
```

| Option | Default | Meaning |
|---|---|---|
| `canvas` | | Canvas to create a renderer for. Ignored when `renderer` is given. |
| `renderer` | | Renderer to draw with. Without `canvas` and `renderer` the engine runs headless. |
| `enableTransparency` | `false` | Whether a renderer the engine creates has a transparent canvas. |
| `pixelRatio` | `devicePixelRatio` | Pixel ratio for a renderer the engine creates. |
| `driver` | `new RafDriver()` | Decides when the engine ticks. |
| `enablePauseWhenHidden` | `true` | Whether a started engine stops its driver while the page is hidden, and starts it again when the page shows; see [Lifecycle](#lifecycle). |
| `onContextLost` | | Called when the renderer's WebGL context is lost; see [Without WebGL](#without-webgl). |
| `onContextRestored` | | Called when a lost WebGL context is restored. |
| `world` | new world | World to run on. A world the engine creates is destroyed on `dispose()`. A world belongs to one engine: pass a world made earlier, not one another engine runs. |
| `seed` | new each time | Seed for `engine.random`; see [Testing and debugging](./testing#random-numbers-from-a-seed). |
| `camera` | | A three.js camera, or `{ position, target, fov, near, far }` for a perspective one. Adds a full-canvas view named `"main"`. |
| `background` | | Color the canvas is cleared to, for a renderer the engine creates. |
| `lights` | `false` | `"studio"` spawns a hemisphere light and a sun from above, front right, as [`Light`](./entities#light) entities. |
| `toneMapping` | `"none"` | How a renderer the engine creates brings bright colors into the screen's range: `"neutral"` keeps colors as given (dashboards), `"aces"` is filmic with strong contrast (games), `"agx"` rolls highlights off softly, `"none"` clips them. |
| `exposure` | `1` | Brightness before tone mapping, for a renderer the engine creates. |
| `enableShadows` | `false` | Whether a renderer the engine creates draws shadows. |
| `environment` | | What the scene reflects and is lit by all around, for any renderer: `"room"` for a neutral studio, or a panorama texture of your own (e.g. a loaded HDR). |
| `fit` | `true` | Element whose size the drawing buffer follows (see `fitToElement` below): `true` for the canvas, `false` for none. Only for a renderer the engine creates. |

### How the scene looks

Three options make a scene look finished: tone mapping, shadows and an
environment for metal and glossy surfaces to reflect.

```ts
import { Engine, Light, Position, Shape } from "@pawnjs/core";

const engine = new Engine({
  canvas,
  camera: { position: { y: 3, z: 8 } },
  toneMapping: "aces",
  enableShadows: true,
  environment: "room",
  lights: "studio", // its sun casts shadows
});
engine.spawn(Shape({ kind: "torus", metalness: 1, roughness: 0.2 }), Position({ y: 1 }));
```

Shapes and models cast and receive shadows; a light casts them with
`enableShadow` (see [`Light`](./entities#light)). Settings of the
renderer apply to one the engine creates; a renderer of your own keeps
its own. To change them later, set them on `engine.renderer`
(`toneMapping`, `toneMappingExposure`; materials drawn before shadows
were turned on need `needsUpdate` to show them), and on `engine.scene`
for the environment (`environment`, `environmentIntensity`). A panorama
may still be loading: it shows once it has. A material with its own
`envMap` reflects that at its own `envMapIntensity` instead.

Camera options default to `{ x: 0, y: 2, z: 6 }` for `position`, the
origin for `target`, a `fov` of 50 degrees, `near` 0.1 and `far` 1000. The
view's camera is `engine.views.first.camera`; [`CameraRig`](./camera)
moves it.

The engine exposes `engine.world` (koota `World`), `engine.scene` (three.js
`Scene`), `engine.clock`, `engine.random` (seeded random numbers),
`engine.renderer` (or `null` when headless) and
`engine.views` (the [views](./views#the-views-of-an-engine) and where they
are). `engine.spawn` spawns an entity: from traits, the same as
`engine.world.spawn(...traits)`, or from a [prefab](./prefabs.md) or the
name it is registered under, with overrides
(`engine.spawn(Tower, { position: { x: 2 } })`).

## Lifecycle

```ts
engine.start();   // starts ticking through the driver
engine.stop();    // stops; the pause is not counted as time
engine.dispose(); // stops, runs plugin cleanups, destroys what the engine created
```

While the page is hidden (another tab, a minimized window), a started
engine stops its driver and starts it again when the page shows; the
pause is not counted as time, and `engine.running` stays `true`. Set
`enablePauseWhenHidden: false` for a scene that must keep ticking hidden,
such as one that records or streams.

`dispose()` destroys the world and renderer only if the engine created them.
A disposed engine throws on `use`, since a plugin's cleanup would never run.
Geometries and materials of your entities belong to you; release them with
`disposeObject3D(root)`.

`engine.setSize(width, height, updateStyle = true)` resizes the drawing buffer
in CSS pixels. Pass `false` as the third argument when CSS already sizes the
canvas.

`engine.fitToElement(element, onResize?)` keeps the drawing buffer the size of
an element (`clientWidth` by `clientHeight`, so padding counts), usually the
canvas's container, now and whenever it resizes. It
leaves the canvas's CSS size alone, so give the canvas `width: 100%;
height: 100%`; a canvas without a CSS size would grow with its own drawing
buffer. `onResize(width, height)` runs after each resize, for example
to reframe a camera for a new aspect. It returns a function that stops
following; `dispose()` stops it too. Elements with no size (hidden) are
skipped. The first call takes over from the `fit` option, so the engine no
longer follows the canvas then.

```ts
engine.fitToElement(container, (width, height) => {
  camera.position.z = width < height ? 8 : 5;
});
```

### Without WebGL

`new Engine({ canvas })` throws `WebGLUnavailableError` when the browser
gives the canvas no WebGL context: the GPU is turned off or blocked, as
in a virtual machine, over remote desktop or in a WebView without
hardware acceleration. Catch it to show a page without 3D (in React, an
error boundary around `<Pawn>` catches it); the browser's error is its
`cause`.

```ts
try {
  const engine = new Engine({
    canvas,
    onContextLost: showFallback, // the GPU reset or the browser took it back
    onContextRestored: hideFallback,
  });
  engine.start();
} catch (error) {
  if (error instanceof WebGLUnavailableError) showFallback();
  else throw error;
}
```

A context can also be lost later. Until it is restored the engine draws
nothing, but systems keep running, so the scene is current when it
comes back; `engine.contextLost` tells the state. After a restore three.js
uploads geometries and textures again, and the engine remakes the
`"room"` environment; a render target of your own must be drawn again.
A renderer of your own is followed the same way, and a host that swaps
in a new renderer with `setRenderer` (as `@pawnjs/maps` does after a
loss) restores the engine with it.

## The frame

Every tick runs these phases in order, then draws the views:

1. `input`: queued input events are applied first (see [Input](./input)).
2. `fixedUpdate`: zero or more times, each with the constant `fixedTimeStep`.
   Physics steps here.
3. `update`: game logic. The default phase for systems.
4. `lateUpdate`: logic that must see the results of `update`, such as
   following one entity with another.
5. `render`: the engine's scene sync runs first here (order
   `Engine.SCENE_SYNC_ORDER`), copying transforms into three.js objects and
   instance matrices; the camera rig and labels run after it.

After the phases, the engine draws every enabled view. `PHASES` lists the
phase names in this order, and `Phase` is their type.

## Systems

A system is a function that receives a `FrameContext`:

```ts
import type { System } from "@pawnjs/core";

const gravity: System = ({ world, delta, elapsed, frame, engine }) => {
  // ...
};

const remove = engine.addSystem(gravity, { phase: "fixedUpdate", order: 10 });
remove(); // unregisters it
```

| Field | Meaning |
|---|---|
| `engine` | The engine. |
| `world` | The koota world. |
| `delta` | Seconds since the previous call of this phase; constant in `fixedUpdate`. |
| `unscaledDelta` | Real seconds since the previous frame, before `clock.timeScale`; the same in every phase and above 0 while time is paused, for what keeps moving then (camera controls, a debug overlay). |
| `elapsed` | Scaled seconds since the engine started. |
| `frame` | Frame counter. |

Within a phase, a lower `order` runs first (default `0`); ties keep the order
of registration. Systems may add or remove systems while a phase runs. The
context object is reused between calls, so do not keep a reference to it.

### Easing toward a moving goal

To follow something that keeps moving (a target, a value from a feed),
cover a share of the remaining way each frame. `easeByHalfLife(delta,
halfLife)` gives that share for a half-life, the seconds to cover half the
way, so the motion looks the same at any frame rate; a half-life of 0
jumps straight there. The camera rig, the chase camera and smoothing use
it too.

```ts
const follow: System = ({ delta }) => {
  marker.position.lerp(goal, easeByHalfLife(delta, 0.2));
};
```

## Timers

`engine.after(seconds, callback)` runs a callback once after a delay and
`engine.every(seconds, callback)` on an interval. Both return a function
that cancels the timer:

```ts
engine.after(0.6, () => engine.spawn(Fruit));
const stop = engine.every(1, () => engine.spawn(Balloon));
stop();
```

Timers count scaled engine time, so a paused clock (`timeScale` 0) holds
them and `engine.step()` drives them in tests. They run at the start of
the `update` phase (order `Engine.TIMERS_ORDER`), earliest first; a frame
longer than an interval runs it once per interval passed. `every` needs an
interval above 0, and `dispose()` cancels every timer.

## Scopes

`engine.scope()` creates a `Scope`: a group of entities and timers that
end together, such as one level of a game or one screen of a dashboard.
`dispose()` destroys its entities with their children and cancels its
timers; the rest of the world (camera, lights, UI entities) stays. A
restart is disposing the scope and building a new one:

```ts
let level = engine.scope();
build(level);

function build(level: Scope) {
  level.spawn(Tower, { position: { x: 2 } });
  level.spawn(Position, Shape({ kind: "box" }));
  level.after(3, startWave);
}

function restart() {
  level.dispose();
  level = engine.scope();
  build(level);
}
```

* `spawn` takes what `engine.spawn` takes (traits, or a prefab or its
  name with overrides and `{ parent, id }`) and spawns into the scope;
  `add(entity)` moves an existing entity in from another scope or none.
* `after` and `every` work like the engine's and end with the scope.
* `has(entity)`, `entities()` and `Scope.of(entity)` tell what belongs
  where; a [`Spawner`](./prefabs.md#spawner) puts what it spawns in its own scope.
* A disposed scope throws when asked to spawn or start a timer.
* `engine.dispose()` disposes the scopes still live, in a world of your
  own too.

## Clock

`engine.clock` turns host timestamps into frame deltas:

| Property | Default | Meaning |
|---|---|---|
| `fixedTimeStep` | `1 / 60` | Step of the `fixedUpdate` phase, in seconds. |
| `maxDelta` | `0.1` | Upper bound for one driver frame's delta (for example after a long stall). |
| `maxFixedSteps` | `5` | Upper bound for fixed steps in one frame; excess time is dropped. |
| `timeScale` | `1` | Multiplier for every delta; `0` pauses simulation time. |

These are writable at runtime (`engine.clock.timeScale = 0.5`). `clock.alpha`
is the progress between the last and the next fixed step (0 to 1), for
interpolating visuals of a fixed-step simulation.

`Clock` is also exported, for timing a loop of your own outside an
engine (an engine's own clock is advanced by the engine; don't advance it
yourself): `advance(timeMs)` turns a host timestamp into a delta bounded by
`maxDelta`, `advanceBy(seconds)` takes an explicit one,
`consumeFixedSteps()` returns the fixed steps now due, and
`clearTimestamp()` keeps a pause out of the next delta.

## Loop drivers

A `LoopDriver` decides when the engine ticks:

* `RafDriver` (default) ticks on every `requestAnimationFrame`.
* `ManualDriver` ticks only when you call `driver.advance(ms)`. Use it in tests
  or when another loop owns the timing.
* `DemandDriver` draws only when something changed; see [Render on demand](#render-on-demand).
* `MapOverlay` from [@pawnjs/maps](../packages/maps) ticks on the map's draws.

Without any driver, `engine.step(seconds)` runs one frame with an explicit
delta. The delta is taken as given: `maxDelta` and `maxFixedSteps` bound only
driver frames, so `engine.step(0.5)` advances half a second and runs every
fixed step in it:

```ts
const engine = new Engine(); // headless: no canvas, no renderer
engine.world.spawn(Position);
engine.step(1 / 60);
```

A custom driver implements two methods:

```ts
import type { LoopDriver, TickCallback } from "@pawnjs/core";

class MyDriver implements LoopDriver {
  start(tick: TickCallback) { /* call tick(timeMs) whenever a frame is due */ }
  stop() { /* stop calling tick */ }
}
```

A driver with an `invalidate()` method ticks on demand: the engine calls
it when it needs a tick, and draws only the frames where something drawn
changed.

### Render on demand

A scene that stays open all day (a dashboard, a digital twin) does not
need to draw 60 times a second while nothing moves. `DemandDriver` draws
a frame only when something drawn changed, then keeps drawing on
`requestAnimationFrame` while it goes on changing. In between it ticks
every `idleInterval` seconds (0.08 by default) without drawing, so timers,
feeds and gamepads keep going while the GPU rests.

```ts
const engine = new Engine({ canvas, driver: new DemandDriver() });
engine.start();

// A change the engine cannot see: a three.js object changed by hand.
material.color.set("#f59e0b");
engine.invalidate();
```

The engine asks for a frame by itself when:

* an entity's `Position`, `Rotation` or `Scale` changes, so motion
  behaviors, tweens, physics and feeds draw as they move;
* a `Visual`, `Instance`, `Shape`, `Light` or `Tint` is added, changed or
  removed, or an entity is spawned under or taken from a parent;
* a view's camera moves, turns or changes its projection (`CameraRig`,
  `ChaseCamera`), or a view moves or resizes (a view following an
  element, as the page scrolls);
* the canvas resizes, the renderer changes or a lost WebGL context comes
  back.

Input (pointer, keys, wheel, on-screen buttons, device tilt) and page
scrolls tick at once, and draw only when what they do changes something
above: moving the mouse over a still scene draws nothing. Gamepads are
read on the ticks there are. A timer runs on any tick; what it changes
in traits is drawn like any other change. A change smaller than a
millionth (of a unit, or of a quaternion part) asks for no frame, so
motion slower than that per tick waits for the next drawn frame.

Call `engine.invalidate()` after anything else you change yourself: a
material, a geometry, a texture that finished loading, a `Visual` moved
through three.js instead of its traits. With other drivers it does
nothing. A change found by a slow tick shows within `idleInterval`;
keep that below `clock.maxDelta`, or engine time falls behind.
