Algorithm Search⌘K

Algorithmcore

Worley noise

Also called cellular noise, Voronoi noise.

A procedural texture basis whose value is the distance to the nearest, or the k-th nearest, of random feature points scattered in cells.

Time
O(q (1 + k/λ + (λ + k) k)) expected
Space
O(k) extra
Where
k = the order of the distance F_k; q = the number of queries; λ = the mean number of feature points per cell
Properties
deterministicnot in placeonlineiterative
Origin
Steven Worley, 1996

Worley noise is a procedural texture made from distances. Random feature points are scattered through space, a fixed set for each seed, and the value at a point xx is Fk(x)F_k(x), the distance from xx to its kk-th nearest feature point. F1F_1 looks like a field of round cells, F2−F1F_2 - F_1 is zero on the edges of the Voronoi diagram of the points and draws a web of cracks, and other combinations give stone, scales, foam and leather. Perlin noise and simplex noise are the other base noises. They blend random gradients on a lattice, and their features have no sharp edges. Fractal noise sums octaves of any of these base noises.

In plain words

Throw a handful of seeds on the floor at random. For each spot on the floor, measure the distance to the nearest seed. Paint near spots dark and far spots light. You get round blobs around the seeds, and the blobs meet in straight lines halfway between neighbors.

You cannot store infinitely many seeds, so the floor is cut into square tiles, and each tile makes its own seeds from a random number generator started with the tile number. The same tile always gets the same seeds. To find the nearest seed, look at your own tile, then at the ring of tiles around it, and so on, until no tile further out could hold a nearer seed.

The problem

The input is a query point x∈R2x \in \mathbb{R}^2, an order k≥1k \ge 1, a seed, a mean density λ>0\lambda > 0 and a distance (Euclidean, Manhattan or Chebyshev). The plane is cut into unit cells. Cell bb holds a Poisson number of points with mean λ\lambda, placed uniformly in the cell, all taken from a generator seeded by a hash of the seed and bb. The output is the sorted list F1(x)≤⋯≤Fk(x)F_1(x) \le \dots \le F_k(x) of the distances from xx to its kk nearest feature points. The answer must be exact, not an estimate, so that the texture has no holes or seams.

The algorithm

  1. WORLEY(x, k, seed)
  2. 1c ← ⌊x⌋; m ← the distance from x to the nearest side of the cell c
  3. 2best ← an empty sorted list
  4. 3for r ← 0, 1, 2, ... do
  5. 4for each cell b at Chebyshev distance exactly r from c do
  6. 5for each feature point p of b do ▷ made from HASH(seed, b)
  7. 6insert δ(x, p) into best and keep the k smallest
  8. 7if best has k entries and best[k] ≤ r + m then
  9. 8return best

The cells at Chebyshev distance at most rr from cc form a square block. Every point outside the block is at a distance of at least r+mr + m from xx. So when the kk-th best distance is at most r+mr + m, no further ring can change the answer.

Example

Take x=(0.5,0.5)x = (0.5, 0.5), k=2k = 2, seed 0 and λ=2\lambda = 2 in the code. Then c=(0,0)c = (0, 0) and m=0.5m = 0.5.

ring feature points distances best after the ring stop test
0 (0.892,0.591)(0.892, 0.591), (0.773,0.079)(0.773, 0.079) 0.40240.4024, 0.50150.5015 (0.4024,0.5015)(0.4024, 0.5015) 0.5015≤0.50.5015 \le 0.5 is false
1 14 points in 8 cells the smallest is 0.91530.9153 (0.4024,0.5015)(0.4024, 0.5015) 0.5015≤1.50.5015 \le 1.5 is true

So F1=0.4024F_1 = 0.4024, F2=0.5015F_2 = 0.5015 and F2−F1=0.0991F_2 - F_1 = 0.0991. The first test fails by a small margin: a point in the next ring could still be at a distance just over 0.50.5, and the search must look. Ring 1 changes nothing here, but it must be searched.

Correctness

The proof file shows four facts. First, the ring function lists each cell of ring rr once, so after ring rr the search has seen every point of the block of cells within Chebyshev distance rr. Second, the list keeps the kk smallest distances seen. Third, a point outside the block differs from xx by at least r+mr + m in some coordinate, and all three distances are at least that difference. So when line L7 holds, no unseen point can be nearer than the kk-th entry, and the answer is exact. Fourth, the loop stops by ring max⁡(rk,⌈Fk⌉)\max(r_k, \lceil F_k \rceil), where rkr_k is the ring of a kk-th nearest point. The code test compares the result with a brute force search over all points of a block of 16×1616 \times 16 cells.

Proof: The ring search returns the exact k nearest feature distancesfull

We use the pseudocode and the notation of the page, in two dimensions. Arithmetic is exact (real-ram). The cells are the unit squares [i,i+1)×[j,j+1)[i, i+1) \times [j, j+1) for integer i,ji, j. Each cell holds a finite set of feature points inside it, which depends only on the seed and the cell. The distance δ\delta is the Euclidean, the Manhattan or the Chebyshev distance. All three satisfy δ(x,p)≥∣xa−pa∣\delta(x, p) \ge |x_a - p_a| for each axis aa.

Let c=⌊x⌋c = \lfloor x \rfloor be the cell of the query xx, and let f=x−c∈[0,1)2f = x - c \in [0, 1)^2. Line L1 sets m=min⁡(f1,1−f1,f2,1−f2)m = \min(f_1, 1 - f_1, f_2, 1 - f_2). Let BrB_r be the set of cells bb with max⁡(∣b1−c1∣,∣b2−c2∣)≤r\max(|b_1 - c_1|, |b_2 - c_2|) \le r. Ring rr is Br∖Br−1B_r \setminus B_{r-1}, with B−1=∅B_{-1} = \emptyset.

Lemma 1 (the rings). The code function ring(c, r) lists each cell of ring rr exactly once. So after the loop of lines L4 to L6 has run for r=0,…,Rr = 0, \dots, R, it has visited each cell of BRB_R exactly once.

Proof. For r=0r = 0 it lists cc only. For r≥1r \ge 1 it lists the two rows b2=c2±rb_2 = c_2 \pm r with b1b_1 from c1−rc_1 - r to c1+rc_1 + r, and the two columns b1=c1±rb_1 = c_1 \pm r with b2b_2 strictly between c2−rc_2 - r and c2+rc_2 + r. A cell has Chebyshev distance exactly rr from cc if and only if one of its coordinates differs by exactly rr and the other by at most rr, so these lists cover ring rr. The rows and the columns do not share a cell, so no cell repeats. There are 2(2r+1)+2(2r−1)=8r2(2r + 1) + 2(2r - 1) = 8r cells, which the code test test_ring_enumerates_each_cell_once checks. □\square

Lemma 2 (points outside the block are far). If a feature point pp lies in a cell outside BrB_r, then δ(x,p)≥r+m\delta(x, p) \ge r + m.

Proof. The cells of BrB_r cover the square Q=[c1−r,c1+r+1)×[c2−r,c2+r+1)Q = [c_1 - r, c_1 + r + 1) \times [c_2 - r, c_2 + r + 1), and the cells are disjoint, so p∉Qp \notin Q. So for some axis aa, either pa<ca−rp_a < c_a - r or pa≥ca+r+1p_a \ge c_a + r + 1. In the first case xa−pa>xa−ca+r=fa+r≥r+mx_a - p_a > x_a - c_a + r = f_a + r \ge r + m. In the second case pa−xa≥ca+r+1−xa=(1−fa)+r≥r+mp_a - x_a \ge c_a + r + 1 - x_a = (1 - f_a) + r \ge r + m. So δ(x,p)≥∣xa−pa∣≥r+m\delta(x, p) \ge |x_a - p_a| \ge r + m. □\square

Invariant. After lines L4 to L6 have run for ring rr, the list best is the sorted list of the min⁡(k,nr)\min(k, n_r) smallest distances from xx to the feature points in the cells of BrB_r, counted with multiplicity, where nrn_r is the number of those points.

Proof. By Lemma 1, line L5 sees each point of BrB_r exactly once. Line L6 keeps a sorted list of at most kk values. A new distance dd enters when the list is short or dd is less than the largest kept value. Then the largest value drops off if the list grows past kk. This is the standard way to keep the kk smallest of a stream: a value that drops off has kk kept values at most as large as it, so it is not among the kk smallest of the stream so far, and it never returns. □\square

Theorem 1 (exactness). If line L8 returns, its list is (F1(x),…,Fk(x))(F_1(x), \dots, F_k(x)), the sorted distances from xx to its kk nearest feature points among all cells.

Proof. Line L7 holds, so best has kk entries and its largest is at most r+mr + m. By the invariant, best lists the kk smallest distances to points in BrB_r. By Lemma 2, every other point has a distance of at least r+m≥r + m \ge best[k][k]. So no point outside BrB_r can take a place among the kk smallest with a smaller value, and the sorted list of the kk smallest values over all points is best. □\square

Theorem 2 (the loop stops). If at least kk feature points exist, line L8 returns. It returns no later than at ring R=max⁡(rk,⌈Fk(x)⌉)R = \max(r_k, \lceil F_k(x) \rceil), where rkr_k is the ring of a kk-th nearest point.

Proof. After ring R≥rkR \ge r_k, the block BRB_R holds the kk nearest points, so best has kk entries with the largest equal to Fk(x)F_k(x). Since R≥Fk(x)R \ge F_k(x) and m≥0m \ge 0, the test Fk(x)≤R+mF_k(x) \le R + m of line L7 holds. □\square

The point of the margin mm is that the search can stop at ring ⌈Fk−m⌉\lceil F_k - m \rceil in place of ⌈Fk⌉\lceil F_k \rceil, which saves a full ring in many queries.

Theorem 3 (the 1-Lipschitz bound). For the Euclidean distance, ∣Fk(x)−Fk(y)∣≤∣x−y∣|F_k(x) - F_k(y)| \le |x - y| for every kk.

Proof. Each point pp has ∣x−p∣≤∣y−p∣+∣x−y∣|x - p| \le |y - p| + |x - y| by the triangle inequality. So the kk nearest points of yy are kk points within the distance Fk(y)+∣x−y∣F_k(y) + |x - y| of xx, and Fk(x)≤Fk(y)+∣x−y∣F_k(x) \le F_k(y) + |x - y|. The same holds with xx and yy swapped. □\square

Expected cost. Assume the ideal model: the counts of the cells are independent Poisson variables with mean λ\lambda, and the points are uniform in their cells, so the points form a Poisson process of intensity λ\lambda. Then λπFk2\lambda \pi F_k^2 has the Gamma distribution with shape kk, and E[Fk2]=k/(πλ)E[F_k^2] = k / (\pi \lambda). A point at Euclidean distance FkF_k lies in a ring at most Fk+1F_k + 1, so by Theorem 2 the search visits at most (2Fk+3)2≤8Fk2+18(2 F_k + 3)^2 \le 8 F_k^2 + 18 cells, and the expected number of cells is at most 8k/(πλ)+18=O(1+k/λ)8k / (\pi \lambda) + 18 = O(1 + k / \lambda). Whether ring rr is visited depends only on the rings before it, and the count of ring rr is independent of them, so by Wald's identity the expected number of points seen is λ\lambda times the expected number of cells, which is O(λ+k)O(\lambda + k). Each point costs O(k)O(k) in line L6. The expected time per query is O(1+k/λ+(λ+k)k)O(1 + k / \lambda + (\lambda + k) k), which is O(1)O(1) for fixed kk and λ\lambda.

Complexity

In the ideal model, where the counts are independent Poisson variables and the points are uniform, the points form a Poisson process of intensity λ\lambda. Then E[Fk2]=k/(πλ)E[F_k^2] = k / (\pi \lambda), and the search visits O(1+k/λ)O(1 + k / \lambda) cells and O(λ+k)O(\lambda + k) points on average. Each point costs O(k)O(k) to insert. So a query costs O(1+k/λ+(λ+k)k)O(1 + k / \lambda + (\lambda + k) k) expected time, which is O(1)O(1) for fixed kk and λ\lambda. These are proved bounds in the model. The worst case has no bound, because any number of cells can be empty. The extra space is O(k)O(k), plus the points of one cell. No table is stored.

Properties

  • Exact. The ring search returns the true FkF_k. This is proved.
  • 1-Lipschitz. ∣Fk(x)−Fk(y)∣≤∣x−y∣|F_k(x) - F_k(y)| \le |x - y| for the Euclidean distance. So FkF_k is continuous, but its gradient jumps on the edges of the Voronoi cells, which gives the sharp creases of the texture.
  • Zero at the feature points. F1(p)=0F_1(p) = 0 at each feature point.
  • Deterministic. Each cell makes the same points for the same seed, so the texture is fixed on the object.
  • Not zero mean. Unlike gradient noise, FkF_k is positive and grows with kk. Shift and scale it before you use it as a signed noise.

Variants and improvements

  • One point per cell. A jittered grid with exactly one point per cell is a common GPU form. It usually searches a fixed 3×33 \times 3 block in 2D, or 3×3×33 \times 3 \times 3 in 3D, for a fixed cost. This is still not exact in every case: for xx near a cell corner, the nine points of the block can all lie at a distance near 2\sqrt2, while a point two cells away lies at a distance just over 1. Its pattern is more regular than a Poisson pattern.
  • Combinations. F2−F1F_2 - F_1 for cracks and cell edges, F1+F2F_1 + F_2, products, and the index of the nearest point as a cell ID for a flat color per cell.
  • Other distances. The Manhattan and the Chebyshev distances give diamond and square cells. The ring search is exact for both.
  • Three and more dimensions. The same search works with cubes in place of squares. The cost per ring grows with the dimension.
  • Fractal sums. Summing octaves of F1F_1 gives rough rock and craters, as in fractal noise.

When to use it

Use Worley noise for textures with cells or cracks: stone tiles, dry mud, scales, cells under a microscope, water caustics and foam. Use it as a source of cell IDs for a random color per cell. For smooth hills and clouds, use Perlin noise or simplex noise. When the points are given data, not a procedural texture, use a nearest neighbor search structure such as a k-d tree or a uniform grid.

Pitfalls

  • The 3×33 \times 3 shortcut with a random count. With a Poisson count, the block can be empty, or a point outside it can be nearer. In the code, with λ=0.5\lambda = 0.5, the shortcut gives a wrong F1F_1 for 3.5 percent of 20000 random queries, and with λ=2\lambda = 2 for 1 query in 20000. These are measurements. The errors show as small seams on the cell borders.
  • Too few points for F2F_2 and higher. A block that is large enough for F1F_1 may not be large enough for F3F_3 or F4F_4. The stop test of line L7 handles this, a fixed block does not.
  • A poor cell hash. If the seeds of neighboring cells are correlated, the points line up. Use a well mixed hash of the cell index.
  • Precision far from the origin. Far from the origin, x−⌊x⌋x - \lfloor x \rfloor loses bits in 32-bit floats, and the cells jitter.
  • Aliasing on the creases. The gradient of FkF_k jumps on the Voronoi edges, so F2−F1F_2 - F_1 at a small scale aliases. Filter it or fade it out with the distance. See aliasing.

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.

worley_noise.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/worley-noise/. The authors are listed in prov/KRW8CM.jsonl.

"""Worley noise (cellular noise) in 2D, after Worley 1996.

Space is cut into unit cells. Each cell holds a Poisson number of feature
points, with the mean `density`, placed uniformly in the cell. The count and
the places come from a generator seeded by the seed and the cell index, so
the same cell always holds the same points and no table is stored.

F_k(x) is the distance from x to the k-th nearest feature point. The search
visits the cells in square rings around the cell of x and stops when no cell
outside the rings can hold a point nearer than the current k-th distance.
This makes the result exact. The common shortcut of a 3 x 3 block is exact
only when the cells are never empty and F_k is small, which a Poisson count
does not promise.
"""

import random
from bisect import insort
from math import exp, floor, inf, sqrt

METRICS = {
    "euclidean": lambda dx, dy: sqrt(dx * dx + dy * dy),
    "manhattan": lambda dx, dy: abs(dx) + abs(dy),
    "chebyshev": lambda dx, dy: max(abs(dx), abs(dy)),
}


def poisson(rng, mean):
    """A Poisson sample by Knuth's product of uniforms (fine for a small mean)."""
    limit, k, prod = exp(-mean), 0, rng.random()
    while prod > limit:
        k += 1
        prod *= rng.random()
    return k


def cell_points(seed, i, j, density):
    """The feature points of cell (i, j). A string seed is hashed the same way on every run."""
    rng = random.Random(f"worley:{seed}:{i}:{j}")
    count = poisson(rng, density)
    return [(i + rng.random(), j + rng.random()) for _ in range(count)]


def ring(ci, cj, r):
    """The cells at Chebyshev distance exactly r from the cell (ci, cj)."""
    if r == 0:
        yield ci, cj
        return
    for a in range(-r, r + 1):
        yield ci + a, cj - r
        yield ci + a, cj + r
    for b in range(-r + 1, r):
        yield ci - r, cj + b
        yield ci + r, cj + b


def worley(x, y, k=2, seed=0, density=2.0, metric="euclidean", max_rings=10000):
    """Return [F_1, ..., F_k] at (x, y): the sorted distances to the k nearest points."""
    dist = METRICS[metric]
    ci, cj = floor(x), floor(y)
    fx, fy = x - ci, y - cj
    margin = min(fx, 1 - fx, fy, 1 - fy)  # @line L1
    best = []  # @line L2
    for r in range(max_rings):  # @line L3
        for (i, j) in ring(ci, cj, r):  # @line L4
            for (px, py) in cell_points(seed, i, j, density):  # @line L5
                d = dist(px - x, py - y)
                if len(best) < k or d < best[-1]:
                    insort(best, d)  # @line L6
                    del best[k:]
        if len(best) == k and best[-1] <= r + margin:  # @line L7
            return best  # @line L8
    raise RuntimeError("no k feature points found within max_rings")


class WorleyNoise:
    """Seeded 2D Worley noise. Calling it returns (F1, F2, ..., Fk)."""

    def __init__(self, seed=0, density=2.0, k=2, metric="euclidean"):
        self.seed, self.density, self.k, self.metric = seed, density, k, metric

    def __call__(self, x, y):
        return worley(x, y, self.k, self.seed, self.density, self.metric)

    def f2_minus_f1(self, x, y):
        f = self(x, y)
        return f[1] - f[0]

    def points(self, i, j):
        return cell_points(self.seed, i, j, self.density)


def nearest_brute_force(x, y, points, k, metric="euclidean"):
    """The k smallest distances from (x, y) to a list of points."""
    dist = METRICS[metric]
    return sorted(dist(px - x, py - y) for (px, py) in points)[:k]


def three_by_three(x, y, k=1, seed=0, density=2.0):
    """The common shortcut: search only the 3 x 3 block of cells. Not always exact."""
    ci, cj = floor(x), floor(y)
    pts = []
    for i in range(ci - 1, ci + 2):
        for j in range(cj - 1, cj + 2):
            pts.extend(cell_points(seed, i, j, density))
    out = nearest_brute_force(x, y, pts, k)
    return out + [inf] * (k - len(out))
test_worley_noise.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/worley-noise/. The authors are listed in prov/KRW8CM.jsonl.

"""Tests of Worley noise.

The ring search is checked against a brute force search over every feature
point of a large block of cells. The tests also check the ring enumeration,
determinism for a seed, the 1-Lipschitz bound, the mean point count, and
that the 3 x 3 shortcut is not always exact.
"""

import random
from math import dist as euclid

from worley_noise import (
    WorleyNoise,
    cell_points,
    nearest_brute_force,
    ring,
    three_by_three,
    worley,
)


def block_points(seed, density, lo=-8, hi=8):
    pts = []
    for i in range(lo, hi):
        for j in range(lo, hi):
            pts.extend(cell_points(seed, i, j, density))
    return pts


def test_ring_enumerates_each_cell_once():
    for r in range(6):
        cells = list(ring(3, -2, r))
        assert len(cells) == len(set(cells)) == (1 if r == 0 else 8 * r)
        assert all(max(abs(i - 3), abs(j + 2)) == r for i, j in cells)


def test_equals_brute_force():
    rng = random.Random(1)
    for seed, density in ((0, 2.0), (1, 0.7), (2, 4.0)):
        pts = block_points(seed, density)
        for metric in ("euclidean", "manhattan", "chebyshev"):
            for _ in range(150):
                x, y = rng.uniform(-2, 2), rng.uniform(-2, 2)
                k = rng.randint(1, 4)
                want = nearest_brute_force(x, y, pts, k, metric)
                # Points within distance 6 of a query in [-2, 2]^2 lie in the block.
                assert want[-1] < 6
                assert worley(x, y, k, seed, density, metric) == want


def test_deterministic_for_seed():
    a, b, c = WorleyNoise(seed=5), WorleyNoise(seed=5), WorleyNoise(seed=6)
    rng = random.Random(2)
    pts = [(rng.uniform(-50, 50), rng.uniform(-50, 50)) for _ in range(500)]
    va = [a(*p) for p in pts]
    assert va == [b(*p) for p in pts]
    assert va != [c(*p) for p in pts]


def test_order_zero_at_points_and_lipschitz():
    noise = WorleyNoise(seed=3, k=3)
    for (px, py) in noise.points(0, 0) + noise.points(4, -1):
        assert noise(px, py)[0] == 0.0
    rng = random.Random(3)
    for _ in range(500):
        p = (rng.uniform(-20, 20), rng.uniform(-20, 20))
        q = (p[0] + rng.uniform(-0.3, 0.3), p[1] + rng.uniform(-0.3, 0.3))
        fp, fq = noise(*p), noise(*q)
        assert fp == sorted(fp)
        assert noise.f2_minus_f1(*p) >= 0
        # Each F_k is 1-Lipschitz in the Euclidean metric.
        for a, b in zip(fp, fq):
            assert abs(a - b) <= euclid(p, q) + 1e-12


def test_mean_point_count():
    for density in (0.5, 2.0, 5.0):
        counts = [len(cell_points(9, i, j, density)) for i in range(60) for j in range(60)]
        mean = sum(counts) / len(counts)
        assert abs(mean - density) < 0.15 * density + 0.05


def test_three_by_three_shortcut_is_not_always_exact():
    rng = random.Random(4)
    wrong = 0
    for _ in range(1500):
        x, y = rng.uniform(-100, 100), rng.uniform(-100, 100)
        exact = worley(x, y, 1, seed=7, density=0.5)
        if three_by_three(x, y, 1, seed=7, density=0.5) != exact:
            wrong += 1
    # A measurement: with a mean of 0.5 points per cell a few percent of the
    # queries get a wrong F1 from the shortcut.
    assert wrong > 0

History

Steven Worley published the cellular texture basis function at SIGGRAPH 1996. He scattered feature points through space with a Poisson count per cube, defined FnF_n as the distance to the nn-th nearest point, and showed textures made from linear combinations of F1F_1 to F4F_4. The idea complements Perlin noise, whose features are smooth and have no edges. Later GPU code often used one jittered point per cell and a fixed 3×33 \times 3 block, which trades exactness and some randomness for a fixed cost.

References

  1. Steven Worley, A cellular texture basis function, SIGGRAPH 1996, pages 291 to 294, the whole paper (feature points with a Poisson count per cube, the functions F_n, and the search of the neighboring cubes)
  2. 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 chapter by Worley on cellular texturing (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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • 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
  • at least three sources
  • a scene preset for the example