---
url: /pawn/docs/guide/instancing.md
description: >-
  Drawing thousands of entities as one InstancedMesh with Instance and
  InstanceBatch.
---

# Instancing

A `Visual` per entity means one `Object3D` and usually one draw call each.
For thousands of similar entities, draw them as instances of one
`InstancedMesh` instead:

```ts
import { Instance, InstanceBatch, Position } from "@pawnjs/core";
import { Color, IcosahedronGeometry, MeshStandardMaterial } from "three";

// One batch, one draw call, however many entities point at it.
const batch = new InstanceBatch({
  geometry: new IcosahedronGeometry(0.1),
  material: new MeshStandardMaterial(),
  capacity: 10_000, // optional; grows by doubling when full (default 1024)
});

const color = new Color();
for (let i = 0; i < 10_000; i++) {
  const entity = engine.world.spawn(
    Position({ x: engine.random.range(0, 10), y: 0, z: engine.random.range(0, 10) }),
    Instance(batch),
  );
  batch.setColor(entity, color.setHSL(i / 10_000, 0.8, 0.6));
}
```

Here 4,900 boxes of one batch ride a wave, in one draw call:

```ts
import {
  Engine,
  Instance,
  InstanceBatch,
  Position,
  type System,
  View,
} from "@pawnjs/core";
import { trait } from "koota";
import {
  AmbientLight,
  BoxGeometry,
  Color,
  DirectionalLight,
  MeshStandardMaterial,
  PerspectiveCamera,
} from "three";

const SIDE = 70; // 4,900 boxes, one draw call

/** Where an entity sits on the floor, for the wave. */
const Cell = trait({ x: 0, z: 0 });

const wave: System = ({ world, elapsed }) => {
  world.query(Cell, Position).updateEach(([cell, position]) => {
    const d = Math.hypot(cell.x, cell.z);
    position.y = Math.sin(d * 0.35 - elapsed * 2.5) * 0.6;
  });
};

export default function instancing(canvas: HTMLCanvasElement): Engine {
  canvas.style.cssText = "display:block;width:100%;height:100%";
  const engine = new Engine({ canvas });
  engine.addSystem(wave);

  engine.scene.add(new AmbientLight(0xffffff, 0.6));
  const sun = new DirectionalLight(0xffffff, 2);
  sun.position.set(5, 10, 3);
  engine.scene.add(sun);

  const batch = new InstanceBatch({
    geometry: new BoxGeometry(0.8, 0.8, 0.8),
    material: new MeshStandardMaterial(),
    capacity: SIDE * SIDE,
  });
  const color = new Color();
  for (let i = 0; i < SIDE; i++) {
    for (let j = 0; j < SIDE; j++) {
      const x = i - SIDE / 2;
      const z = j - SIDE / 2;
      const box = engine.world.spawn(
        Position({ x, z }),
        Cell({ x, z }),
        Instance(batch),
      );
      batch.setColor(box, color.setHSL(0.6 + (i + j) / (SIDE * 8), 0.7, 0.6));
    }
  }

  const camera = new PerspectiveCamera(45, 1, 0.1, 200);
  camera.position.set(0, 30, 45);
  camera.lookAt(0, -4, 0);
  engine.views.add(new View({ camera, background: 0x09090b }));

  engine.fitToElement(canvas);
  engine.start();
  return engine;
}

```

* Adding `Instance` also adds `Position`, `Rotation` and `Scale` when missing.
  Keep them while the entity is instanced.
* The engine writes instance matrices from the transform traits in the
  `render` phase; no `Object3D` exists per entity.
* `batch.setColor(entity, color)` sets a per-instance color, multiplied with
  the material color. New instances start white; `batch.getColor(entity,
  target)` reads it back.
* `batch.setMatrix(entity, matrix)` writes an instance's matrix at once (for
  picking before the next render); the next render writes it again from
  the transform traits. `batch.indexOf(entity)` and
  `batch.entityAt(index)` map between entities and instance indices, e.g.
  for a raycast hit's `instanceId`.
* The batch's mesh joins the scene with its first entity and leaves it when
  the batch empties. Settings on `batch.mesh` (shadows, for example) survive
  growth.
* Picking maps the hit instance back to its entity, like a `Visual`.
* Use either `Instance` or `Visual` on an entity, not both.
* Instances are drawn in world space and ignore `ChildOf`.

Geometry and material belong to you. `batch.dispose()` releases only the
batch's own instance buffers.

## Instanced shapes

A [`Shape`](./entities.md#shape) with `enableInstancing` is drawn as an
instance without a batch of your own: the engine keeps one batch per kind
of shape and colors each instance with the shape's `color`.

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

for (let i = 0; i < 1000; i++) {
  engine.world.spawn(
    Shape({ kind: "sphere", color: "#38bdf8", enableInstancing: true }),
    Position({ x: engine.random.range(-10, 10), z: engine.random.range(-10, 10) }),
    Scale({ x: 0.2, y: 0.2, z: 0.2 }),
  );
}
```

* `Tint`, hover and clicks work on instanced shapes as on meshes.
* Changing `kind` moves the entity to that kind's batch; turning
  `enableInstancing` off gives it a mesh of its own again.
* Instances are drawn in world space, so a shape under a `ChildOf` parent
  stays a mesh.
* `burst()` throws instanced spheres.

## Measured

Measured headless with 100,000 moving entities (`bun run bench` in
`packages/core`), a frame takes about 12 ms with `Instance` or instanced
`Shape`, about 46 ms with a `Shape` mesh each and about 100 ms with a
`Visual` each; drawing, which instancing cuts to one call per batch, comes
on top. The [Swarm example](https://jakubprill.github.io/pawn/swarm.html)
shows it live.
