Algorithmadvanced
Simplex noise
Also called Perlin simplex noise.
Gradient noise summed over the n + 1 corners of the simplex that holds the point, which costs O(n^2) instead of O(n 2^n) in n dimensions.
- Time
- Θ(q n^2) worst
- Space
- Θ(n) 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, 2001
Simplex noise is a gradient noise on , like Perlin noise, but it uses a different grid. Perlin noise blends the corners of a cube cell. Simplex noise splits space into simplices (triangles in 2D, tetrahedra in 3D) and adds one radial kernel for each of the corners of the simplex that holds the point. So it costs per point in place of , it has less axis bias, and its gradient is continuous. Like Perlin noise it is a base noise for fractal noise. Worley noise is a different kind of base noise, made of distances to random points.
In plain words
Cover the plane with equal triangles. At each corner of each triangle, put a small tilted plane with a random slope, and fade it out in a round bump around the corner. The noise at a point is the sum of the bumps that reach it.
The trick is that the bumps are small enough that only the three corners of the triangle that holds the point can reach it. So you find that triangle, add three terms, and you are done. In 3D there are four corners, in 4D five. A square grid would need four, eight and sixteen corners.
To find the triangle quickly, the method stretches the plane along its diagonal, so that the triangles become halves of unit squares.
The problem
The input is a point and a permutation of , stored twice as in Perlin noise. The output is a real number . Let and , and let be the sum of the coordinates. The skew maps the simplex grid onto the integer lattice , and the unskew is its inverse. In 2D, and .
Each lattice point has a gradient , chosen by a nested hash of its coordinates through . Its kernel at is with and . The noise is . The task is to compute this sum without a search over the lattice.
The algorithm
SIMPLEX-NOISE(x, P) ▷ x in R^n- 1
s ← F · (x_1 + ... + x_n) ▷ the skew - 2
k ← (⌊x_1 + s⌋, ..., ⌊x_n + s⌋) ▷ the cell in skewed space - 3
π ← the axes sorted by decreasing x_i + s - k_i - 4
c_0 ← k; c_m ← c_{m-1} + e_{π(m)} for m = 1..n - 5
for m ← 0 to n do - 6
d ← x - (c_m - G · (sum of c_m) · 1) ▷ the unskewed offset - 7
if r^2 - |d|^2 ≤ 0 then skip this corner - 8
total ← total + (r^2 - |d|^2)^4 · (g[HASH(c_m, P)] · d) - 9
return scale · total
The table in the code is the table of Gustavson's code in 2D and 3D: the 12 edge directions of a cube, with the hash modulo 12, and in 2D their first two components. In four or more dimensions it holds the vectors with entries in and exactly one zero. The scale is 70 in 2D, as in Gustavson's code, and 1 otherwise. It only sets the range.
Example
Take in 2D and the permutation of seed 0 in the code. Line L1 gives , so the skewed point is about and . The part is larger, so line L4 steps along first, and the corners are , and .
| corner | unskewed corner | term | ||||
|---|---|---|---|---|---|---|
The sum is , and with the scale 70 the noise is . The nearest corner, , has the largest weight, as expected.
Correctness
The proof file shows that the sum over the corners equals the sum over the whole lattice when . The key step is a formula for the distance. If is an offset in skewed space, then , which is the spread of the numbers about their mean. For a lattice point that is not one of the chosen corners, two of these numbers differ by at least 1, so the squared distance is at least , and its kernel is zero.
Three facts follow. The value does not depend on how line L3 breaks ties, so the noise is continuous across the faces of the simplices. The noise is , because is . And the noise is zero at every lattice point. The bound is reached, so a larger radius makes the corner sum drop terms that are not zero.
Proof: The sum over the corners of one simplex equals the sum over the whole latticefull
We use the pseudocode and the notation of the page. Arithmetic is exact (real-ram). Let , and . For write and . The skew is and the unskew is . For each let be its hashed gradient, and let the kernel of at be
The full noise is . Lines L5 to L8 sum only over the corners that lines L1 to L4 select. We prove that for the two sums are equal.
Lemma 1 (the skew and the unskew are inverse). .
Proof. , so . Now and . So the two terms cancel.
Lemma 2 (the distance in skewed coordinates). For , . Equivalently, if and is the mean of its entries, then .
Proof. with . Put . Then . For the second form, , and . The mean minimizes the sum of squares.
The second form does not change if the same constant is added to all entries of . We use this below.
Lemma 3 (the chosen corners). Let , and , as in lines L1 and L2. Let be the order of line L3, so . The corners of line L4 are for . Then is the convex combination with , for , and .
Proof. The weights are nonnegative by the order and sum to 1 by telescoping. Coordinate of is , again by telescoping.
So by Lemma 1, lies in the simplex with the vertices , and the code test test_point_lies_in_chosen_simplex checks the weights.
Lemma 4 (every other lattice point is far). Let with . Then .
Proof. Let . By Lemma 1 and linearity, . Let have for and . Extend and by and , so that in with .
Suppose first that some pair has . By Lemma 2, .
So it is enough to show: if for all , then is one of the corners . Assume this. For each , . If , then , which is false. So the values take at most two consecutive integers, and . If and , then , so by the assumption. So the set is an upper set of : every in has a strictly larger than every not in . Since is the smallest entry and , either and , or holds all indices and , so in the first entries. In the second case . In the first case is a set of indices whose values are strictly larger than all others. An order that sorts in decreasing order, with any rule for ties, lists such a set first, because ties cannot cross the boundary of . So with , and .
Theorem 1 (the corner sum is the noise). If , then for every the sum of lines L5 to L8 equals .
Proof. The sum of lines L5 to L8 is , and line L7 skips exactly the terms whose factor is 0. For every other lattice point , Lemma 4 gives , so .
The bound is reached. In 2D, maps the unit square to two equilateral triangles of side , whose height is . At the midpoint of the diagonal edge, the corner of the other triangle is at the distance . In any dimension, take . Line L3 puts one of the first two axes first, and the unit step along the other one is not a corner. Its is in the first two entries and 0 elsewhere, so the squared distance is exactly . With a larger radius that point would add a term that the corner sum drops. The code test test_larger_radius_breaks_corner_sum measures such a difference with in 3D.
Theorem 2 (smoothness and zeros). For , is on , and for every .
Proof. The map is : on its first three derivatives , and tend to 0 as , which match the zero function on . The map is a polynomial, and is linear. So each is . On a bounded set only finitely many are not zero, so is . At , the term has the factor . Every other lattice point has , and with every entry of ties, so the only upper set of Lemma 4 that is allowed is the empty one, and is not a corner. So and .
By Theorem 1, the value of the code does not depend on how line L3 breaks ties, and it is the same function on both sides of a face of a simplex. So the corner sum is continuous, although the set of corners changes at the faces.
Cost. Lines L1 and L2 take . The sort of line L3 takes comparisons. Line L4 makes corners, and for each corner lines L6 to L8 take : the unskew, the squared distance, the dot product, and table lookups for the hash. The total is per point, against for the corners of a cube cell.
Complexity
Lines L1 and L2 take time. The sort of line L3 takes . Each of the corners takes for the unskew, the distance, the dot product and the lookups of the hash. So one point costs , and points cost , in the real-RAM model. Perlin noise costs : in 3D that is 4 corners against 8, and in 4D 5 corners against 16. The extra space is for the corner, plus the table of 512 entries.
Properties
- Continuous with a continuous gradient. This is a proved property for . The noise is .
- Zero at the lattice points. for every . This is proved.
- Less axis bias. The kernels are radial, so the pattern has fewer features along the axes than Perlin noise. This is an observation, not a theorem.
- Range. With the scale 70 in 2D, the largest absolute value on 200000 random points with seed 0 is . This is a measurement. Other dimensions need their own scale.
- Period. The hash reduces each coordinate modulo 256, so the noise repeats every 256 units of the skewed lattice.
Variants and improvements
- Gustavson's code. It unrolls the sort of line L3 into comparisons, two in 2D and a decision tree in 3D, and hard-codes the corner offsets.
- Radius 0.6. Gustavson's 3D and 4D code first used , which gives wider and smoother bumps. The PDF now marks it as an error: with 0.6 the noise jumps on the faces of the simplices. See the pitfall below.
- Analytic derivatives. The kernel is a polynomial in , so its gradient costs little more than its value. This is useful for bump mapping and flow noise.
- OpenSimplex and similar. Other lattices and kernels avoid some of the artifacts of the plain simplex grid. They follow the same plan of a few corners and a radial kernel.
- Tiling. A tiling version needs a lattice whose period matches the simplex grid, which is harder than for Perlin noise.
When to use it
Use simplex noise in three or more dimensions, for example 3D noise animated in time as 4D noise, where the corner count of Perlin noise grows fast. Use it when the axis bias of Perlin noise shows, or when the shading needs a continuous gradient. In 2D at small scale the gain over Perlin noise is small, and Perlin noise tiles more easily. Use Worley noise for cell patterns, and fractal noise to sum several octaves of either base noise.
Pitfalls
- A radius above . The sum then misses terms of lattice points outside the simplex. The noise jumps on the faces. In 3D the code test measures the jump with .
- A wrong unskew factor. and must satisfy . A copy of the 2D constants in 3D, or a rounded constant, puts the point in the wrong simplex.
- Truncation in place of floor. As for Perlin noise, a cast to an integer gives the wrong cell for negative coordinates.
- Assuming a range. The scale depends on the dimension, the radius and the gradient set. Measure the range or bound it before you clamp.
- Hash collisions in high dimensions. With a table of 256 entries, the nested hash repeats with the period 256, and in many dimensions this can show as repeats in the pattern.
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/simplex-noise/. The authors are listed in prov/PWY9S0.jsonl.
"""Simplex noise in n dimensions (Perlin 2001), in the form of Gustavson 2005.
The skew x' = x + F (x_1 + ... + x_n) with F = (sqrt(n + 1) - 1) / n maps the
simplex grid to the integer lattice, where the simplices are the cells of the
unit cube cut by the order of the coordinates. The point lies in the simplex
whose n + 1 corners are reached from floor(x') by unit steps along the axes,
in decreasing order of the fractional parts. Each corner adds
max(0, r2 - |d|^2)^4 (g . d), where d is the offset from the corner after the
unskew with G = (1 - 1 / sqrt(n + 1)) / n, and g is a hashed gradient.
In 2D and 3D the gradients are those of Gustavson's code: the 12 edge
directions of a cube (in 2D their first two components), with the index hash
mod 12. In 2D the sum is scaled by 70, as in his code. For n >= 4 the
gradients are the vectors with entries in {-1, 0, 1} that have exactly one
zero, and the scale is 1. The radius r2 = 0.5 keeps the noise continuous in
every dimension (see the proof of the page). Gustavson's 3D and 4D code uses
0.6, which makes small jumps on the faces of the simplices.
"""
import random
from itertools import product
from math import floor, sqrt
GRAD3 = (
(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),
)
def skew_constants(n):
"""Return (F, G) for dimension n."""
return (sqrt(n + 1) - 1) / n, (1 - 1 / sqrt(n + 1)) / n
def gradient_set(n):
"""The gradient table for dimension n."""
if n == 2:
return tuple(g[:2] for g in GRAD3)
if n == 3:
return GRAD3
out = []
for zero in range(n):
for signs in product((1, -1), repeat=n - 1):
g = list(signs)
g.insert(zero, 0)
out.append(tuple(g))
return tuple(out)
def make_permutation(rng):
p = list(range(256))
rng.shuffle(p)
return p + p
def lattice_hash(k, perm):
"""Nested permutation hash of the integer point k (last axis innermost)."""
h = 0
for c in reversed(k):
h = perm[(c & 255) + h]
return h
def simplex_corners(x):
"""Return the skewed corner list of the simplex that holds the point x."""
n = len(x)
F, _ = skew_constants(n)
s = sum(x) * F # @line L1
k = [floor(c + s) for c in x] # @line L2
f = [c + s - kc for c, kc in zip(x, k)]
order = sorted(range(n), key=lambda a: -f[a]) # @line L3
corners = [tuple(k)]
cur = list(k)
for a in order: # @line L4
cur[a] += 1
corners.append(tuple(cur))
return corners
def unskew(k):
_, G = skew_constants(len(k))
t = sum(k) * G
return tuple(c - t for c in k)
def corner_term(x, k, perm, grads, r2):
"""The contribution of the lattice point k to the noise at x."""
u = unskew(k) # @line L6
d = [a - b for a, b in zip(x, u)]
t = r2 - sum(c * c for c in d)
if t <= 0: # @line L7
return 0.0
g = grads[lattice_hash(k, perm) % len(grads)]
return t ** 4 * sum(a * b for a, b in zip(g, d)) # @line L8
class SimplexNoise:
"""Seeded simplex noise in n dimensions."""
def __init__(self, n=2, seed=0, r2=0.5, scale=None):
self.n = n
self.perm = make_permutation(random.Random(seed))
self.grads = gradient_set(n)
self.r2 = r2
self.scale = (70.0 if n == 2 else 1.0) if scale is None else scale
def __call__(self, *x):
if len(x) != self.n:
raise ValueError("wrong number of coordinates")
total = 0.0
for k in simplex_corners(x): # @line L5
total += corner_term(x, k, self.perm, self.grads, self.r2)
return self.scale * total # @line L9
test_simplex_noise.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simplex-noise/. The authors are listed in prov/PWY9S0.jsonl.
"""Tests of simplex noise.
The 2D case is checked against a direct copy of the structure of Gustavson's
2D code. In 2, 3 and 4 dimensions the sum over the n + 1 corners is checked
against a brute force sum over every lattice point near the point, which is
the claim of the proof. The tests also check that the point lies in the
chosen simplex, the zeros at the lattice points, continuity, determinism for
a seed, and that a radius above 0.5 breaks the corner sum.
"""
import random
from itertools import product
from math import floor, sqrt
from simplex_noise import (
GRAD3,
SimplexNoise,
corner_term,
simplex_corners,
skew_constants,
unskew,
)
def gustavson_2d(xin, yin, perm):
"""The 2D noise written as in Gustavson's paper, with r^2 = 0.5 and scale 70."""
F2 = 0.5 * (sqrt(3.0) - 1.0)
G2 = (3.0 - sqrt(3.0)) / 6.0
s = (xin + yin) * F2
i, j = floor(xin + s), floor(yin + s)
t = (i + j) * G2
x0, y0 = xin - (i - t), yin - (j - t)
i1, j1 = (1, 0) if x0 > y0 else (0, 1)
x1, y1 = x0 - i1 + G2, y0 - j1 + G2
x2, y2 = x0 - 1.0 + 2.0 * G2, y0 - 1.0 + 2.0 * G2
ii, jj = i & 255, j & 255
gi = (
perm[ii + perm[jj]] % 12,
perm[ii + i1 + perm[jj + j1]] % 12,
perm[ii + 1 + perm[jj + 1]] % 12,
)
total = 0.0
for g, (dx, dy) in zip(gi, ((x0, y0), (x1, y1), (x2, y2))):
t = 0.5 - dx * dx - dy * dy
if t > 0:
t *= t
total += t * t * (GRAD3[g][0] * dx + GRAD3[g][1] * dy)
return 70.0 * total
def brute_force(noise, x, reach=2):
"""Sum the corner term of every lattice point whose skewed cell is near x."""
n = len(x)
F, _ = skew_constants(n)
s = sum(x) * F
base = [floor(c + s) for c in x]
total = 0.0
for off in product(range(-reach, reach + 1), repeat=n):
k = tuple(b + o for b, o in zip(base, off))
total += corner_term(x, k, noise.perm, noise.grads, noise.r2)
return noise.scale * total
def test_matches_gustavson_2d():
noise = SimplexNoise(n=2, seed=1)
rng = random.Random(1)
for _ in range(3000):
x, y = rng.uniform(-300, 300), rng.uniform(-300, 300)
assert abs(noise(x, y) - gustavson_2d(x, y, noise.perm)) < 1e-12
def test_skew_constants():
F2, G2 = skew_constants(2)
assert abs(F2 - (sqrt(3) - 1) / 2) < 1e-15
assert abs(G2 - (3 - sqrt(3)) / 6) < 1e-15
for n in range(1, 8):
F, G = skew_constants(n)
# The unskew undoes the skew: (1 + nF)(1 - nG) = 1.
assert abs((1 + n * F) * (1 - n * G) - 1) < 1e-14
def test_point_lies_in_chosen_simplex():
rng = random.Random(2)
for n in (2, 3, 4, 5):
F, _ = skew_constants(n)
for _ in range(300):
x = [rng.uniform(-50, 50) for _ in range(n)]
y = [c + sum(x) * F for c in x]
cs = simplex_corners(x)
assert len(set(cs)) == n + 1
# Barycentric weights in skewed space: differences of the sorted
# fractional parts. They are nonnegative and rebuild the point.
k = cs[0]
f = sorted((a - b for a, b in zip(y, k)), reverse=True)
lam = [1 - f[0]] + [f[m] - f[m + 1] for m in range(n - 1)] + [f[-1]]
assert min(lam) >= -1e-12 and abs(sum(lam) - 1) < 1e-12
rebuilt = [sum(lam[m] * cs[m][a] for m in range(n + 1)) for a in range(n)]
assert max(abs(a - b) for a, b in zip(rebuilt, y)) < 1e-9
def test_corner_sum_equals_brute_force():
rng = random.Random(3)
for n, count in ((2, 400), (3, 200), (4, 40)):
noise = SimplexNoise(n=n, seed=n)
for _ in range(count):
x = [rng.uniform(-40, 40) for _ in range(n)]
assert abs(noise(*x) - brute_force(noise, x)) < 1e-12
def test_larger_radius_breaks_corner_sum():
noise = SimplexNoise(n=3, seed=4, r2=0.6)
rng = random.Random(4)
worst = 0.0
for _ in range(300):
x = [rng.uniform(-20, 20) for _ in range(3)]
worst = max(worst, abs(noise(*x) - brute_force(noise, x)))
# With r2 = 0.5 the difference is below 1e-12 (the test above).
assert worst > 1e-6
def test_zero_at_lattice_points():
rng = random.Random(5)
for n in (2, 3, 4):
noise = SimplexNoise(n=n, seed=5)
for _ in range(200):
k = tuple(rng.randint(-300, 300) for _ in range(n))
assert abs(noise(*unskew(k))) < 1e-9
def test_continuity():
rng = random.Random(6)
for n in (2, 3, 4):
noise = SimplexNoise(n=n, seed=6)
for _ in range(300):
x = [rng.uniform(-20, 20) for _ in range(n)]
e = [rng.uniform(-1e-7, 1e-7) for _ in range(n)]
y = [a + b for a, b in zip(x, e)]
assert abs(noise(*x) - noise(*y)) < 1e-4
def test_deterministic_for_seed():
a, b, c = SimplexNoise(2, seed=9), SimplexNoise(2, seed=9), SimplexNoise(2, seed=10)
rng = random.Random(7)
pts = [(rng.uniform(-100, 100), rng.uniform(-100, 100)) 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]
assert max(abs(v) for v in va) <= 1.0
History
Ken Perlin presented simplex noise in his SIGGRAPH course notes of 2001 and 2002, with a compact reference code in Java. His aims were a lower cost in high dimensions, a design that suits hardware, and the removal of the axis artifacts of his 1985 noise. Few people used it at first, because the reference code was hard to read. In 2005 Stefan Gustavson wrote Simplex noise demystified, which explains the skew and the choice of the simplex and gives readable code for two, three and four dimensions. Most later implementations follow his code.
References
- Ken Perlin, Noise hardware, SIGGRAPH 2001 course notes, the simplex grid, the skew of the input, and the radial kernel per corner (general locator)
- Stefan Gustavson, Simplex noise demystified, Linköping University, 2005, the 2D code (skew factor F2, unskew factor G2, the radius 0.5 and the scale 70) and the 3D code, with the note that its radius 0.6 should be 0.5 for continuity
- Ken Perlin, An image synthesizer, Computer Graphics 19(3), SIGGRAPH 1985, pages 287 to 296, the lattice gradient noise that simplex noise replaces (general locator)
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 PWY9S0 Edit this page History Report an error Markdown