Shaders From Zero · Episode 07
Vertex Shaders
Vertex Shaders is Episode 07 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Every shader in the first six episodes had the same vertex shader: "transform the position, pass through the UV." That was a lie of omission. The vertex shader is just as programmable as the fragment shader — and when you start displacing vertices, you go from drawing on a surface to deforming one. Waves, breathing, exploding, flag-waving — all vertex shader, no geometry update.
This episode wakes the vertex shader up. We swap the plane for a sphere with five thousand vertices, write five vertex shaders of increasing weirdness, and learn the one rule that gates everything: your geometry must have enough vertices to deform. A four-vertex plane displaced by a sine wave looks exactly like an undisplaced plane, because there's nothing in the middle to move. Subdivision is the price of admission.
Drag the demo to rotate. The mesh is an IcosahedronGeometry(1.0, 6) —
about five thousand triangles, smooth enough that displacement actually shows.
What the vertex shader actually does
The vertex shader runs once per vertex of your geometry. If
your mesh has 5,000 vertices, it runs 5,000 times per frame. Three.js auto-declares
the per-vertex inputs for you when you use ShaderMaterial:
// auto-declared, do not write these yourself:
attribute vec3 position;
attribute vec3 normal;
attribute vec2 uv;
Its one mandatory job is to write a value to gl_Position — a
vec4 in clip space, the GPU's standardized "where on the
screen does this point land?" coordinate system. Everything else the vertex
shader does (writing varyings, computing per-vertex colors, etc.) is bonus.
To get from the raw position attribute (which is in object
space — coordinates relative to the mesh's own origin) to clip space, you
multiply by some matrices. Three.js declares all of them as uniforms for free:
| Uniform | Goes from | To |
|---|---|---|
modelMatrix | object space | world space |
viewMatrix | world space | camera space |
projectionMatrix | camera space | clip space |
modelViewMatrix | object space | camera space |
modelViewMatrix is just viewMatrix * modelMatrix
precomputed on the CPU. Use it instead of multiplying both — one matrix multiply
per vertex is half as expensive as two.
Modifying position — the universal pattern
Almost every vertex shader you'll ever write follows this template:
void main() {
vec3 p = position; // 1. copy the attribute
p.y += sin(uTime + p.x * 4.0) * 0.1; // 2. modify
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0); // 3. project
}
Three rules, learned the hard way:
- Always copy
positionto a local first.positionis anattribute, which means it's effectively read-only. Writing to it directly is a compile error. - Modify before you project. The matrix multiply is the last thing you do. If you displace after, you're trying to manipulate clip-space coordinates, which is rarely what you want and very hard to reason about.
- Stay in object space when you can. The pattern moves with the mesh: if you rotate the mesh, the wave rotates with it, which is almost always what you want. World-space patterns look static on a moving mesh — a different effect, occasionally useful, rarely the default.
Why your geometry needs enough vertices
This is the single most common reason vertex shader code "doesn't work" the first time. You wrote a beautiful sine wave displacement, ran the demo, and the plane looks completely flat. The code is correct. The geometry is wrong.
A vertex shader can only move vertices that exist. A
PlaneGeometry(1, 1, 1, 1) has exactly four vertices — one at each
corner. Your sine wave displaces those four corners by some amount, and the
rasterizer linearly interpolates the triangles between them. Linear
interpolation between four corner offsets does not look like a sine wave. It
looks like a flat plane that's been tilted slightly.
The fix is subdivision. PlaneGeometry(1, 1, 64, 64) has 4,225
vertices arranged in a 65×65 grid. Now your sine wave has somewhere to land
between the corners. For this episode we use
IcosahedronGeometry(1.0, 6) — a high-poly sphere with about 5,000
triangles, which gives a nice volumetric shape to deform.
Rule of thumb: if you can see the polygon edges of your geometry in the displaced result, you don't have enough vertices. Bump the subdivision until the silhouette looks smooth.
Sine wave displacement
The simplest displacement is a sine of one coordinate, added to another. "As you walk across the X axis, push the surface up and down":
void main() {
vec3 p = position;
p.y += sin(p.x * 4.0 + uTime) * 0.1;
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
}
That gives you a flag. The wave travels along X because uTime
is added to p.x * 4.0 — increase time, the same phase value moves
leftward across the surface.
For a circular ripple (a stone dropped in water), use the radial distance from the center as the input:
void main() {
vec3 p = position;
float w = sin(length(p.xz) * 6.0 - uTime * 3.0);
p.y += w * 0.1;
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
}
Same idea: take a scalar derived from position, pass it through
sin, multiply by an amplitude, add it to one axis. From here the
variations are endless — multiple sines stacked, different frequencies per
axis, noise instead of sine.
Noise-based displacement
Sine waves look like sine waves. For something organic — a beating blob,
a wind-disturbed surface, a soft glob — use noise. The hash and value-noise
helpers from Episode 5 work identically in the vertex shader; just paste them
in above main.
The interesting new choice is the direction of displacement. Two common patterns:
// Pattern A: displace along the vertex normal
vec3 p = position;
float n = valueNoise(p * 2.0 + uTime * 0.3);
p += normal * (n - 0.5) * 0.15;
// Pattern B: displace along a fixed world axis
vec3 p = position;
float n = valueNoise(p * 2.0 + uTime * 0.3);
p.y += (n - 0.5) * 0.15;
Pattern A inflates each vertex outward by a noise amount — the shape grows and shrinks coherently, perpendicular to the surface. It looks like a breathing creature.
Pattern B pushes every vertex in the same direction (up) regardless of where it sits on the surface. The top of the sphere swells, the bottom indents. It looks like wind blowing across.
Most "organic" effects use along-normal. Most "directional" effects use a fixed axis. The choice is purely aesthetic; the code change is one line.
Recomputing normals — and why we mostly punt
Here's an inconvenient truth nobody warns you about: once you displace
the vertices, the normals are wrong. The normal attribute
on each vertex was baked into the geometry at creation time, computed for the
original shape. Move the vertices, and those normals no longer point
perpendicular to the actual deformed surface.
For lit materials, this is a real problem. Shadows fall in the wrong places.
Specular highlights stay anchored to the undisplaced shape. A bumpy noise blob
rendered with MeshStandardMaterial looks like a smooth sphere with
confused shading on top.
There are two real fixes, both out of scope for this episode:
- CPU recompute. Update the vertices on the CPU each frame,
call
geometry.computeVertexNormals(), and re-upload. Slow, defeats the point of doing it on the GPU. - Analytic recompute in the shader. Use
dFdxanddFdyin the fragment shader to derive a per-pixel normal from neighboring pixels' positions, or compute the displacement at three nearby points in the vertex shader and reconstruct the normal from the cross product. Both work; both add complexity.
For this episode we sidestep the problem entirely by rendering with an unlit fragment shader that colors by the original vertex normal and by the displacement amount. There's no concept of "shadow" or "specular," so there's nothing to be wrong. This is also a useful real-world technique: stylized renders that color by surface direction look good and never need normal recompute.
Per-vertex color via varying
Once you're displacing vertices, you usually want the fragment shader to know by how much, so it can tint the surface accordingly. Standard varying setup:
// VERTEX SHADER
varying float vDisp;
varying vec3 vNormal;
void main() {
vec3 p = position;
float disp = sin(p.x * 6.0 + uTime * 2.0) * 0.15;
p.y += disp;
vDisp = disp; // pass amount to fragment
vNormal = normal; // pass original normal too
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
}
// FRAGMENT SHADER
varying float vDisp;
varying vec3 vNormal;
void main() {
vec3 warm = vec3(0.95, 0.55, 0.2);
vec3 cool = vec3(0.2, 0.55, 0.95);
vec3 col = mix(cool, warm, vDisp * 0.5 + 0.5);
gl_FragColor = vec4(col, 1.0);
}
This is the "high points are warm, low points are cool" effect, and it's
the single best way to verify that your displacement is actually doing
something. If the surface stays one color, you forgot to write
vDisp or the displacement is too small. If it flickers wildly,
the displacement is too large or the noise frequency is too high.
Common first-day pitfalls
- Modifying
positionin place. Thepositionattribute is effectively const; the shader won't compile if you assign to it. Always copy to a local:vec3 p = position;. - Too few vertices. Your math is correct, your displacement
is invisible.
PlaneGeometry(1, 1, 1, 1)has four vertices. Bump it to(1, 1, 128, 128)or use a higher-subdivision primitive. - Forgetting to pass world position via varying. If your
fragment shader needs the displaced position (for fog, for distance
fades, for matching a screen-space effect), pass it explicitly as a varying.
The fragment shader has no access to the modified
potherwise. - Lit material with no normal recompute. Surface looks flat-shaded even when displaced because the lighting reads from stale normals. Either switch to unlit or recompute normals.
- World-space displacement on a moving mesh. If you displace
based on
(modelMatrix * vec4(position, 1.0)).xyz, the pattern is anchored in world space — translate the mesh and the pattern swims across it. Use the localpositionfor patterns that move with the object. - Tiny
uTimemultiplier with huge amplitude. The mesh visibly jitters frame-to-frame because the displacement is changing too fast relative to its size. Lower the amplitude or smooth the input — for example multiplyuTimeby a small constant like 0.3 before using it insidesin.
Exercises
- Stack two sine waves at different frequencies and axes in Stage 2:
p.y += sin(p.x * 6.0 + uTime) * 0.1 + sin(p.z * 9.0 + uTime * 1.3) * 0.05;. Notice that combining two cheap waves looks more interesting than one expensive one. - In Stage 4 (exploding), change the
hash(position * 5.0)tohash(position * 1.5). Each vertex now groups with its neighbors, and the explosion forms chunks instead of spikes. Hash frequency = chunk size. - Add a
uMouseuniform (avec2from JS) and use it to bias one of the displacement stages — for example, make Stage 3's noise frequency depend onuMouse.x. Episode 8 covers mouse uniforms in detail; this is a sneak preview.
What's next
Episode 08 — Time, Easing & Animation. We've used
uTime as a raw input to sin all series. Next episode
we treat time as a first-class design tool: easing curves
(smoothstep, cubic, elastic), staggered animations across a mesh,
one-shot triggers, and mouse-driven interaction. By the end of Episode 8 your
shaders will respond, not just oscillate.