Algorithmcore
Perlin noise
Also called gradient noise, improved Perlin noise.
A smooth pseudorandom function made by interpolating random gradients at the points of an integer lattice with a quintic fade curve.
- Time
- Θ(q n 2^n) worst
- Space
- Θ(1) extra
- Where
- n = the dimension of the domain; q = the number of points at which the noise is evaluated
- Model
- Real RAM
- Properties
- deterministicnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ken Perlin, 1985
Perlin noise is a pseudorandom function on that is smooth, has no visible structure at a large scale, and has most of its variation at the scale of one lattice cell. At each point of the integer lattice it fixes a random gradient vector. At any other point it blends the linear functions of the corners of the cell, with a fade curve as the weight. The function is zero at every lattice point and repeats with a period of 256 in each axis. It is the base of most procedural textures, and of fractal noise, which sums it at many scales. This page gives the improved version of Perlin (2002) in three dimensions. Simplex noise is a later noise of Perlin that sums over the corners of a simplex, and Worley noise is a different basis made of distances to random points.
In plain words
You want a random pattern for marble, clouds or rough stone, but white noise looks like television static, and a texture image repeats and costs memory. Perlin noise is a formula that you can evaluate at any point.
Think of a grid of posts. On top of each post sits a small tilted plane, and the tilt is random. To get the value at a point, find the cell of the grid that holds it. Each corner of the cell gives the height of its tilted plane at that point. Then blend the corner heights, with a smooth curve that gives more weight to the nearer corners. The result is a gentle surface of hills and valleys, about one cell wide, that passes through zero at each post. The same point always gives the same value, so the pattern stays fixed on the object.
The problem
The input is a point and a permutation of . In the code, comes from a seeded Fisher-Yates shuffle, and it is stored twice, as with , so that sums of indices need no reduction. The output is a real number . The required properties are: is deterministic for a fixed , it is , it is 0 at the lattice points, its gradient at a lattice point is the gradient that the hash gives that point, and its values in different cells are not correlated beyond the neighbors.
The gradient set holds the 12 vectors from the center of a cube to the midpoints of its edges, , and , and four of them again, , , and , for 16 entries. With 16 entries the index is , a bit mask.
The algorithm
PERLIN-NOISE(x, y, z, P) ▷ P: a permutation of 0..255, stored twice- 1
(X, Y, Z) ← (⌊x⌋ mod 256, ⌊y⌋ mod 256, ⌊z⌋ mod 256) - 2
(x, y, z) ← (x - ⌊x⌋, y - ⌊y⌋, z - ⌊z⌋) ▷ the position in the unit cell - 3
(u, v, w) ← (FADE(x), FADE(y), FADE(z)) - 4
for each corner (a, b, c) in {0, 1}^3 do - 5
h ← P[P[P[X + a] + Y + b] + Z + c] ▷ the hash of the corner - 6
n[a, b, c] ← GRAD(h, x - a, y - b, z - c) - 7
blend the 8 values n with lerp in x by u, then in y by v, then in z by w - 8
return the blended value FADE(t)- 9
return 6t^5 - 15t^4 + 10t^3 GRAD(h, x, y, z)- 10
return G[h mod 16] · (x, y, z)
Here . In the code the hashes of line L5 share their inner lookups, as in Perlin's reference code: , , and so on. GRAD in the code uses bit tests in place of the table, which give the same 16 vectors with no multiplication.
The fade has , and zero first and second derivatives at 0 and 1. So a corner has the full weight at its own lattice point, no weight on the far side of the cell, and the weight changes with no jump in its first two derivatives across a cell face.
Example
Take the point in the cell of the origin, and the permutation of seed 0 in the code. Its hash gives the corner gradients , , and . Since , the weight , and the four corners with do not count.
| corner | offset $p - $ corner | offset |
|---|---|---|
The fades are and . The lerp in gives on the edge , and on the edge . The lerp in gives . At the corner itself, every offset either is zero or has a component of absolute value 1, where the weight is 0, so .
Correctness
The proof file shows four facts in exact arithmetic. First, the nested lerps of line L7 equal the sum, over the 8 corners, of the corner value times a product of fades, one per axis. Second, this is the same as a sum over all lattice points of a kernel times , where on and 0 outside. The kernel is because and vanish at 0 and 1, so is , its value at a lattice point is 0, and its gradient there is . Third, in three dimensions, because each corner value is at most 2 and the weights are convex. Fourth, has the period 256 in each axis, because line L1 reduces the cell index modulo 256.
Proof: Improved Perlin noise is a C2 sum of lattice kernels that vanishes at the lattice pointsfull
We use the pseudocode and the notation of the page, in dimensions. The proofs for other dimensions are the same with corners. Let be the fade, and for each lattice point let be the gradient that the permutation gives to (the function corner_gradient of the code). Arithmetic is exact (real-ram).
Lemma 1 (the fade). , , for all , and . On , is nondecreasing, so .
Proof. and . Both vanish at 0 and 1. The values at 0 and 1 follow by substitution. The polynomial has the derivative , so it is constant, and its value at is . Last, everywhere.
Lemma 2 (the nested lerps are a tensor product sum). Let lie in the cell with , and let . Lines L3 to L8 return
with and .
Proof. Line L5 computes the hash of the corner , and line L6 its value , because GRAD returns the dot product with the gradient of index (the code test test_grad_matches_table lists all 16 cases). . Line L7 applies the lerp in to each of the four pairs, then in , then in . Expanding the three levels gives each corner value exactly once, multiplied by one weight per axis.
Lemma 3 (one kernel per lattice point). Let for and for , and let . Then for every
Proof. Fix in the cell of with . A lattice point with in some axis has . A point with exactly also gives . So only the 8 corners remain, with . For , . For , by Lemma 1. The same holds in and , so the sum is the sum of Lemma 2.
Theorem 1 (zeros at the lattice). for every .
Proof. By Lemma 3, a lattice point differs from by at least 1 in some axis, so . The term of itself is .
Theorem 2 (smoothness). is twice continuously differentiable on , and at every lattice point .
Proof. The function is on . On it is the polynomial , and on the polynomial . At both pieces have the value 1, the first derivative and the second derivative . At the pieces have the value , the first derivative and the second derivative , which match the zero function outside. So is , each term is , and on any bounded set only finitely many terms are not zero. So is . At a lattice point , every other term has and , because and vanish at and , so each component of holds one factor or . The term of has the gradient .
With the cubic fade of Perlin's 1985 noise, and . Then just inside and outside, so jumps by 6 there. So is only , and its second derivative jumps on the cell faces. This is the reason for the quintic fade.
Theorem 3 (a bound on the range). for every .
Proof. Each gradient has two components equal to and one equal to 0. Each offset has components in . So each corner value is at most in absolute value. By Lemma 1 the weights are in and , so the 8 products in Lemma 2 are nonnegative and sum to 1. A convex combination of numbers in lies in .
The bound is not tight. A corner value of 2 needs an offset with two components of absolute value 1, and where an offset component has absolute value 1, the weight of that corner is 0.
Theorem 4 (the period). for each unit axis vector .
Proof. Line L1 reduces the cell index modulo 256, and line L2 does not change under an integer shift. The table has 512 entries with , so the hashes of line L5 depend only on the cell index modulo 256. So every quantity in lines L3 to L8 is the same at and at .
Cost. Lines L1 to L3 take operations. The loop runs over corners. Each corner takes table lookups and a dot product of length , so . Line L7 takes lerps. The total is operations per point, which is for the fixed of the code.
Complexity
In dimensions one evaluation visits the corners of the cell, and each corner costs table lookups and a dot product of length . The blend is lerps. So one point costs operations, and points cost , in the real-RAM model. In three dimensions this is 8 corners and 7 lerps, a constant. The table takes 512 entries. On a GPU the table is a small texture or a hash function in the shader. Simplex noise costs per point, which is less for .
Properties
- Band limited in practice. Most of the energy lies near the frequency of one cell, so the noise can be scaled to a chosen feature size and summed at several scales without much overlap. It is not strictly band limited: the fade and the lattice add higher frequencies.
- Zero at the lattice. for . A sample on the integers gives a constant image.
- Range. The proved bound is . It is not tight: on 200000 random points with seed 0, the largest absolute value is . Do not assume the range without a scale and a clamp.
- Period. The pattern repeats every 256 units in each axis.
- Axis bias. The cells are cubes, and the 12 gradients lie in the coordinate planes, so the noise has slight directional features along the axes. Simplex noise has less of this.
Variants and improvements
- Original noise (1985). A table of random unit gradient vectors and the cubic fade . Its second derivative jumps on the cell faces, which shows as artifacts in bump mapping, where the shading uses the derivative of the noise.
- Value noise. Random values, not gradients, at the lattice points, interpolated in the same way. It is cheaper but looks more blocky, and it is not zero at the lattice.
- Analytic derivatives. Differentiate the sum of Lemma 2 in the proof file to get with the value, which bump mapping and terrain need.
- Tiling noise. Reduce the cell index modulo a period before the hash, so that the noise tiles on a texture of cells.
- Hash in place of a table. GPU code often replaces by an integer hash of the cell coordinates.
- Higher dimensions. Four-dimensional noise animates a three-dimensional pattern in time. Its cost is 16 corners, which is one reason for simplex noise.
When to use it
Use Perlin noise for procedural textures, terrain heights, cloud density, and to perturb other textures or animation curves. Use it as the base octave of fractal noise and turbulence. Use simplex noise in four or more dimensions, or when the axis bias is visible, and Worley noise for cell-like patterns such as stone, scales or foam. When the texture is fixed and the memory is free, a stored texture with mipmaps is cheaper to sample.
Pitfalls
- Truncation in place of floor. A cast to an integer rounds toward zero in C and many shader languages. For negative coordinates this gives the wrong cell and a seam at 0. Use floor, as in lines L1 and L2.
- Integer sample points. Sampling at integer coordinates, or at a scale that maps the pixels to integers, gives zeros.
- Precision far from the origin. With 32-bit floats, loses bits when is large, and the noise becomes blocky. Keep the coordinates small, or wrap them by the period first.
- Assuming a range. The range depends on the dimension and the gradient set. Scale and clamp by a measured or proved bound.
- Aliasing. Noise at a frequency above half the pixel rate aliases. In a fractal sum, drop the octaves that are finer than a pixel. See aliasing.
- A different table on each machine. The pattern depends on . To get the same texture on every run and platform, fix the seed or the table.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/perlin-noise/. The authors are listed in prov/QWP9HR.jsonl.
"""Improved Perlin noise in 3D (Perlin 2002).
The lattice is the integer grid. A permutation P of 0..255, doubled to 512
entries, hashes each lattice point to one of 16 gradient vectors: the 12
vectors from the center of a cube to the midpoints of its edges, and 4 of
them again, so that the index is h & 15. The value at a point is the
trilinear blend, with the quintic fade 6t^5 - 15t^4 + 10t^3 as the weight,
of the 8 corner values g . (p - corner).
Perlin's reference code uses one fixed table for P. This module makes P from
a seed with a Fisher-Yates shuffle, so different seeds give different noise.
"""
import random
from math import floor
# Index h & 15 -> gradient. The order is that of the bit tests in Perlin's
# reference code: entry h is (u-sign, v-sign) applied to the chosen axes.
GRADIENTS = (
(1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0),
(1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1),
(0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1),
(1, 1, 0), (0, -1, 1), (-1, 1, 0), (0, -1, -1),
)
def make_permutation(rng):
"""Return a list of 512 entries: a random permutation of 0..255, twice."""
p = list(range(256))
rng.shuffle(p)
return p + p
def fade(t):
"""The quintic fade 6t^5 - 15t^4 + 10t^3."""
return t * t * t * (t * (t * 6 - 15) + 10) # @line L9
def grad(h, x, y, z):
"""Dot product of gradient h & 15 with (x, y, z), as in Perlin's code."""
h &= 15 # @line L10
u = x if h < 8 else y
v = y if h < 4 else (x if h in (12, 14) else z)
return (u if h & 1 == 0 else -u) + (v if h & 2 == 0 else -v)
def lerp(t, a, b):
return a + t * (b - a)
def noise(x, y, z, perm):
"""Improved Perlin noise at (x, y, z) for a doubled permutation perm."""
fx, fy, fz = floor(x), floor(y), floor(z)
X, Y, Z = fx & 255, fy & 255, fz & 255 # @line L1
x, y, z = x - fx, y - fy, z - fz # @line L2
u, v, w = fade(x), fade(y), fade(z) # @line L3
p = perm
# The 8 corners, with the hashes nested as in Perlin's code.
a = p[X] + Y # @line L4
aa, ab = p[a] + Z, p[a + 1] + Z # @line L5: P[P[P[X + a] + Y + b] + Z + c] shares lookups
b = p[X + 1] + Y
ba, bb = p[b] + Z, p[b + 1] + Z
# The 8 corner values g . (p - corner).
n000 = grad(p[aa], x, y, z) # @line L6
n100 = grad(p[ba], x - 1, y, z)
n010 = grad(p[ab], x, y - 1, z)
n110 = grad(p[bb], x - 1, y - 1, z)
n001 = grad(p[aa + 1], x, y, z - 1)
n101 = grad(p[ba + 1], x - 1, y, z - 1)
n011 = grad(p[ab + 1], x, y - 1, z - 1)
n111 = grad(p[bb + 1], x - 1, y - 1, z - 1)
return lerp(w, # @line L7
lerp(v, lerp(u, n000, n100), lerp(u, n010, n110)),
lerp(v, lerp(u, n001, n101), lerp(u, n011, n111))) # @line L8
def corner_gradient(i, j, k, perm):
"""The gradient vector that perm assigns to the lattice point (i, j, k)."""
p = perm
h = p[p[p[i & 255] + (j & 255)] + (k & 255)]
return GRADIENTS[h & 15]
class PerlinNoise:
"""Seeded 3D improved Perlin noise."""
def __init__(self, seed=0):
self.perm = make_permutation(random.Random(seed))
def __call__(self, x, y, z=0.0):
return noise(x, y, z, self.perm)
test_perlin_noise.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/perlin-noise/. The authors are listed in prov/QWP9HR.jsonl.
"""Tests of improved Perlin noise.
The nested lerps of the implementation are checked against a direct sum of
the 8 corner terms with tensor product weights, exactly on rational points.
The tests also check the zeros at the lattice points, the gradient there,
the fade conditions, the period 256, determinism for a seed and the bound 2.
"""
import random
from fractions import Fraction
from math import floor
from perlin_noise import GRADIENTS, PerlinNoise, corner_gradient, fade, grad, noise
def reference(x, y, z, perm):
"""Sum over the 8 corners of w_a(x) w_b(y) w_c(z) g . (p - corner)."""
fx, fy, fz = floor(x), floor(y), floor(z)
tx, ty, tz = x - fx, y - fy, z - fz
total = 0
for a in (0, 1):
for b in (0, 1):
for c in (0, 1):
g = corner_gradient(fx + a, fy + b, fz + c, perm)
d = (tx - a, ty - b, tz - c)
wx = fade(tx) if a else 1 - fade(tx)
wy = fade(ty) if b else 1 - fade(ty)
wz = fade(tz) if c else 1 - fade(tz)
total += wx * wy * wz * (g[0] * d[0] + g[1] * d[1] + g[2] * d[2])
return total
def rand_point(rng, lo=-20, hi=20):
return tuple(Fraction(rng.randint(lo * 64, hi * 64), 64) for _ in range(3))
def test_grad_matches_table():
rng = random.Random(1)
for h in range(256):
x, y, z = rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)
g = GRADIENTS[h & 15]
assert abs(grad(h, x, y, z) - (g[0] * x + g[1] * y + g[2] * z)) < 1e-15
assert sorted(set(GRADIENTS)) == sorted(
{v for v in GRADIENTS if sum(abs(c) for c in v) == 2})
assert len(set(GRADIENTS)) == 12
def test_against_direct_sum_exact():
n = PerlinNoise(seed=7)
rng = random.Random(2)
for _ in range(300):
x, y, z = rand_point(rng)
assert noise(x, y, z, n.perm) == reference(x, y, z, n.perm)
def test_zero_at_lattice_points():
n = PerlinNoise(seed=3)
rng = random.Random(3)
for _ in range(300):
i, j, k = rng.randint(-600, 600), rng.randint(-600, 600), rng.randint(-600, 600)
assert n(i, j, k) == 0
assert n(float(i), float(j), float(k)) == 0.0
def test_fade_conditions():
f = fade
assert f(Fraction(0)) == 0 and f(Fraction(1)) == 1
# f'(t) = 30 t^2 (t - 1)^2 and f''(t) = 60 t (t - 1) (2t - 1), so both
# vanish at 0 and 1. Check them by exact finite differences of the polynomial.
e = Fraction(1, 10 ** 6)
for t in (Fraction(0), Fraction(1)):
d1 = (f(t + e) - f(t - e)) / (2 * e)
d2 = (f(t + e) - 2 * f(t) + f(t - e)) / (e * e)
assert abs(d1) < Fraction(1, 10 ** 10) and abs(d2) < Fraction(1, 10 ** 4)
rng = random.Random(4)
for _ in range(100):
t = Fraction(rng.randint(0, 1000), 1000)
assert f(t) == 6 * t ** 5 - 15 * t ** 4 + 10 * t ** 3
assert 0 <= f(t) <= 1
def test_gradient_at_lattice_point_is_corner_gradient():
n = PerlinNoise(seed=5)
rng = random.Random(5)
h = 1e-6
for _ in range(50):
i, j, k = rng.randint(-50, 50), rng.randint(-50, 50), rng.randint(-50, 50)
g = corner_gradient(i, j, k, n.perm)
num = (
(n(i + h, j, k) - n(i - h, j, k)) / (2 * h),
(n(i, j + h, k) - n(i, j - h, k)) / (2 * h),
(n(i, j, k + h) - n(i, j, k - h)) / (2 * h),
)
for a, b in zip(num, g):
assert abs(a - b) < 1e-6
def test_period_256_and_continuity():
n = PerlinNoise(seed=6)
rng = random.Random(6)
for _ in range(200):
x, y, z = rng.uniform(-10, 10), rng.uniform(-10, 10), rng.uniform(-10, 10)
assert abs(n(x, y, z) - n(x + 256, y - 512, z + 256)) < 1e-9
for _ in range(200):
k = rng.randint(-20, 20)
y, z = rng.uniform(-5, 5), rng.uniform(-5, 5)
assert abs(n(k - 1e-9, y, z) - n(k + 1e-9, y, z)) < 1e-7
def test_deterministic_for_seed_and_bounded():
a, b, c = PerlinNoise(seed=11), PerlinNoise(seed=11), PerlinNoise(seed=12)
rng = random.Random(8)
pts = [(rng.uniform(-30, 30), rng.uniform(-30, 30), rng.uniform(-30, 30)) for _ in range(2000)]
va = [a(*p) for p in pts]
assert va == [b(*p) for p in pts]
assert va != [c(*p) for p in pts]
# Each corner term is at most |d_i| + |d_j| <= 2, and the weights are convex.
assert max(abs(v) for v in va) <= 2
assert abs(sum(va) / len(va)) < 0.05
History
Perlin described noise in 1985, in the paper An image synthesizer, as one primitive of a language for procedural shading of images. There the gradients were pseudorandom vectors from a table, and the interpolant was the cubic . In the 2002 note Improving noise, Perlin replaced the cubic by the quintic fade, to make the second derivative continuous, and replaced the random gradients by 12 fixed edge directions of a cube, to remove clumps where random gradients happen to align. In 2001 he had described simplex noise, which uses a simplex grid in place of the cubic lattice.
References
- Ken Perlin, An image synthesizer, Computer Graphics 19(3), SIGGRAPH 1985, pages 287 to 296, the noise function (pseudorandom gradients at the integer lattice, interpolated with a cubic) and its use in procedural textures (general locator)
- Ken Perlin, Improving noise, ACM Transactions on Graphics 21(3), SIGGRAPH 2002, pages 681 to 682, the whole paper (the fade 6t^5 - 15t^4 + 10t^3 and the 12 gradient directions, with the reference code)
- David S. Ebert, F. Kenton Musgrave, Darwyn Peachey, Ken Perlin and Steven Worley, Texturing and Modeling, A Procedural Approach, third edition, Morgan Kaufmann, 2003, the chapters by Peachey on building procedural textures and by Perlin on noise (general locator)
- Matt Pharr, Wenzel Jakob and Greg Humphreys, Physically Based Rendering, From Theory to Implementation, third edition, Morgan Kaufmann, 2016, Section 10.6.1, Perlin Noise
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QWP9HR Edit this page History Report an error Markdown