TExcelTAD
Home › 3D Web Games with Three.js › InstancedMesh & BatchedMesh

InstancedMesh & BatchedMesh

Forests, grass, rocks, coins, bullets, asteroid fields, crowds: games are full of many copies of the same thing. Drawing each copy as its own Mesh costs a draw call apiece (Draw Calls). Instancing draws all copies of one geometry + material in a single draw call, with a per-instance transform (and optionally a color) stored in a buffer. It's the most important optimization for game scenes in Three.js.

InstancedMesh

js
const COUNT = 10000;
const trees = new THREE.InstancedMesh(treeGeometry, treeMaterial, COUNT);
const dummy = new THREE.Object3D();                  // a helper to build matrices
for (let i = 0; i < COUNT; i++) {
  dummy.position.set(x, 0, z);
  dummy.rotation.y = angle;
  dummy.scale.setScalar(size);
  dummy.updateMatrix();
  trees.setMatrixAt(i, dummy.matrix);              // per-instance transform
  trees.setColorAt(i, color);                      // optional per-instance color
}
trees.instanceMatrix.needsUpdate = true;           // upload after changes
trees.instanceColor.needsUpdate = true;
scene.add(trees);

Key facts:

Feature How
Move one instance setMatrixAt(i, m) then instanceMatrix.needsUpdate = true
Change its color setColorAt(i, c) then instanceColor.needsUpdate = true (the first setColorAt creates the color buffer)
Draw fewer (pooling) mesh.count = n draws only the first n instances; keep live ones at the front
Frequently updated matrices mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage)
Picking raycast hits return hit.instanceId
Culling the whole InstancedMesh is culled as one object, by a bounding sphere around all instances; call computeBoundingSphere() after moving instances far

Ten thousand asteroids in one call

The playground draws 10,000 rotating asteroids with per-instance colors in one draw call, updating every matrix every frame. Hover over an asteroid to highlight it (the raycast reports its instanceId).

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }
#stats { position: fixed; left: 8px; top: 8px; color: #fff; font: 12px ui-monospace, monospace; background: rgba(0,0,0,.55); padding: 4px 6px; border-radius: 4px; white-space: pre; pointer-events: none }</style>
<div id="stats"></div>
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#070912');
const camera = new THREE.PerspectiveCamera(55, innerWidth / innerHeight, 0.1, 400);
camera.position.set(0, 25, 70);
camera.lookAt(0, 0, 0);
addEventListener('resize', () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});
scene.add(new THREE.HemisphereLight('#c8d8ff', '#202030', 1.0));
const sun = new THREE.DirectionalLight('#fff4e0', 3);
sun.position.set(10, 5, 8);
scene.add(sun);
const planet = new THREE.Mesh(new THREE.SphereGeometry(10, 48, 24), new THREE.MeshStandardMaterial({ color: '#d58b4a' }));
scene.add(planet);

function mulberry32(seed) {
  return () => {
    seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const rng = mulberry32(42);

const COUNT = 10000;
const rocks = new THREE.InstancedMesh(new THREE.IcosahedronGeometry(0.4, 0), new THREE.MeshStandardMaterial({ flatShading: true }), COUNT);
rocks.instanceMatrix.setUsage(THREE.DynamicDrawUsage);    // rewritten every frame
const data = [];                                           // per-instance game data lives in plain arrays
const color = new THREE.Color();
for (let i = 0; i < COUNT; i++) {
  const radius = 16 + rng() * 22, angle = rng() * Math.PI * 2;
  data.push({ radius, angle, y: (rng() - 0.5) * 3 * (radius / 20), speed: 0.6 / Math.sqrt(radius), spin: rng() * 3, size: 0.4 + rng() * 1.4 });
  rocks.setColorAt(i, color.setHSL(0.06 + rng() * 0.08, 0.25, 0.35 + rng() * 0.3));
}
scene.add(rocks);

const dummy = new THREE.Object3D();
const raycaster = new THREE.Raycaster(), pointer = new THREE.Vector2(9, 9);
renderer.domElement.addEventListener('pointermove', (e) => pointer.set((e.offsetX / innerWidth) * 2 - 1, -(e.offsetY / innerHeight) * 2 + 1));
let hovered = -1, savedColor = new THREE.Color();
const stats = document.getElementById('stats');
const timer = new THREE.Timer();

renderer.setAnimationLoop((t) => {
  timer.update(t);
  const time = Math.max(0, timer.getElapsed());
  for (let i = 0; i < COUNT; i++) {
    const d = data[i], a = d.angle + time * d.speed;
    dummy.position.set(Math.cos(a) * d.radius, d.y, Math.sin(a) * d.radius);
    dummy.rotation.set(time * d.spin, time * d.spin * 0.7, 0);
    dummy.scale.setScalar(d.size);
    dummy.updateMatrix();
    rocks.setMatrixAt(i, dummy.matrix);
  }
  rocks.instanceMatrix.needsUpdate = true;
  rocks.computeBoundingSphere();                           // instances moved: keep culling and raycasting correct

  raycaster.setFromCamera(pointer, camera);
  const hit = raycaster.intersectObject(rocks, false)[0];
  const id = hit ? hit.instanceId : -1;
  if (id !== hovered) {
    if (hovered >= 0) rocks.setColorAt(hovered, savedColor);          // restore the old one
    if (id >= 0) { rocks.getColorAt(id, savedColor); rocks.setColorAt(id, color.set('#4fc3f7')); }
    hovered = id;
    rocks.instanceColor.needsUpdate = true;
  }
  renderer.render(scene, camera);
  stats.textContent = `instances ${COUNT}\ndraw calls ${renderer.info.render.calls}\ntriangles ${renderer.info.render.triangles}\nhover instanceId ${hovered}`;
});
</script>

Two calls for 10,000 asteroids and a planet. The bottleneck has moved to the JavaScript loop that rebuilds 10,000 matrices per frame (and the raycast that tests 200,000 triangles); the GPU barely notices. For effects like this, games move the motion into the vertex shader (pass time as a uniform, compute the orbit on the GPU) so the CPU writes nothing per frame; the Shaders course shows how. For mostly static instances (a forest), write the matrices once and you pay nothing per frame.

Pooling with count

InstancedMesh is also a ready-made object pool for projectiles, coins and particles: allocate the maximum once and draw only the live ones by keeping them packed at the front:

js
// remove instance i by moving the last live one into its slot ("swap and pop")
function removeAt(i) {
  const last = bullets.count - 1;
  bullets.getMatrixAt(last, tmp);
  bullets.setMatrixAt(i, tmp);
  state[i] = state[last];
  bullets.count--;
  bullets.instanceMatrix.needsUpdate = true;
}

BatchedMesh: different shapes, one call

Instancing needs one geometry. BatchedMesh relaxes that: it stores several different geometries sharing one material in one big buffer, and each instance picks a geometry. Every instance keeps its own matrix, color and visibility, and Three.js culls each instance separately (perObjectFrustumCulled, on by default) and can sort them. It suits varied static-ish props: a city block of different buildings, a level's rocks and crates with one atlas material.

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }
#stats { position: fixed; left: 8px; top: 8px; color: #fff; font: 12px ui-monospace, monospace; background: rgba(0,0,0,.55); padding: 4px 6px; border-radius: 4px; white-space: pre }</style>
<div id="stats"></div>
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1a2030');
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 200);
camera.position.set(0, 18, 26);
camera.lookAt(0, 0, 0);
scene.add(new THREE.HemisphereLight('#fff', '#334', 1.3));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(4, 10, 6);
scene.add(sun);

const shapes = [new THREE.BoxGeometry(1, 1, 1), new THREE.SphereGeometry(0.6, 16, 10), new THREE.ConeGeometry(0.6, 1.4, 12), new THREE.TorusGeometry(0.45, 0.18, 8, 20)];
const maxVertices = shapes.reduce((n, g) => n + g.attributes.position.count, 0);
const maxIndices = shapes.reduce((n, g) => n + g.index.count, 0);
const INSTANCES = 900;
const batch = new THREE.BatchedMesh(INSTANCES, maxVertices, maxIndices, new THREE.MeshStandardMaterial({ roughness: 0.5 }));
const geometryIds = shapes.map((g) => batch.addGeometry(g));       // each shape stored once

const m = new THREE.Matrix4(), q = new THREE.Quaternion(), p = new THREE.Vector3(), s = new THREE.Vector3(1, 1, 1);
const c = new THREE.Color();
const ids = [];
for (let i = 0; i < INSTANCES; i++) {
  const gx = i % 30, gz = Math.floor(i / 30);
  const id = batch.addInstance(geometryIds[(gx + gz) % shapes.length]);   // pick a shape per instance
  p.set((gx - 14.5) * 1.6, 0.6, (gz - 14.5) * 1.6);
  batch.setMatrixAt(id, m.compose(p, q.identity(), s));
  batch.setColorAt(id, c.setHSL(((gx + gz) % 12) / 12, 0.6, 0.55));
  ids.push(id);
}
scene.add(batch);

const stats = document.getElementById('stats');
renderer.setAnimationLoop((t) => {
  for (let i = 0; i < ids.length; i += 7) {          // move every 7th instance: each keeps its own matrix
    batch.getMatrixAt(ids[i], m);
    m.decompose(p, q, s);
    p.y = 0.6 + Math.abs(Math.sin(t / 400 + i)) * 1.2;
    batch.setMatrixAt(ids[i], m.compose(p, q, s));
  }
  scene.rotation.y = t / 9000;
  renderer.render(scene, camera);
  stats.textContent = `geometries ${shapes.length}, instances ${INSTANCES}\ndraw calls ${renderer.info.render.calls}`;
});
</script>

One draw call for 900 objects of four different shapes. (BatchedMesh uses the WEBGL_multi_draw extension when the browser has it and falls back to separate draws otherwise, so check renderer.info on your target devices.)

Which to use

Many Mesh InstancedMesh BatchedMesh Merged geometry
Draw calls one each 1 1 (with multi-draw) 1
Different geometries yes no yes yes
Different materials yes no (per-instance color only) no (one material) no (groups → more calls)
Move one object yes yes (matrix) yes (matrix) no
Per-object culling yes no (whole set) yes no
Best for a few hundred unique things thousands of identical things many varied props static level geometry

Test yourself

You changed instance 42's matrix with setMatrixAt but nothing moves on screen. What is missing?

  1. mesh.updateMatrix()
  2. mesh.instanceMatrix.needsUpdate = true
  3. renderer.info.reset()
  4. mesh.count = 42

How do you draw only the first 120 of 1,000 allocated instances?

  1. Set their scale to 0
  2. instancedMesh.count = 120
  3. Call dispose() on the rest
  4. Create a new InstancedMesh

When is BatchedMesh a better fit than InstancedMesh?

  1. When all objects are identical
  2. When objects have different geometries but share one material, and each must stay individually movable
  3. When every object needs a different material
  4. For skinned characters