Skip to content

Patch Shader

InstancedMesh2 renders through indirect instancing, adding a USE_INSTANCING_INDIRECT define.
three.js shaders are patched automatically, but external or custom shaders that check USE_INSTANCING must be patched too.

import { patchShader } from '@three.ez/instanced-mesh';
const patched = patchShader(externalShaderSource);

patchShader replaces:

#ifdef USE_INSTANCING

with:

#if defined USE_INSTANCING || defined USE_INSTANCING_INDIRECT

Custom Chunks

When writing a vertex shader from scratch, the library registers custom chunks in three.js ShaderChunk, so they can be included with #include <...>:

  • <instanced_pars_vertex> — declares instanceIndex, matricesTexture and the getInstancedMatrix() helper.
  • <instanced_vertex> — computes instanceMatrix (include it inside main, before using the matrix).
  • <instanced_color_pars_vertex> / <instanced_color_vertex> — per-instance color.
  • <instanced_skinning_pars_vertex> — per-instance bones (replaces skinning_pars_vertex).
#include <instanced_pars_vertex>
void main() {
#include <instanced_vertex>
vec4 worldPosition = instanceMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * modelViewMatrix * worldPosition;
}