Shaders From Zero · Episode 11
Water Surface
Water Surface is Episode 11 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Water in real-time graphics is mostly a lie — a smart sum of sine waves plus a few
coloring tricks. Real ocean simulation uses FFTs and runs on the CPU of a render farm.
Real-time water uses Gerstner waves. They're math you already know —
sin and cos — arranged in a specific way that makes the wave
peaks sharper than the troughs, the way real water looks.
By the end of this episode you'll have a horizontal plane that ripples convincingly,
colors itself deep blue in the troughs and cyan at the peaks, catches a warm sky tint
on the highlights, and breaks into white foam at the very tops. Everything in one
ShaderMaterial, vertex-displaced, fragment-colored. Drag to orbit the camera.
The five layers
Water is a stack. Each layer fixes something the previous one couldn't do alone:
- Flat plane. The baseline — no displacement, no color trick. Just proves the geometry is in front of the camera.
- One Gerstner wave. Pure vertex displacement. The shape is correct but the pattern is regular and obviously a single wave.
- Layered Gerstner waves. Three or four octaves at different scales and directions. The regularity breaks up and starts looking like water.
- Depth-based color. Warmer / lighter at peaks, deeper blue at troughs. Sells the volume even with no real lighting.
- Foam at the highest peaks. A bright white band where the displacement passes a threshold. Adds the final visual punch.
The article runs through these in order. Each builds directly on the previous one's GLSL — by the end you can read the final shader top to bottom and recognize every term.
Gerstner waves — the math
The naive way to make a surface ripple is to displace each vertex along Y by
sin(time + x). Try it and you'll get a wave, but it'll look wrong — too
soft, too symmetric. Real water has sharp peaks and broad troughs.
The water spends most of its time low, and only briefly high.
Gerstner waves get this right with a small trick: they displace each vertex in two directions at once. A horizontal nudge toward the wave's peak, and a vertical nudge up. As the wave passes a vertex, the vertex traces a tiny circle — not just an up-down line. That circular motion is what produces the asymmetric peak-and-trough shape.
The formula. Given a wave direction d (a unit 2D vector in the XZ
plane), an amplitude a, a wavelength L, and a speed:
vec3 gerstnerWave(vec3 pos, vec2 dir, float amplitude,
float wavelength, float speed, float time) {
float k = 6.2832 / wavelength; // wave number, 2π / L
float c = sqrt(9.8 / k); // dispersion: long waves go faster
vec2 d = normalize(dir);
float f = k * (dot(d, pos.xz) - c * speed * time);
float a = amplitude;
return vec3(d.x * (a * cos(f)), // X offset toward peak
a * sin(f), // Y offset (height)
d.y * (a * cos(f))); // Z offset toward peak
}
Three things worth unpacking:
- Wave number
k. A standard physics convention: a wavelength ofLmeters hask = 2π / Lradians per meter. A small wavelength → largek→ tightly packed wave fronts. - Dispersion
c = sqrt(9.8 / k). Real ocean waves propagate at a speed that depends on wavelength — long swells move fast, ripples move slow. The9.8is gravity. You don't have to use this; you can hard-code a speed. But it makes the layered waves feel right because the big ones overtake the small ones the way they would in the real world. - The phase
f = k * (dot(d, pos.xz) - c * speed * time). Project the vertex onto the wave direction withdot(d, pos.xz). That gives a 1D coordinate along the wave. Multiply byk, subtract a time term, and that's your sine input. The subtraction is what makes the wave travel.
Add the returned vec3 to position in your vertex shader.
All three components are nonzero — that's the point.
Side note: the formula usescosfor horizontal andsinfor vertical. They're 90° out of phase, which is exactly what makes a vertex trace a circle rather than a line. If you swap them, the wave goes backward. If you make them bothsin, you get the boring symmetric wave.
Layering Gerstner waves
A single Gerstner wave already looks more like water than a pure sine. But it's still obviously a single wave, marching in one direction, with one frequency. Real water is a sum of waves at different scales, going in different directions, moving at different speeds. The trick is to layer 3 to 5 of them.
vec3 offset = vec3(0.0);
offset += gerstnerWave(position, vec2(1.0, 0.0), 0.05, 1.00, 1.0, uTime);
offset += gerstnerWave(position, vec2(0.7, 0.7), 0.03, 0.60, 1.5, uTime);
offset += gerstnerWave(position, vec2(-0.4, 0.9), 0.02, 0.35, 2.0, uTime);
vec3 p = position + offset;
Notice the pattern: each successive wave has a smaller amplitude, a shorter wavelength, and a different direction. This is exactly how you'd layer fractal noise (Episode 05) — smaller, faster, more detail on top of the big slow stuff.
Why does this work? Because a small smooth function plus another small smooth function at a different frequency isn't smooth anymore. The interference produces the irregular crests and broken patches that read as "water." If every wave went the same direction, you'd just get a more complicated 1D pattern. The different directions are what give it depth.
Three or four octaves is plenty for a stylized look. Real ocean shaders sometimes use 16 — at which point you start thinking about precomputing them into a texture, but that's a different episode.
Depth-based color
You have a rippling plane. Color it solid blue and it'll look like a rippling napkin. The next trick: color the troughs differently from the peaks.
To do that we need to know, in the fragment shader, how high each pixel's underlying vertex was displaced. Pass it as a varying:
// VERTEX SHADER
varying float vHeight;
void main() {
vec3 offset = ...; // from the layered Gerstner code above
vec3 p = position + offset;
vHeight = offset.y; // just the vertical displacement
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
}
// FRAGMENT SHADER
varying float vHeight;
void main() {
vec3 deep = vec3(0.0, 0.15, 0.4); // trough color
vec3 surf = vec3(0.2, 0.6, 0.9); // peak color
vec3 col = mix(deep, surf, smoothstep(-0.05, 0.05, vHeight));
gl_FragColor = vec4(col, 1.0);
}
The smoothstep(-0.05, 0.05, vHeight) takes the displacement (which
ranges roughly from -0.10 in deep troughs to +0.10 at peaks)
and remaps it smoothly to 0..1. mix then blends the deep blue
into the surface cyan.
This is a cheat, of course. In real water, troughs look deeper because more light is absorbed by the water column under them. We're not doing any light transport — we're just explicitly coloring low spots dark and high spots light. The eye buys it completely. This single trick is what separates "swimming pool tile" from "actual water" in most stylized 3D scenes.
Sky reflection (the cheapest trick that works)
Real water reflects the sky. The proper way to do this is a cubemap — you sample
a panorama texture using a reflection vector computed from the surface normal and the
camera direction. Three.js exposes this through
THREE.CubeTextureLoader and envMap on a MeshStandardMaterial.
For physically-based water you want all of that.
But for stylized water? A much cheaper trick gets 80% of the visual benefit:
tint the highlights warm. The brightest parts of water — the parts that catch
the sun — should be warm and bright. The rest stays cool. You can drive this with the
same vHeight varying you already have:
float highlight = smoothstep(0.04, 0.08, vHeight);
vec3 sky = mix(col, vec3(1.0, 0.95, 0.8), highlight * 0.5);
The high points get a touch of warm cream. The * 0.5 keeps it from
overpowering the blue. The brain reads it as sunlight catching the wave crests and
fills in the rest — sky, sun, even time of day — for free.
Power-user upgrade: replace this with a real env map. Load a sky cubemap withTHREE.CubeTextureLoader, compute a reflection vector (reflect(viewDir, normal)), and sample the cubemap. You'll need actual normals from the wave gradient instead of just the height. The shape of the code is the same — only the source of the "sky color" changes.
Foam at the wave peaks
The final layer. Foam is just a bright white band at the very top of each
wave. One more smoothstep:
float foam = smoothstep(0.07, 0.09, vHeight);
col = mix(col, vec3(0.95, 0.95, 0.9), foam);
The tuning of the smoothstep range is everything here:
- Too narrow (
smoothstep(0.085, 0.090, vHeight)) — the foam is a razor-thin line that looks like a rendering artifact. - Too wide (
smoothstep(0.02, 0.09, vHeight)) — the entire upper half of every wave is white and the water looks like cream. - Just right — a soft white cap on the topmost 20% of each crest. You see it catch the wave as it forms, like real ocean foam.
The trick is that the threshold is just under the maximum amplitude of your
summed waves. If your three waves sum to roughly 0.10 at their peaks,
set the foam range somewhere around 0.07–0.09. Crank the wave amplitudes
later and you'll need to retune.
Common pitfalls
- Plane subdivision too low. The math is correct but the
displacement is invisible — a plane with 1×1 segments has only 4 vertices and
can't bend at all. Use
PlaneGeometry(8, 8, 256, 256). That's 66,049 vertices, which is fine. Lower it if you see CPU stalls; raise it if you see polygonal facets. - Normals not recomputed. The plane's normals are all
(0, 1, 0)regardless of how you bend it. If you use a lit material (MeshStandardMaterial), the lighting will be flat-wrong. We avoid this by not using lighting at all — color is driven byvHeightdirectly. Call this out in your own code. - Wave amplitude too high. Crank the amplitudes past
~0.15and the horizontal Gerstner offset gets so large that vertices cross through each other. You'll see a chaotic clipped mesh. Either lower the amplitudes or shorten the wavelengths to compensate. - Single wave direction. One Gerstner wave at one direction
looks like a corrugated roof. Always layer at least three directions. The set
(1,0),(0.7, 0.7),(-0.4, 0.9)is a good starting trio — no two parallel, no two perpendicular. - UV seams. If you were tiling a noise texture, you'd worry
about wrapping. Gerstner is positional — it uses
pos.xzdirectly, notuv— so there's no seam to worry about. The same wave continues smoothly across the entire plane.
If you do want lit water with correct normals: differentiate the Gerstner formula
analytically, accumulate the tangent and binormal contributions from each layer,
then normal = normalize(cross(B, T)). It's not hard, just verbose.
Most stylized water skips it and relies on height-driven coloring like we did.
Exercises
- Storm mode. Double every amplitude in the layered Gerstner
call (
0.10,0.06,0.04). Retune the foam and depth thresholds so the foam still appears on the new peaks and the depth contrast still reads. What does the water look like? What breaks? - Sunset palette. Swap the deep blue / cyan / cream colors for
a sunset version — purple troughs, orange peaks, hot yellow highlights, and use
scene.background = new THREE.Color(0x2a0a14)for a warmer sky. - Per-vertex jitter. Pull in a noise function from Episode 05
and add a small
vec3(0, noise(pos.xz + uTime) * 0.01, 0)on top of the Gerstner displacement. Does the surface look more or less like water?
What's next
Episode 12 — Glass & Refraction. Water is at its core a refractive material, and we faked all of that with color tricks. Next episode we look through a surface instead of bouncing light off it: index of refraction, Snell's law in a fragment shader, and the screen-space refraction trick that gives you cheap glass without raymarching.