CodeRigor

LESSON

Gradient noise and octaves

Hash a lattice into gradients, blend them with the quintic fade so the surface stays smooth, then stack octaves into fractal terrain noise.

A procedural world needs a function that looks random but has no jumps: ask it for the height at any point and the answer changes smoothly as you move. This lesson is about building that function from nothing but a hash, a few dot products and one easing curve. It pairs with [Unity] Procedural Planets (E03: layered noise) by Sebastian Lague and with What is Perlin Noise? by Acerola, both linked under Watch & read. The first is about layering several noise settings on a planet, the second is an introduction to Perlin noise. You build gradient_noise, fbm and ridged in NumPy and check them against a one-point-at-a-time version and against measured slopes.

Start with a lattice of integer points. Every lattice point gets a pseudo-random unit gradient, a direction chosen by hashing the point's coordinates and a seed. The hash is a few multiplications and xor-shifts on uint32 numbers that wrap around on purpose, and it keeps no table, so the same point always gets the same direction, for any coordinate and in any order of evaluation. Here the low three bits of the hash pick one of eight directions, k·π/4.

To evaluate the noise at (x, y), find the cell: its corner is (⌊x⌋, ⌊y⌋) and the position inside it is (fx, fy) = (x - ⌊x⌋, y - ⌊y⌋). Each of the four corners contributes the dot product of its gradient with the vector from that corner to the point. A corner at distance zero contributes zero, which is why the noise is exactly 0 at every integer point. Then blend: the two bottom values along x, the two top values along x, and those two results along y.

The weights of the blend are the whole story. Plain linear weights (fx and fy) give a surface without jumps, but with creases along every cell border, because the slope on one side of a border is built from different gradients than the slope on the other. Easing the weights with fade(t) = 6t⁵ - 15t⁴ + 10t³ makes the first derivative of the weight zero at both ends of the cell, so each cell hands over to the next with a flat start and a flat end.

Linear weight against the quintic fade
Both curves go from 0 to 1 over one cell. The fade leaves 0 and arrives at 1 with slope 0, so neighboring cells meet without a crease.
Linear weight against the quintic fade
Both curves go from 0 to 1 over one cell. The fade leaves 0 and arrives at 1 with slope 0, so neighboring cells meet without a crease.
Python
def fade(t):
    return t * t * t * (t * (t * 6 - 15) + 10)


print([round(fade(t), 6) for t in (0.0, 0.25, 0.5, 0.75, 1.0)])
h = 1e-6
print(abs(round((fade(h) - fade(0)) / h, 4)), abs(round((fade(1) - fade(1 - h)) / h, 4)))

The next snippet shows the effect in one dimension, with lattice gradients 1.0, 0.5 and -1.0 at x = 0, 1, 2. It measures the slope immediately left and right of the border at x = 1.

Python
import math

def fade(t):
    return t * t * t * (t * (t * 6 - 15) + 10)

def noise(x, w, g=(1.0, 0.5, -1.0)):   # gradients at x = 0, 1, 2
    i, f = math.floor(x), x - math.floor(x)
    a, b = g[i] * f, g[i + 1] * (f - 1)
    return a + w(f) * (b - a)

h = 1e-6
for name, w in (("linear", lambda t: t), ("quintic", fade)):
    left = (noise(1 - 1e-9, w) - noise(1 - 1e-9 - h, w)) / h
    right = (noise(1 + h, w) - noise(1 + 1e-9, w)) / h
    print(name, round(left, 3), round(right, 3))

With linear weights the slope jumps from -0.5 to about 1.5 at the border. With the fade both sides read 0.5, which is the gradient at that lattice point.

One evaluation of gradient_noise
start / 4
The steps for a single point. Only the weights pass through fade; the dot products are blended as they are.
One evaluation of gradient_noise
The steps for a single point. Only the weights pass through fade; the dot products are blended as they are.

A worked example, with corner gradients chosen by hand instead of by the hash. The point sits at (fx, fy) = (0.25, 0.75) in its cell; the corner gradients are (1, 0), (0, 1), (0, -1) and (-1, 0) for the lower-left, lower-right, upper-left and upper-right corners.

Python
corners = {"00": (1, 0), "10": (0, 1), "01": (0, -1), "11": (-1, 0)}
fx, fy = 0.25, 0.75
offset = {"00": (fx, fy), "10": (fx - 1, fy), "01": (fx, fy - 1), "11": (fx - 1, fy - 1)}
dots = {k: g[0] * offset[k][0] + g[1] * offset[k][1] for k, g in corners.items()}
print(dots)
u = fx**3 * (fx * (fx * 6 - 15) + 10)
v = fy**3 * (fy * (fy * 6 - 15) + 10)
bottom = dots["00"] + u * (dots["10"] - dots["00"])
top = dots["01"] + u * (dots["11"] - dots["01"])
print(round(u, 6), round(v, 6), round(bottom + v * (top - bottom), 6))

The four dot products are 0.25, 0.75, 0.25 and 0.75. Because the two rows are equal, the blend along y changes nothing and the answer is the blend along x: 0.25 + 0.103516 · 0.5 = 0.301758. Linear weights would have given 0.375 for the same point.

One octave of noise has a single feature size. Fractal noise adds octaves: octave i samples the noise at lacunarity^i times the coordinates, so its features are smaller, and scales it by gain^i, so they matter less. The sum is divided by the sum of the amplitudes, which keeps the result in the same range as one octave however many you stack. Use a different seed per octave, so that the layers are not copies of one lattice. Ridged noise uses 1 - |noise| for each octave, which turns the zero crossings of the noise into sharp crests.

Python
gain, lacunarity = 0.5, 2.0
for i in range(4):
    print(i, lacunarity ** i, gain ** i)
print(sum(gain ** i for i in range(4)))

The mistakes people make here are few and all quiet. Casting a coordinate to an integer rounds toward zero, so the cell of -0.25 comes out as 0 and its fraction as -0.25; the surface then jumps along every border at negative coordinates, while positive coordinates look fine. Applying the fade to the dot products instead of to the fractions leaves the noise zero at the lattice and still continuous, but the values leave the legal range and the surface is no longer the one described above. Forgetting the division by the amplitude sum makes the range grow with every octave.

The tests check the result in several independent ways: a scalar reimplementation that works on one point at a time, finite differences immediately left and right of cell borders, the value bounds, determinism and seed changes, and negative coordinates. What they cannot tell you is whether the terrain looks good: that is a judgement you make by eye, for example about whether eight gradient directions are enough for your world. A passing hash test shows that the hash mixes its inputs, not that it suits every use.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

A short introduction to Perlin noise as a smooth random function. Watch it before the lesson text for the overall idea, then use the lesson to pin down the lattice, the fade and the octaves.