Shaders From Zero · Episode 05

Noise

Noise is Episode 05 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 05 · Shaders From Zero

If you've ever wondered how shaders make smoke look like smoke and not like a checkerboard, the answer is noise. It is the most important math toolkit in shaders, and once you have it, half of what looks magical in CGI suddenly becomes a one-liner. Fire, water, fog, marble, clouds, terrain, the wood grain on a tabletop, the wrinkles on a forehead — every organic-looking effect you have ever seen in a game or a film is, somewhere in its chain of code, calling a noise function.

This episode is dense. We're going to build noise from the ground up: starting with a one-line hash that fakes randomness, then teaching it to be smooth, then layering multiple copies of it on top of each other, and finally using noise to distort itself. By the end you'll have five techniques in your pocket — and the last one, domain warping, is the engine behind effects so good that they look like cheating.

0 fps
ShaderMaterial · GLSL
hash(vUv * 200.0) — TV static. Random but deterministic.

What noise is, and isn't

The first thing to internalize: noise is not random. A shader runs the same code on every pixel, every frame, every machine. If you fed it true randomness, the picture would flicker every frame and look different every time you refresh. That's not what we want.

What we actually want is a function that takes a coordinate and returns a value that looks random — but is fully deterministic. Same input, same output, forever. Call noise(0.5, 0.7) a million times and you get the same number every time. Call it for the pixel next door at (0.501, 0.7) and you get something close to that number. That last part is the secret.

Smoothness is what separates noise from random-per-pixel garbage. If every pixel pulled an independent random value, you'd get TV static — high-frequency hash that looks the same at any scale. Useful sometimes, but it doesn't look like clouds or fire or anything in the natural world. The natural world has correlation: two points near each other tend to have similar values. Noise functions are random-looking but smooth, and that combination is why they show up in literally every effect that needs to look organic.

Here's the conceptual hierarchy we're going to build:

┌───────────────────────────────────────────────────────────┐ │ hash(p) deterministic chaos. TV static. │ │ │ │ │ ▼ │ │ valueNoise(p) hash a coarse grid, interpolate smoothly │ │ │ │ │ ▼ │ │ gradNoise(p) Perlin-style. No grid artifacts. │ │ │ │ │ ▼ │ │ fbm(p) 5 octaves of noise. Clouds. │ │ │ │ │ ▼ │ │ fbm(p + fbm(p)) domain warping. Anything you want. │ └───────────────────────────────────────────────────────────┘

Each step is built on the one above. You can stop at any rung and you'll have something useful. By the end of the episode we'll have climbed the whole ladder.

The hash function — the primitive that fakes randomness

At the bottom of the noise stack is a function called a hash. It takes any input and returns a number in [0, 1] that has no discoverable relationship to its neighbors. This is the canonical one-liner you'll see in every shader on the internet:

float hash(vec2 p) {
  return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}

It looks like magic. It isn't. Walk through it left to right:

  • dot(p, vec2(127.1, 311.7)) — collapse the 2D coordinate into a single float. The two constants are intentionally weird, ugly numbers; they have no factor relationship to each other, which prevents your hash from accidentally lining up into stripes.
  • sin(...) — chaotic permutation. The sine function is bounded in [-1, 1] but wraps around fast, so even tiny changes in the input produce wildly different outputs.
  • * 43758.5453 — explosion. We multiply by a large, also-ugly number to scatter the result across many decimal places.
  • fract(...) — take only the fractional part, clamping the result to [0, 1].

Stage 1 in the demo just plots this hash directly. Try it. It looks like television static — high-frequency, structureless. That's exactly what you should expect: the hash has no smoothness built in. Every pixel got an independent value.

A caveat for the academically inclined: this is not a real cryptographic hash. It's also not a great statistical hash — there are known patterns and biases if you stare hard enough. None of that matters for graphics. We need something "random enough to fool the eye," and this delivers in one line of GLSL.

You will sometimes see hash functions written with no sin, just integer bit manipulation. Those are technically better — faster, more uniform — but they're harder to read, and most platforms run the sine version fine. Use whichever you remember.

Value noise — hash a grid, interpolate

The problem with raw hash is that there's no correlation between neighbors. The fix is famously simple: instead of hashing every pixel, hash a coarse grid, and smoothly interpolate between the grid corners for everything in between.

That's value noise. Here it is in full:

float valueNoise(vec2 p) {
  vec2 i = floor(p);                 // integer cell
  vec2 f = fract(p);                 // position within cell, [0,1]

  float a = hash(i);                 // corner values, one per cell vertex
  float b = hash(i + vec2(1.0, 0.0));
  float c = hash(i + vec2(0.0, 1.0));
  float d = hash(i + vec2(1.0, 1.0));

  vec2 u = f * f * (3.0 - 2.0 * f); // smoothstep curve on the blend factor

  return mix(mix(a, b, u.x),
             mix(c, d, u.x), u.y);   // bilinear blend, but smooth
}

Three pieces, in order:

  1. floor and fract split the input coordinate into which cell it's in and where it is inside that cell. If p = (3.7, 5.2), then i = (3, 5) and f = (0.7, 0.2).
  2. Four hash calls give us the value at each of the four cell corners. These are the only places noise has "real" data; everything inside the cell is interpolated.
  3. The u = f * f * (3.0 - 2.0 * f) line is the smoothstep curve from Episode 2 — the S-shaped easing. We don't blend linearly between corners, because linear interpolation has visible diamond-shaped seams. The smoothstep curve gives us continuous slopes across the cell boundary.

The double mix at the end is just bilinear interpolation: blend a→b along x, blend c→d along x, then blend those two results along y. Standard 2D interpolation, but with the smoothed blend factor.

Stage 2 in the demo. Same hash function as Stage 1, but now smoothly interpolated across a coarse grid. The result is a blobby, soft pattern — immediately more useful than TV static. You can already imagine this as the basis of an animal-fur texture, or a cloud, or marbling.

Perlin / Simplex — the production-grade alternative

Value noise has one tell. If you stare at it long enough, you'll notice faint grid-aligned bumps — places where the smoothstep curve flattens out at integer coordinates. The pattern leaks through. Most of the time you won't notice. Sometimes you will.

The fix, invented by Ken Perlin in 1985, is to store gradients at the grid corners instead of values. Then, instead of blending corner values, you blend the dot products of each corner's gradient with the offset vector from that corner to the sample point. The math is fiddly but the result has no grid bumps and looks more natural across all scales.

The canonical Ashima / Stefan Gustavson implementation of simplex noise is a hundred lines of tightly-packed swizzles. For this episode we'll use a shorter "gradient noise" formulation from Inigo Quilez, which gives you the visual benefits of Perlin with code you can still read:

// Two-component hash, returning a unit-ish gradient
vec2 hash2(vec2 p) {
  p = vec2(dot(p, vec2(127.1, 311.7)),
           dot(p, vec2(269.5, 183.3)));
  return -1.0 + 2.0 * fract(sin(p) * 43758.5453);
}

float gradNoise(vec2 p) {
  vec2 i = floor(p);
  vec2 f = fract(p);
  vec2 u = f * f * (3.0 - 2.0 * f);

  return mix(mix(dot(hash2(i + vec2(0.0, 0.0)), f - vec2(0.0, 0.0)),
                 dot(hash2(i + vec2(1.0, 0.0)), f - vec2(1.0, 0.0)), u.x),
             mix(dot(hash2(i + vec2(0.0, 1.0)), f - vec2(0.0, 1.0)),
                 dot(hash2(i + vec2(1.0, 1.0)), f - vec2(1.0, 1.0)), u.x), u.y);
}

The structure is identical to value noise — sample four corners, smooth-blend in 2D. The two changes:

  • hash2 returns a vec2 in [-1, 1], treated as a per-corner gradient vector.
  • The corner "value" is now dot(gradient, offset) — the dot product of that corner's gradient with the vector from the corner to the sample point. This is zero exactly at each corner, which is the property that kills the grid artifacts.

One trap: gradient noise returns values roughly in [-0.7, 0.7], not [0, 1]. If you want to use it as a color channel directly, you have to remap with gradNoise(p) * 0.5 + 0.5. We'll do that in Stage 3.

Toggle to Stage 3 and compare with Stage 2. The two look similar, but stare at the boundaries: Stage 2 has subtle square structure, Stage 3 doesn't. At production-grade scale it matters. For learning purposes, value noise is fine most of the time.

FBM — fractal Brownian motion

One layer of noise gives you blobs. Cool, but limited. The natural world isn't made of single-scale blobs — it's made of details on top of details on top of details. Mountains are made of ridges made of bumps made of pebbles. Clouds have wisps inside wisps inside wisps.

The trick to mimic that: sum multiple octaves of noise. Each octave doubles in frequency and halves in amplitude:

float fbm(vec2 p) {
  float v = 0.0;
  float a = 0.5;
  for (int i = 0; i < 5; i++) {
    v += a * gradNoise(p);
    p *= 2.0;       // next octave: twice the frequency
    a *= 0.5;       // ... and half the amplitude
  }
  return v;
}

That's it. That's the whole technique behind clouds, smoke, fire, marble, wood grain, terrain heightmaps, and roughly 80% of the high-end procedural textures you've ever seen.

The 0.5 / 2.0 ratio isn't arbitrary. It's called 1/f noise or "pink noise" — the spectral character that natural phenomena tend to converge on. The sky, biological tissues, the rhythm of human speech, the surface of mountains, all share something like this falloff. Stray from it and the result starts looking artificial. (Some people use 0.5 / 2.02 to break up periodicity from exact octave alignment; a small wobble like that can help.)

Stage 4 in the demo. Five octaves of gradient noise, animated by adding uTime to the input. Now you have clouds. Same code, modulate time differently and you have rolling mist, dust drifting through light, the surface of a stormy ocean from a distance.

Each octave costs a full noise call, so FBM with 5 octaves is roughly 5× the cost of a single noise lookup. That's the practical ceiling for real-time shaders. If you need more detail you're usually better off making each individual octave cheaper than adding more of them.

Domain warping — the trick that makes noise look organic

FBM gets you 80% of the way to anything natural-looking. The last 20% comes from a deceptively simple idea: use noise to displace the coordinates you feed into more noise.

Instead of writing:

float n = fbm(p);

You write:

vec2 q = vec2(fbm(p), fbm(p + vec2(5.2, 1.3)));
float n = fbm(p + q);

That's domain warping. You sample two FBMs (with offset inputs so they're not identical) to build a 2D noise vector, then you add that vector to the coordinates of a third FBM lookup. The third lookup is sampling noise "at a smeared location" — the smear itself is noisy — so the result has the swirling, taffy-like character you can't get from straight FBM.

Stack it twice and it gets even better:

vec2 q = vec2(fbm(p), fbm(p + 5.0));
vec2 r = vec2(fbm(p + q + vec2(1.7, 9.2)),
             fbm(p + q + vec2(8.3, 2.8)));
float n = fbm(p + r);

For Stage 5 we'll keep it to one warp level because the cost compounds: each warp multiplies the number of FBM calls. One warp = 3 FBMs = 15 noise calls per pixel. Two warps = 7 FBMs = 35 calls. Beautiful, but not free.

The definitive reference on domain warping is Inigo Quilez's article at iquilezles.org/articles/warp. It includes the famous "self-warping clouds" example and shows the same technique applied to displacement maps, animation fields, and signed distance functions. If you take one bookmark away from this episode, make it that page.

Toggle the demo to Stage 5. The slow, fluid swirl you see is domain warping in action. There is no fluid simulation under the hood — just noise sampling noise sampling noise. The visual richness comes from feedback, not from any physical model. That's the whole trick.

Common first-day pitfalls

  • Hash with un-floored coords. hash(floor(p)) is intentional — that's how value/gradient noise picks the corner values for one cell. Calling hash(p) directly is also valid; it just gives you Stage 1 (TV static) instead of smoothness. Know which you wrote.
  • Range confusion. Value noise returns [0, 1]; gradient and Perlin noise return roughly [-0.7, 0.7] and never exactly [-1, 1]. Mixing them without remapping will give you washed-out or clipped output. Always know your range and remap with n * 0.5 + 0.5 when you need a color channel.
  • FBM cost. Every octave is another noise call. 5 octaves is the practical max for real-time shaders. If you need 8 octaves your math is probably wrong; tune the base scale before adding layers.
  • Grid artifacts at large zoom. If your value noise looks like a stretched checkerboard, you're sampling at a frequency below 1 cell per pixel. Either zoom out (multiply input by a smaller number) or switch to gradient noise, which hides the grid better.
  • Banding on smooth gradients. 8-bit output channels only have 256 steps, so an extremely smooth noise gradient can show as visible stripes. Adding a tiny per-pixel dither — + (hash(gl_FragCoord.xy) - 0.5) / 255.0 — fixes it cheaply.
  • Time × scale coupling. If you add uTime to the input of a noise call, the noise effectively scrolls at that speed. If you then scale the input, you scale time too. Most of the time you want fbm(p * 4.0 + uTime * 0.1), where the time term is applied after the scale and tuned separately.
  • Floats, always. hash(vec2(1, 0)) won't compile on strict drivers. Write vec2(1.0, 0.0). Every constant. Every time.

Exercises

  1. Take the FBM stage and change the lacunarity (the 2.0 multiplier on p) to 2.5 and the gain (the 0.5 multiplier on a) to 0.4. Compare. Both controls move the noise away from the natural 1/f character; one direction gives sharper detail, the other gives softer rolls. Find the combination you think looks most like real clouds.
  2. Color the domain-warped stage instead of just rendering grayscale. Use the IQ palette function from Episode 4 (a + b * cos(2π * (c * t + d))) with the warped noise as t. You have just rebuilt the famous "warped clouds" demo in 20 lines.
  3. Animate the warp itself: instead of a static offset, write q = vec2(fbm(p + uTime * 0.1), fbm(p + vec2(5.2, 1.3) + uTime * 0.13)). The two slightly different time multipliers make the warp field move independently along x and y, which gives you a slow, breathing fluid motion.

What's next

Episode 06 — SDFs (Signed Distance Fields). We've spent five episodes drawing colors. Time to draw shapes — not by uploading geometry, but by writing a function that, for any point in space, returns the distance to the nearest surface. Once you have that, you can union, intersect, subtract, blur, extrude, and animate shapes with math alone. SDFs are how Shadertoy makes those impossible-looking scenes you've seen, and they pair beautifully with noise — every edge you blur with noise becomes a piece of weather.