TExcelTAD
Home › Shaders & Graphics Programming › Three.js ShaderMaterial

Three.js ShaderMaterial

Raw WebGL2 makes you write fifty lines before the first triangle. Three.js does that plumbing for you: geometry buffers, attribute bindings, the camera matrices, resizing. With ShaderMaterial and RawShaderMaterial you keep all of that and replace only the part you care about: the vertex and fragment shaders. This is also how custom shaders work in most engines: the engine owns the mesh and the camera, you own the shader.

The examples use Three.js r186 through the playground's import map (import * as THREE from 'three'). For the Three.js basics (scene, camera, renderer, meshes) see the Three.js course.

ShaderMaterial: Three.js fills in the boilerplate

A ShaderMaterial takes your vertexShader and fragmentShader strings and prepends a header. That header declares the attributes of the geometry and the uniforms Three.js sets for every object, so you can use them without declaring them:

Declared for you Type Meaning
position, normal, uv attributes (vec3, vec3, vec2) from the BufferGeometry
modelMatrix mat4 object → world
viewMatrix mat4 world → camera
modelViewMatrix mat4 object → camera (viewMatrix * modelMatrix)
projectionMatrix mat4 camera → clip space
normalMatrix mat3 object normals → camera space (inverse-transpose of modelViewMatrix)
cameraPosition vec3 camera position in world space

Your own uniforms go in the uniforms option as { name: { value } } objects. Three.js uploads value before each draw, so animating is just assigning material.uniforms.uTime.value = t.

The header also accepts the older GLSL 1 spelling (attribute, varying, gl_FragColor), which most tutorials use and which is mapped to GLSL ES 3.00 behind the scenes. The example below uses it.

html · try it yourself
<style>body { margin: 0; background: #101018 } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 0, 4);

const material = new THREE.ShaderMaterial({
  uniforms: {
    uTime: { value: 0 },
    uColorA: { value: new THREE.Color(0x3355ff) },
    uColorB: { value: new THREE.Color(0xff5577) },
  },
  vertexShader: /* glsl */ `
    uniform float uTime;
    varying vec3 vNormal;
    varying float vBump;
    void main() {
      // push every vertex out along its normal by a moving wave pattern
      float bump = sin(position.x * 4.0 + uTime) * sin(position.y * 4.0 + uTime * 1.3) * sin(position.z * 4.0);
      vBump = bump;
      vec3 displaced = position + normal * bump * 0.2;
      vNormal = normalize(normalMatrix * normal);                       // camera-space normal
      gl_Position = projectionMatrix * modelViewMatrix * vec4(displaced, 1.0);
    }`,
  fragmentShader: /* glsl */ `
    uniform vec3 uColorA;
    uniform vec3 uColorB;
    varying vec3 vNormal;
    varying float vBump;
    void main() {
      float light = max(dot(normalize(vNormal), normalize(vec3(0.5, 0.8, 0.6))), 0.0);
      vec3 base = mix(uColorA, uColorB, vBump * 0.5 + 0.5);
      gl_FragColor = vec4(base * (0.25 + 0.75 * light), 1.0);
    }`,
});

const blob = new THREE.Mesh(new THREE.IcosahedronGeometry(1, 48), material);
scene.add(blob);

renderer.setAnimationLoop((ms) => {
  material.uniforms.uTime.value = ms / 1000;
  blob.rotation.y = ms / 4000;
  renderer.render(scene, camera);
});
</script>

The lighting uses the undisplaced normal, so the bumps are colored but not shaded correctly. Moving vertices changes the surface slope, and the normals must be recomputed to match: analytically (derivative of the displacement function), by displacing two nearby neighbor points and taking a cross product, or per pixel with screen-space derivatives (dFdx/dFdy). That is the same problem as normal estimation in Normal Estimation.

RawShaderMaterial: nothing is added

RawShaderMaterial passes your code to WebGL almost untouched. You declare every attribute, uniform and output yourself, including the precision line. Three.js still sets the built-in uniforms by name if you declare them, so you can use projectionMatrix and modelViewMatrix without computing them. Set glslVersion: THREE.GLSL3 and Three.js adds the #version 300 es line for you, so do not write it yourself.

Use it when you want code that can be pasted into another WebGL program, or when you want to see exactly what the GPU compiles. This example waves a flag: a subdivided PlaneGeometry, displaced in the vertex shader, with the displacement's slope used for shading.

html · try it yourself
<style>body { margin: 0; background: #1a2230 } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 50);
camera.position.set(1.5, 0.4, 2.6);
camera.lookAt(0, 0, 0);
scene.background = new THREE.Color(0x1a2230);

const material = new THREE.RawShaderMaterial({
  glslVersion: THREE.GLSL3,
  side: THREE.DoubleSide,
  uniforms: { uTime: { value: 0 } },
  vertexShader: /* glsl */ `
    precision highp float;
    in vec3 position;
    in vec2 uv;
    uniform mat4 modelViewMatrix;
    uniform mat4 projectionMatrix;
    uniform float uTime;
    out vec2 vUv;
    out float vSlope;
    float wave(float x, float t) { return sin(x * 6.0 - t * 3.0) * 0.18 * x; }   // pole at x = 0
    void main() {
      vUv = uv;
      float x = uv.x;
      vec3 p = position;
      p.z += wave(x, uTime);
      vSlope = wave(x + 0.01, uTime) - wave(x, uTime);                           // how steep here
      gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
    }`,
  fragmentShader: /* glsl */ `
    precision highp float;
    in vec2 vUv;
    in float vSlope;
    out vec4 fragColor;
    void main() {
      vec3 color = vUv.y > 0.5 ? vec3(0.9, 0.2, 0.25) : vec3(0.95);
      if (abs(vUv.x - 0.3) < 0.06 || abs(vUv.y - 0.5) < 0.08) color = vec3(0.15, 0.3, 0.8);
      float shade = 0.8 + vSlope * 25.0;                                        // fake light from the slope
      fragColor = vec4(color * shade, 1.0);
    }`,
});

const flag = new THREE.Mesh(new THREE.PlaneGeometry(2, 1.2, 60, 20), material);
scene.add(flag);
renderer.setAnimationLoop((ms) => {
  material.uniforms.uTime.value = ms / 1000;
  renderer.render(scene, camera);
});
</script>

Choosing between them

ShaderMaterial RawShaderMaterial
Built-in attributes and uniforms declared for you declare the ones you use
precision, #version added write precision; glslVersion: THREE.GLSL3 adds #version 300 es
Three.js shader chunks (#include <fog_fragment>, <colorspace_fragment>, <tonemapping_fragment>) available not available
Portability of the GLSL Three.js only close to plain WebGL2

Both need material.needsUpdate = true if you change the shader strings or defines after the first render, because the program is compiled once and cached.

Note: Neither material is lit by Three.js lights unless you do the lighting yourself, and neither applies the renderer's tone mapping or output color space unless you add #include <tonemapping_fragment> and #include <colorspace_fragment> at the end of a ShaderMaterial's fragment shader. To extend a built-in material instead (keep MeshStandardMaterial's PBR and shadows and change one line), use material.onBeforeCompile to edit its shader source, or the node-based materials (TSL) used by Three.js' WebGPURenderer.

Uniform types

Three.js picks the gl.uniform* call from the JavaScript value:

JavaScript value GLSL type
number float (or int / bool if declared so)
THREE.Vector2 / Vector3 / Vector4 vec2 / vec3 / vec4
THREE.Color vec3
THREE.Matrix3 / Matrix4 mat3 / mat4
THREE.Texture sampler2D
array of numbers or vectors float[N], vec3[N]

Mutate the existing value (uniforms.uColor.value.set(0xff0000)) instead of replacing the object every frame; it avoids garbage and keeps references valid.

Test yourself

Which of these must you declare yourself in a RawShaderMaterial but not in a ShaderMaterial?

  1. Your custom uniforms in the uniforms option
  2. in vec3 position; and uniform mat4 projectionMatrix;
  3. gl_Position
  4. void main()

How do you animate a uniform called uTime on a Three.js shader material?

  1. Recreate the material every frame
  2. Set material.uniforms.uTime.value before rendering
  3. Call gl.uniform1f yourself
  4. Set material.needsUpdate = true every frame

After displacing vertices along their normals, why does the lighting look wrong?

  1. Displacement disables depth testing
  2. The original normals no longer match the new surface slope
  3. normalMatrix is not available
  4. Uniforms are not interpolated