Shaders From Zero · Episode 01

What Is a Shader?

What Is a Shader? is Episode 01 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 01 · Shaders From Zero

A shader is a tiny program that runs on your GPU. Not on your CPU — on the thousand-or-so little cores inside your graphics card, all running the same program in parallel. One copy of the program per vertex (for the vertex shader). One copy per pixel (for the fragment shader). That parallelism is why your screen can update sixty times a second with millions of colored pixels and still feel instant.

By the end of this episode you'll have written a shader from scratch, understood why it's split into two stages, and stepped through five progressively more interesting versions of the same square. No prior GLSL knowledge required. We assume you've at least rendered something in Three.js before — a cube, a sphere, anything with a material on it.

0 fps
ShaderMaterial · GLSL
A solid red plane. The simplest possible shader.

The mental model: two programs, one pipeline

The word "shader" is older than what it does. It used to mean "a program that decides how light bounces off a surface." Today it means almost any small GPU program. Three.js gives you direct access to two of them:

  • The vertex shader answers, for each vertex of your geometry, "where on the screen does this point go?"
  • The fragment shader answers, for each pixel that ends up inside a triangle, "what color is this pixel?"

Everything else — the lighting, the textures, the post-processing — is some combination of those two questions, answered cleverly.

Here's the pipeline that ties them together:

┌──────────────┐ attributes (per-vertex) │ Geometry │ ─────────────────────────┐ └──────────────┘ │ ▼ ┌──────────────┐ uniforms (per-draw) ┌──────────────────┐ │ JavaScript │ ──────────────────────▶│ Vertex shader │ └──────────────┘ │ runs 1× per │ │ vertex │ └────────┬─────────┘ │ gl_Position + varyings ▼ ┌──────────────────┐ │ Rasterizer │ (fixed function; │ fills triangle │ you don't touch it) │ with pixels and │ │ interpolates │ │ varyings │ └────────┬─────────┘ │ interpolated varyings, per pixel ▼ ┌──────────────────┐ │ Fragment shader │ │ runs 1× per │ │ pixel inside │ │ the triangle │ └────────┬─────────┘ │ gl_FragColor ▼ pixel

Three things to take away before we write any code:

  1. The vertex shader runs few times (one per vertex; a cube has 24). The fragment shader runs many times (one per pixel covered; a fullscreen quad on a Retina laptop is millions per frame).
  2. You don't write the rasterizer in between. The GPU does that. It also does the interpolation that lets per-vertex data become smoothly-varying per-pixel data.
  3. The only things you must output: a clip-space position from the vertex shader (gl_Position), and a color from the fragment shader (gl_FragColor). Everything else is up to you.

Three kinds of input

Both shaders are pure functions. They take inputs, they produce outputs. The inputs come in three flavors — memorize these, they're the whole API:

KindVaries how often?Example
attribute Once per vertex The vertex's position, normal, uv
uniform Once per draw call A time value, a color, a texture, a transform matrix
varying Set per-vertex, read per-pixel (interpolated) Pass the UV from the vertex shader so the fragment shader can use it

If you ever feel lost in someone else's shader code, sort everything into those three buckets and the structure usually clears up.

The blank canvas: ShaderMaterial

Three.js gives you a material whose entire job is to host shader code:

const material = new THREE.ShaderMaterial({
  uniforms: {
    uTime: { value: 0 },
  },
  vertexShader: /*glsl*/`
    void main() {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: /*glsl*/`
    void main() {
      gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
  `,
});

Put this material on any geometry and you get Stage 1 in the demo: a solid red plane. That's it. That's a complete shader. Twelve lines, two functions, one color.

Two things Three.js does for you here that would be annoying to do by hand:

  • It declares position, normal, and uv as attributes for free — you don't write attribute vec3 position; at the top of your vertex shader.
  • It declares projectionMatrix, modelViewMatrix, modelMatrix, viewMatrix, and cameraPosition as uniforms for free, with the right values plumbed through from the camera.
Power-user note: there's also RawShaderMaterial, which gives you none of that — you declare every attribute and matrix yourself. It exists for when you want WebGL2's GLSL 3.00 syntax with in/out instead of attribute/varying. We won't use it in this series.

Stage 1 — A red square (the minimum viable shader)

Here's the entire shader from Stage 1, annotated:

// VERTEX SHADER
// Runs once per vertex. There are 4 vertices on a plane, so this runs 4 times per frame.

void main() {
  // Take the vertex's position (which Three.js gave us as an attribute),
  // transform it from object space → world space → camera space → clip space.
  // projectionMatrix and modelViewMatrix are uniforms Three.js plumbs in for us.
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

// FRAGMENT SHADER
// Runs once per pixel inside the rasterized triangle.

void main() {
  // Output: red, green, blue, alpha — each in 0.0 to 1.0.
  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

The vertex shader's line is the universal "do nothing, just place the vertex correctly" line. You'll write it a thousand times. Read it left to right: project the model-view transformed vec4 position. The vec4(position, 1.0) turns the vec3 position into a vec4 with w = 1.0 — required for 4×4 matrix math.

The fragment shader is even simpler: every pixel gets the same color. Open the demo, leave it on Stage 1, and verify you see a red square. If you don't, the rest of the episode won't make sense.

Stage 2 — Per-pixel variation with a varying

A solid color is boring. The question now is: how do you make the fragment shader behave differently for different pixels?

The vertex shader can give it information. Specifically: a varying. The vertex shader writes a value at each vertex, and the GPU smoothly interpolates it across the triangle so every pixel gets its own slightly different value.

// VERTEX SHADER
varying vec3 vPos;        // declare the varying

void main() {
  vPos = position;        // write at each vertex
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

// FRAGMENT SHADER
varying vec3 vPos;        // same name, same type

void main() {
  // vPos here is the interpolated position — different for every pixel.
  gl_FragColor = vec4(vPos * 0.5 + 0.5, 1.0);  // remap −1..1 → 0..1
}

Toggle the demo to Stage 2. The square is now a smooth gradient, colored by where each pixel is in object space. Left-bottom is dark, top-right is bright. That smoothness is the rasterizer's interpolation, free of charge.

This is the single most important pattern in shaders: set something in the vertex shader, read it in the fragment shader, and let the GPU do the smoothing. Almost every effect you'll ever write uses it.

Stage 3 — UVs, the texture coordinates that aren't a texture

Object-space position works, but it's awkward. The coordinates depend on the size and shape of your mesh. There's a better default: UVs.

Every Three.js geometry has a uv attribute: a vec2 on each vertex, with values in the range [0, 1] across the surface. A plane has (0,0) at one corner and (1,1) at the opposite. UVs are normally used to look up textures, but you can use them as a plain coordinate system:

// VERTEX SHADER
varying vec2 vUv;

void main() {
  vUv = uv;       // 'uv' is auto-declared by ShaderMaterial
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

// FRAGMENT SHADER
varying vec2 vUv;

void main() {
  // vUv.x goes 0 → 1 across the surface horizontally.
  // vUv.y goes 0 → 1 vertically.
  gl_FragColor = vec4(vUv.x, vUv.y, 0.0, 1.0);
}

Toggle to Stage 3: red rises left to right, green rises bottom to top. The bottom-left corner is black, top-right is yellow. This is the "UV visualization" image that's printed on the wall of every shader programmer's brain. Whenever you write a new effect and something looks wrong, this is the first thing you check.

Stage 4 — Time, the only uniform that matters yet

Now we want the shader to animate. We need a value that the shader can read, that changes every frame, and that comes from outside the shader. That's a uniform.

On the JS side:

const material = new THREE.ShaderMaterial({
  uniforms: {
    uTime: { value: 0 },          // note: boxed in { value: ... }
  },
  vertexShader,
  fragmentShader,
});

renderer.setAnimationLoop((t) => {
  material.uniforms.uTime.value = t * 0.001;  // seconds since start
  renderer.render(scene, camera);
});

On the GLSL side:

// FRAGMENT SHADER
uniform float uTime;
varying vec2  vUv;

void main() {
  // sin oscillates between −1 and 1; remap to 0..1 and mix with vUv.x
  float t = sin(uTime + vUv.x * 6.2832) * 0.5 + 0.5;
  gl_FragColor = vec4(t, t * 0.4, 1.0 - t, 1.0);
}

Stage 4 in the demo. Same UV setup, but now a sine wave traveling across the surface in time. 6.2832 is 2π — it makes one full sine cycle cover the full UV range exactly. That's a number you'll type a thousand times. Some people define #define TAU 6.2832 at the top of their shaders.

Why is uTime boxed inside { value: 0 }? Because Three.js stores uniforms as objects so it can mutate them in place without rebuilding the shader. The number-one beginner mistake is writing material.uniforms.uTime = t — which replaces the object and breaks the binding. Always assign to .value.

Stage 5 — Mixing two colors

One last technique before we close. The mix(a, b, t) function interpolates between two values: when t = 0 you get a, when t = 1 you get b, and anything in between is a smooth linear blend. It works on floats, vec2/3/4, basically everything.

// FRAGMENT SHADER
uniform float uTime;
varying vec2  vUv;

void main() {
  vec3 warm = vec3(1.0, 0.4, 0.1);    // orange
  vec3 cool = vec3(0.1, 0.5, 1.0);    // blue

  float t = sin(uTime + vUv.x * 6.2832) * 0.5 + 0.5;  // 0..1
  vec3 col = mix(warm, cool, t);

  gl_FragColor = vec4(col, 1.0);
}

Stage 5 in the demo: a warm-to-cool gradient that washes across the surface in time. That's a real effect. You'll see this exact pattern behind half the loading screens on the internet.

From here, the next 7 episodes are essentially: "and now we make t more interesting." A noise function makes it organic. A signed distance field makes it shape-aware. A vertex displacement makes it 3D. A post-process makes it apply to the whole screen.

The same five stages, side by side

Take a final look at the demo and step through stages 1 through 5 in order. Notice that the vertex shader never changes after stage 1 — only the fragment shader gets smarter. That's normal for surface effects: most of the visual interest lives per-pixel.

Notice also that the JS side barely changes between stages. The whole "shader workflow" is mostly: write GLSL, pass uniforms, leave the loop alone.

Common first-day pitfalls

  • Black mesh. Your vertex shader doesn't write to gl_Position, your fragment shader doesn't write to gl_FragColor, or there's a GLSL compile error and Three.js fell back to black. Open the console and look for "Shader Error" — it includes the line number.
  • Varying name mismatch. The varying in your vertex and fragment shaders must have identical names and identical types. A vec2 vUv on one side and vec3 vUv on the other will silently break — or worse, compile and render garbage.
  • Uniforms not updating. You wrote material.uniforms.uTime = t instead of material.uniforms.uTime.value = t. The first one detaches the binding; the second one is the only correct form.
  • Implicit float vs int. GLSL is strict. vec3(1, 0, 0) works but vec3(1) * 0.5 sometimes won't — always write 1.0, 0.5, 2.0. If your shader fails with a cryptic message, look for missing decimal points first.
  • "position is not defined." You're on RawShaderMaterial by mistake. Use ShaderMaterial for this series. position, normal, uv are only auto-declared on the cooked version.
  • Looks fine on desktop, wrong on iPhone. Some old mobile GPUs default to mediump precision and your math overflows. Add precision highp float; at the top of your fragment shader. (Three.js adds mediump by default; you're overriding it.)

Exercises

  1. Modify Stage 5 to mix three colors instead of two — a warm, a cool, and a green — based on vUv.x. Hint: use two mix() calls or a single step()-and-pick.
  2. Make the Stage 4 gradient travel vertically instead of horizontally. (One character changes.)
  3. Add a second uniform called uColor (a THREE.Color on the JS side, a vec3 on the shader side) and tint the Stage 1 red square from JS. Verify that changing material.uniforms.uColor.value.setHex(...) from the console updates the cube live.

What's next

Episode 02 — GLSL Essentials. Now that you've seen the structure, we cover the language itself: types (float, vec2, vec3, vec4, mat), swizzles (color.rgb, pos.xy), and the five math functions that appear in 90% of all shaders: mix, step, smoothstep, fract, mod. After Episode 02 you can read any shader on Shadertoy without getting stuck on syntax.