Three.js Custom & Instanced Attributes (300k Grass Blades)

Custom vertex attributes in Three.js, with a field of up to 300,000 wind-blown grass blades from one InstancedBufferGeometry using a per-vertex tip weight and per-instance offset, height, phase, colour and lean in an interleaved buffer.

Key topics: three.js custom attributes, instancedbuffergeometry, interleaved buffer, grass shader, instanced attributes

What this code does

- Per-Vertex Attribute: `aTip` runs from 0 at the root to 1 at the tip and scales the wind bend.
- Per-Instance Attributes: offset, height, phase, colour and lean vary per blade through `InstancedBufferAttribute`s.
- Interleaving: one `InstancedInterleavedBuffer` (stride 9 floats) holds all instance data for locality and a single upload.
- Wind: the vertex shader bends tips quadratically with a travelling gust, entirely on the GPU.
- Attribute Views: colour-code any attribute to see exactly what each vertex or instance receives.
- Controls: blade count, wind, attribute view and interleaved vs separate buffers.

Continue Learning

JavaScript Implementation

ES6+
// Custom per-vertex + per-instance attributes on an InstancedBufferGeometry
const geometry = new THREE.InstancedBufferGeometry()
geometry.setAttribute('position', bladePositions)                                  // per vertex
geometry.setAttribute('aTip', new THREE.Float32BufferAttribute(tipWeights, 1))     // per vertex
const data = new Float32Array(count * 9)                                          // offset3 height1 phase1 color3 lean1
const buffer = new THREE.InstancedInterleavedBuffer(data, 9, 1)                   // stride 9 floats, 1 per instance
geometry.setAttribute('aOffset', new THREE.InterleavedBufferAttribute(buffer, 3, 0))
geometry.setAttribute('aHeight', new THREE.InterleavedBufferAttribute(buffer, 1, 3))
geometry.setAttribute('aColor', new THREE.InterleavedBufferAttribute(buffer, 3, 5))
geometry.instanceCount = count
// vertex shader: attribute vec3 aOffset; attribute float aTip; … p.x += aTip * aTip * wind;
scene.add(new THREE.Mesh(geometry, grassMaterial))