Algorithm Search⌘K

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
Properties
deterministicnot in placeonlineiterative
Origin
Ken Perlin, 1985

Perlin noise is a pseudorandom function on Rn\mathbb{R}^n 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 2n2^n 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 n+1n + 1 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 p=(x,y,z)∈R3p = (x, y, z) \in \mathbb{R}^3 and a permutation PP of 0,…,2550, \dots, 255. In the code, PP comes from a seeded Fisher-Yates shuffle, and it is stored twice, as P[0…511]P[0 \ldots 511] with P[i+256]=P[i]P[i + 256] = P[i], so that sums of indices need no reduction. The output is a real number N(p)N(p). The required properties are: NN is deterministic for a fixed PP, it is C2C^2, 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 GG holds the 12 vectors from the center of a cube to the midpoints of its edges, (±1,±1,0)(\pm 1, \pm 1, 0), (±1,0,±1)(\pm 1, 0, \pm 1) and (0,±1,±1)(0, \pm 1, \pm 1), and four of them again, (1,1,0)(1, 1, 0), (0,−1,1)(0, -1, 1), (−1,1,0)(-1, 1, 0) and (0,−1,−1)(0, -1, -1), for 16 entries. With 16 entries the index is h mod 16h \bmod 16, a bit mask.

The algorithm

  1. PERLIN-NOISE(x, y, z, P) ▷ P: a permutation of 0..255, stored twice
  2. 1(X, Y, Z) ← (⌊x⌋ mod 256, ⌊y⌋ mod 256, ⌊z⌋ mod 256)
  3. 2(x, y, z) ← (x - ⌊x⌋, y - ⌊y⌋, z - ⌊z⌋) ▷ the position in the unit cell
  4. 3(u, v, w) ← (FADE(x), FADE(y), FADE(z))
  5. 4for each corner (a, b, c) in {0, 1}^3 do
  6. 5h ← P[P[P[X + a] + Y + b] + Z + c] ▷ the hash of the corner
  7. 6n[a, b, c] ← GRAD(h, x - a, y - b, z - c)
  8. 7blend the 8 values n with lerp in x by u, then in y by v, then in z by w
  9. 8return the blended value
  10. FADE(t)
  11. 9return 6t^5 - 15t^4 + 10t^3
  12. GRAD(h, x, y, z)
  13. 10return G[h mod 16] · (x, y, z)

Here lerp(t,A,B)=A+t(B−A)\mathrm{lerp}(t, A, B) = A + t (B - A). In the code the hashes of line L5 share their inner lookups, as in Perlin's reference code: A=P[X]+YA = P[X] + Y, AA=P[A]+ZAA = P[A] + Z, 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 ff has f(0)=0f(0) = 0, f(1)=1f(1) = 1 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 p=(14,12,0)p = (\tfrac14, \tfrac12, 0) in the cell of the origin, and the permutation of seed 0 in the code. Its hash gives the corner gradients g000=(0,−1,−1)g_{000} = (0, -1, -1), g100=(0,−1,1)g_{100} = (0, -1, 1), g010=(1,1,0)g_{010} = (1, 1, 0) and g110=(0,1,1)g_{110} = (0, 1, 1). Since z=0z = 0, the weight w=f(0)=0w = f(0) = 0, and the four corners with c=1c = 1 do not count.

corner offset $p - $ corner g⋅g \cdot offset
(0,0,0)(0, 0, 0) (14,12,0)(\tfrac14, \tfrac12, 0) −12-\tfrac12
(1,0,0)(1, 0, 0) (−34,12,0)(-\tfrac34, \tfrac12, 0) −12-\tfrac12
(0,1,0)(0, 1, 0) (14,−12,0)(\tfrac14, -\tfrac12, 0) −14-\tfrac14
(1,1,0)(1, 1, 0) (−34,−12,0)(-\tfrac34, -\tfrac12, 0) −12-\tfrac12

The fades are u=f(14)=53512u = f(\tfrac14) = \tfrac{53}{512} and v=f(12)=12v = f(\tfrac12) = \tfrac12. The lerp in xx gives −12-\tfrac12 on the edge y=0y = 0, and −14+53512(−12+14)=−5652048-\tfrac14 + \tfrac{53}{512}(-\tfrac12 + \tfrac14) = -\tfrac{565}{2048} on the edge y=1y = 1. The lerp in yy gives N(p)=12(−10242048−5652048)=−15894096≈−0.3879N(p) = \tfrac12 (-\tfrac{1024}{2048} - \tfrac{565}{2048}) = -\tfrac{1589}{4096} \approx -0.3879. At the corner (0,0,0)(0, 0, 0) itself, every offset either is zero or has a component of absolute value 1, where the weight is 0, so N=0N = 0.

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 qq of a kernel K(p−q)=∏is(pi−qi)K(p - q) = \prod_i s(p_i - q_i) times gq⋅(p−q)g_q \cdot (p - q), where s(r)=1−f(∣r∣)s(r) = 1 - f(|r|) on [−1,1][-1, 1] and 0 outside. The kernel is C2C^2 because f′f' and f′′f'' vanish at 0 and 1, so NN is C2C^2, its value at a lattice point is 0, and its gradient there is gqg_q. Third, ∣N∣≤2|N| \le 2 in three dimensions, because each corner value is at most 2 and the weights are convex. Fourth, NN 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 n=3n = 3 dimensions. The proofs for other dimensions are the same with 2n2^n corners. Let f(t)=6t5−15t4+10t3f(t) = 6t^5 - 15t^4 + 10t^3 be the fade, and for each lattice point q∈Z3q \in \mathbb{Z}^3 let gq∈Gg_q \in G be the gradient that the permutation gives to qq (the function corner_gradient of the code). Arithmetic is exact (real-ram).

Lemma 1 (the fade). f(0)=0f(0) = 0, f(1)=1f(1) = 1, f(1−t)=1−f(t)f(1 - t) = 1 - f(t) for all tt, and f′(0)=f′(1)=f′′(0)=f′′(1)=0f'(0) = f'(1) = f''(0) = f''(1) = 0. On [0,1][0, 1], ff is nondecreasing, so 0≤f(t)≤10 \le f(t) \le 1.

Proof. f′(t)=30t4−60t3+30t2=30t2(t−1)2f'(t) = 30 t^4 - 60 t^3 + 30 t^2 = 30 t^2 (t - 1)^2 and f′′(t)=60t(t−1)(2t−1)f''(t) = 60 t (t - 1)(2t - 1). Both vanish at 0 and 1. The values at 0 and 1 follow by substitution. The polynomial f(t)+f(1−t)−1f(t) + f(1 - t) - 1 has the derivative f′(t)−f′(1−t)=30t2(t−1)2−30(1−t)2t2=0f'(t) - f'(1 - t) = 30 t^2 (t-1)^2 - 30 (1-t)^2 t^2 = 0, so it is constant, and its value at t=0t = 0 is 0+1−1=00 + 1 - 1 = 0. Last, f′≥0f' \ge 0 everywhere. □\square

Lemma 2 (the nested lerps are a tensor product sum). Let pp lie in the cell c+[0,1)3c + [0, 1)^3 with c=⌊p⌋c = \lfloor p \rfloor, and let t=p−ct = p - c. Lines L3 to L8 return

N(p)=∑a,b,e∈{0,1}Wa(tx) Wb(ty) We(tz)  gc+(a,b,e)⋅(t−(a,b,e)),N(p) = \sum_{a, b, e \in \{0, 1\}} W_a(t_x)\, W_b(t_y)\, W_e(t_z)\; g_{c + (a, b, e)} \cdot (t - (a, b, e)),

with W0(s)=1−f(s)W_0(s) = 1 - f(s) and W1(s)=f(s)W_1(s) = f(s).

Proof. Line L5 computes the hash of the corner c+(a,b,e)c + (a, b, e), and line L6 its value nabe=gc+(a,b,e)⋅(t−(a,b,e))n_{abe} = g_{c + (a,b,e)} \cdot (t - (a, b, e)), because GRAD returns the dot product with the gradient of index h mod 16h \bmod 16 (the code test test_grad_matches_table lists all 16 cases). lerp(s,A,B)=W0(s)A+W1(s)B\mathrm{lerp}(s, A, B) = W_0(s) A + W_1(s) B. Line L7 applies the lerp in xx to each of the four pairs, then in yy, then in zz. Expanding the three levels gives each corner value exactly once, multiplied by one weight per axis. □\square

Lemma 3 (one kernel per lattice point). Let s(r)=1−f(∣r∣)s(r) = 1 - f(|r|) for ∣r∣≤1|r| \le 1 and s(r)=0s(r) = 0 for ∣r∣>1|r| > 1, and let K(d)=s(dx) s(dy) s(dz)K(d) = s(d_x)\, s(d_y)\, s(d_z). Then for every p∈R3p \in \mathbb{R}^3

N(p)=∑q∈Z3K(p−q)  gq⋅(p−q).N(p) = \sum_{q \in \mathbb{Z}^3} K(p - q)\; g_q \cdot (p - q).

Proof. Fix pp in the cell of cc with t=p−ct = p - c. A lattice point qq with ∣px−qx∣>1|p_x - q_x| > 1 in some axis has K(p−q)=0K(p - q) = 0. A point with ∣px−qx∣=1|p_x - q_x| = 1 exactly also gives s=1−f(1)=0s = 1 - f(1) = 0. So only the 8 corners q=c+(a,b,e)q = c + (a, b, e) remain, with 0≤tx<10 \le t_x < 1. For a=0a = 0, s(tx)=1−f(tx)=W0(tx)s(t_x) = 1 - f(t_x) = W_0(t_x). For a=1a = 1, s(tx−1)=1−f(1−tx)=f(tx)=W1(tx)s(t_x - 1) = 1 - f(1 - t_x) = f(t_x) = W_1(t_x) by Lemma 1. The same holds in yy and zz, so the sum is the sum of Lemma 2. □\square

Theorem 1 (zeros at the lattice). N(q)=0N(q) = 0 for every q∈Z3q \in \mathbb{Z}^3.

Proof. By Lemma 3, a lattice point q′≠qq' \ne q differs from qq by at least 1 in some axis, so K(q−q′)=0K(q - q') = 0. The term of qq itself is K(0) gq⋅0=0K(0)\, g_q \cdot 0 = 0. □\square

Theorem 2 (smoothness). NN is twice continuously differentiable on R3\mathbb{R}^3, and ∇N(q)=gq\nabla N(q) = g_q at every lattice point qq.

Proof. The function ss is C2C^2 on R\mathbb{R}. On (0,1)(0, 1) it is the polynomial 1−f(r)1 - f(r), and on (−1,0)(-1, 0) the polynomial 1−f(−r)1 - f(-r). At r=0r = 0 both pieces have the value 1, the first derivative ∓f′(0)=0\mp f'(0) = 0 and the second derivative −f′′(0)=0-f''(0) = 0. At r=±1r = \pm 1 the pieces have the value 1−f(1)=01 - f(1) = 0, the first derivative ∓f′(1)=0\mp f'(1) = 0 and the second derivative −f′′(1)=0-f''(1) = 0, which match the zero function outside. So KK is C2C^2, each term K(p−q) gq⋅(p−q)K(p - q)\, g_q \cdot (p - q) is C2C^2, and on any bounded set only finitely many terms are not zero. So NN is C2C^2. At a lattice point qq, every other term q′q' has K(q−q′)=0K(q - q') = 0 and ∇K(q−q′)=0\nabla K(q - q') = 0, because ss and s′s' vanish at ±1\pm 1 and s(0)=1s(0) = 1, so each component of ∇K\nabla K holds one factor s(±1)s(\pm 1) or s′(±1)s'(\pm 1). The term of qq has the gradient K(0)gq+(gq⋅0)∇K(0)=gqK(0) g_q + (g_q \cdot 0) \nabla K(0) = g_q. □\square

With the cubic fade 3t2−2t33t^2 - 2t^3 of Perlin's 1985 noise, f′′(0)=6f''(0) = 6 and f′′(1)=−6f''(1) = -6. Then s′′(r)=−f′′(1)=6s''(r) = -f''(1) = 6 just inside r=±1r = \pm 1 and 00 outside, so s′′s'' jumps by 6 there. So NN is only C1C^1, and its second derivative jumps on the cell faces. This is the reason for the quintic fade.

Theorem 3 (a bound on the range). ∣N(p)∣≤2|N(p)| \le 2 for every pp.

Proof. Each gradient g∈Gg \in G has two components equal to ±1\pm 1 and one equal to 0. Each offset t−(a,b,e)t - (a, b, e) has components in [−1,1][-1, 1]. So each corner value is at most 1+1=21 + 1 = 2 in absolute value. By Lemma 1 the weights W0,W1W_0, W_1 are in [0,1][0, 1] and W0+W1=1W_0 + W_1 = 1, so the 8 products in Lemma 2 are nonnegative and sum to 1. A convex combination of numbers in [−2,2][-2, 2] lies in [−2,2][-2, 2]. □\square

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). N(p+256 ei)=N(p)N(p + 256\, e_i) = N(p) for each unit axis vector eie_i.

Proof. Line L1 reduces the cell index modulo 256, and line L2 does not change under an integer shift. The table PP has 512 entries with P[i+256]=P[i]P[i + 256] = P[i], 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 pp and at p+256 eip + 256\, e_i. □\square

Cost. Lines L1 to L3 take O(n)O(n) operations. The loop runs over 2n2^n corners. Each corner takes nn table lookups and a dot product of length nn, so O(n)O(n). Line L7 takes 2n−12^n - 1 lerps. The total is Θ(n2n)\Theta(n 2^n) operations per point, which is O(1)O(1) for the fixed n=3n = 3 of the code.

Complexity

In nn dimensions one evaluation visits the 2n2^n corners of the cell, and each corner costs nn table lookups and a dot product of length nn. The blend is 2n−12^n - 1 lerps. So one point costs Θ(n2n)\Theta(n 2^n) operations, and qq points cost Θ(qn2n)\Theta(q n 2^n), 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 O(n2)O(n^2) per point, which is less for n≥4n \ge 4.

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. N(q)=0N(q) = 0 for q∈Z3q \in \mathbb{Z}^3. A sample on the integers gives a constant image.
  • Range. The proved bound is ∣N∣≤2|N| \le 2. It is not tight: on 200000 random points with seed 0, the largest absolute value is 0.9210.921. Do not assume the range [−1,1][-1, 1] 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 3t2−2t33t^2 - 2t^3. 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 ∇N\nabla N with the value, which bump mapping and terrain need.
  • Tiling noise. Reduce the cell index modulo a period TT before the hash, so that the noise tiles on a texture of TT cells.
  • Hash in place of a table. GPU code often replaces PP 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, x−⌊x⌋x - \lfloor x \rfloor loses bits when ∣x∣|x| 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 PP. 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.

perlin_noise.pyI0RawGitHub
# 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 3t2−2t33t^2 - 2t^3. 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

  1. 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)
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example