Skip to content
Voronoi diagram over a fantasy map, dividing forest, desert, and snow biomes into polygon cells

Voronoi Diagrams in Game Development — Procedural Maps, AI Territories & Stylish Effects

Every pixel belongs to its nearest seed. Click to drop a new one.

Voronoi diagrams are how game development turns a blank map into regions that look grown instead of gridded: kingdoms and provinces, biomes, faction territories, cracked stone and glowing force fields. Scatter a handful of points, give every spot on the map to the point nearest to it, and the world splits into organic cells. The hero above is doing exactly that, live, with the code from this page.

In this tutorial, you’ll build a Voronoi diagram from scratch, then use it four ways: an island world map with biomes, AI territories that shift when a base falls, evenly spaced regions with Lloyd relaxation, and cell-noise textures for stone, lava and shields. Then you’ll put it all together and paint the whole island as a game-ready map. Eight hands-on labs show every step. The code comes in JavaScript, C#, C++ and pseudocode, all seeded, so the same seed builds the same map in every language, and the JavaScript is the exact code running in the labs.

What Is a Voronoi Diagram?

Imagine dropping a handful of seeds on the ground. Now imagine each seed growing into a patch of land that extends until it touches the edges of its neighbors. That’s the intuition behind Voronoi diagrams.

Formally, a Voronoi diagram splits space into cells around a set of points called sites. Each cell holds every location that is closer to its site than to any other site. Two facts fall out of that definition:

  • Borders are halfway lines. Every point on the border between two cells is the same distance from both sites, so the border is a piece of the line exactly halfway between them.
  • Corners are three-way ties. Where three cells meet, the point is equally far from all three sites.

The idea is old: it’s named after the mathematician Georgy Voronoy, who studied it in 1908, and geographers call the same cells Thiessen polygons. You’ve seen the pattern all over the place:

  • Nature: giraffe patches, dragonfly wings, cracked mud and soap foam all look a lot like Voronoi cells.
  • Everyday maps: “nearest hospital” and “which cell tower serves this street” are Voronoi questions.
  • Games: region maps, influence maps, destruction and stone shaders. You’ll build all of them below.
Glowing green cell walls in a Voronoi pattern, each cell holding a different miniature biome of mushrooms, crystals, and pools

Before any code, watch the definition happen. Each seed below claims ground at the same speed.

Lab: Grow the Seeds

Every seed claims ground at the same speed. A patch stops where it meets a neighbor, and that meeting line is exactly halfway between the two seeds. When nothing is left to claim, you're looking at a Voronoi diagram.

👉 Try this: press Grow and watch the patches meet. Then drag Radius back and forth around the moment two patches touch. They always meet exactly halfway between their two seeds, which is why every border is a straight line. Change Seeds to 3, then to 40: the rule never changes, only the number of neighbors.

Why Use Voronoi Diagrams in Game Development?

  • Procedural maps: countries, provinces, biomes and city districts that look organic, and you get the list of which regions border which for free. That’s Lab #4.
  • AI territories and influence maps: make each base a site and its cell is the land it controls. Spawn units there, keep patrols inside it, and when a base falls, its neighbors split its land with no extra code. That’s Lab #5.
  • Placement: one site per settlement, dungeon room or resource node, and its cell is that thing’s catchment area: which village owns which farmland, which spawner covers which corridor.
  • Stylized visuals: the distances to the nearest sites make cell noise, the basis of countless stone, scale, crack, caustic and force-field shaders. That’s Lab #6.
  • Destruction: fracture tools cut a mesh into Voronoi cells to make convincing shards. Unreal Engine’s Chaos Destruction does exactly that (more below).

Behind the Scenes: Two Ways to Build One

There are two classic ways to compute a Voronoi diagram, and this tutorial uses both:

  • Ask every pixel. For each pixel (or tile), check every site and keep the nearest. It’s a dozen lines of code, works in any language and on any grid, and handles any distance metric. The cost is pixels × sites, which is fine for game-sized maps.
  • Build the cells directly. Clever algorithms produce the exact polygons in O(n log n) time: Steven Fortune’s sweep-line algorithm (1986), or a Delaunay triangulation and its “dual”, which is what the d3-delaunay library does. You’ll use it in Lab #2.

For a beautiful visual explanation of the geometry, bookmark Red Blob Games’ polygon map generation article, which Lab #4 borrows ideas from.

Step-by-Step Lab #1: Build a Voronoi Diagram From Scratch

No libraries: just sites, distances and a loop. This version is the one you’ll reach for in a tile-based game, a shader or an engine without a geometry library, and it’s the foundation for everything else on this page.

Step 1: Seeded Sites

Games need randomness you can repeat. If a player shares seed 123456, everyone should get the same continents. So instead of Math.random(), we use the same SeededRandom class as our Perlin noise, Cellular Automata and Biome tutorials: a tiny Lehmer generator that gives identical numbers in JavaScript, C# and C++.

makeSites() scatters count sites across a width × height map. A site is just an [x, y] pair. In C#, these methods live in a static class; ours is called VoronoiGen. Every JavaScript, C# and C++ block is fully commented; hover it and click Hide comments for the compact version (one click switches every block on the page).

/*
  Step 1: Seeded sites
  --------------------
  A Voronoi diagram starts with its sites: the "seeds" each region grows from.
  We scatter them with a seeded random number generator, so the same seed
  always gives the same map (and a bug report about seed 42 can be replayed).
*/
class SeededRandom {
  constructor(seed) {
    // Park-Miller "minimal standard" generator: the state must stay in 1..2^31 - 2.
    this.seed = seed % 2147483647;
    if (this.seed <= 0) this.seed += 2147483646;
  }

  next() {
    // Multiply by 16807 and wrap around the prime 2^31 - 1.
    return this.seed = this.seed * 16807 % 2147483647;
  }

  nextFloat() {
    // Map 1..2147483646 onto 0..1 (0 included, 1 excluded).
    return (this.next() - 1) / 2147483646;
  }
}

function makeSites(count, width, height, seed) {
  const random = new SeededRandom(seed);
  const sites = [];
  for (let i = 0; i < count; i++) {
    const x = random.nextFloat() * width;   // anywhere across the map...
    const y = random.nextFloat() * height;  // ...and anywhere down it
    sites.push([x, y]);                     // a site is just an [x, y] pair
  }
  return sites;
}
/*
  Explanation:
  - The same SeededRandom class runs our Perlin, Cellular Automata and Biome tutorials,
    so a seed means the same thing everywhere on Game Genius Lab.
  - makeSites(20, 720, 400, 123456) always returns the same 20 points.
  Next step: decide which site owns any given point.
*/
// Step 1: Seeded sites
// --------------------
// A Voronoi diagram starts with its sites: the "seeds" each region grows from.
// We scatter them with a seeded random number generator, so the same seed always
// gives the same map. The methods below go inside a static class (ours is VoronoiGen).
using System;
using System.Collections.Generic;

public class SeededRandom
{
    private long seed;
    private const long a = 16807;        // Park-Miller "minimal standard" multiplier
    private const long m = 2147483647;   // the prime 2^31 - 1

    public SeededRandom(int seed)
    {
        // The state must stay in 1..m - 1, so fold 0 and negative seeds into range.
        this.seed = seed % m;
        if (this.seed <= 0) this.seed += m - 1;
    }

    public int Next()
    {
        seed = a * seed % m;   // long math: a * seed never overflows
        return (int)seed;
    }

    public double NextFloat()
    {
        // Map 1..m - 1 onto 0..1 (0 included, 1 excluded).
        return (Next() - 1) / (double)(m - 1);
    }
}

public static List<(double X, double Y)> MakeSites(int count, double width, double height, int seed)
{
    var random = new SeededRandom(seed);
    var sites = new List<(double X, double Y)>();
    for (int i = 0; i < count; i++)
    {
        double x = random.NextFloat() * width;    // anywhere across the map...
        double y = random.NextFloat() * height;   // ...and anywhere down it
        sites.Add((x, y));
    }
    return sites;
}
// Same seed, same numbers, same sites as the JavaScript and C++ versions.
// Next step: decide which site owns any given point.
// Step 1: Seeded sites
// --------------------
// A Voronoi diagram starts with its sites: the "seeds" each region grows from.
// We scatter them with a seeded random number generator, so the same seed always gives the same map.
#include <vector>

class SeededRandom {
private:
  long long seed;
  static const long long a = 16807;        // Park-Miller "minimal standard" multiplier
  static const long long m = 2147483647;   // the prime 2^31 - 1

public:
  SeededRandom(int seed) : seed(seed % m) {
    // The state must stay in 1..m - 1, so fold 0 and negative seeds into range.
    if (this->seed <= 0) this->seed += m - 1;
  }

  int Next() {
    seed = a * seed % m;   // 64-bit math: a * seed never overflows
    return static_cast<int>(seed);
  }

  // Map 1..m - 1 onto 0..1 (0 included, 1 excluded).
  double NextFloat() { return (Next() - 1) / static_cast<double>(m - 1); }
};

struct Site {
  double x;
  double y;
};

std::vector<Site> makeSites(int count, double width, double height, int seed) {
  SeededRandom random(seed);
  std::vector<Site> sites;
  for (int i = 0; i < count; i++) {
    double x = random.NextFloat() * width;    // anywhere across the map...
    double y = random.NextFloat() * height;   // ...and anywhere down it
    sites.push_back({x, y});
  }
  return sites;
}
// Same seed, same numbers, same sites as the JavaScript and C# versions.
// Next step: decide which site owns any given point.
// Step 1: Seeded sites
// --------------------
// Scatter the sites (the seeds each region grows from) with a seeded generator,
// so the same seed always gives the same map.

CLASS SeededRandom
    METHOD constructor(seed)
        DECLARE this.seed = seed MOD 2147483647
        IF this.seed <= 0 THEN
            this.seed = this.seed + 2147483646
        END IF
    END METHOD

    METHOD next()
        this.seed = (this.seed * 16807) MOD 2147483647
        RETURN this.seed
    END METHOD

    METHOD nextFloat()
        RETURN (this.next() - 1) / 2147483646   // 0 up to (but not including) 1
    END METHOD
END CLASS

FUNCTION makeSites(count, width, height, seed)
    DECLARE random = NEW SeededRandom(seed)
    DECLARE sites = EMPTY_ARRAY
    FOR i FROM 1 TO count DO
        DECLARE x = random.nextFloat() * width
        DECLARE y = random.nextFloat() * height
        APPEND [x, y] TO sites
    END FOR
    RETURN sites
END FUNCTION

Step 2: Find the Nearest Site

This is the definition from above, turned into code: nearestSite() measures the distance from a point to every site and returns the index of the closest one.

“Closest” depends on how you measure, so distance() takes a metric:

  • Euclidean: a straight line, as the crow flies. Borders are straight lines at any angle.
  • Manhattan: walk across, then down, like a city grid or a unit that moves in 4 directions. Borders are made of horizontal, vertical and 45° pieces.
  • Chebyshev: diagonal steps cost the same as straight ones, like a chess king or 8-way movement. Borders come out boxy, again in horizontal, vertical and 45° pieces.
/*
  Step 2: Find the nearest site
  -----------------------------
  This is the whole definition of a Voronoi diagram: a point belongs to the site
  closest to it. "Closest" depends on how you measure distance, so we make the
  metric a parameter.
*/
const Metric = { Euclidean: "euclidean", Manhattan: "manhattan", Chebyshev: "chebyshev" };

function distance(ax, ay, bx, by, metric = Metric.Euclidean) {
  const dx = Math.abs(ax - bx);
  const dy = Math.abs(ay - by);
  if (metric === Metric.Manhattan) return dx + dy;            // city blocks: walk across, then down
  if (metric === Metric.Chebyshev) return Math.max(dx, dy);   // king moves: diagonals cost the same as straights
  return Math.sqrt(dx * dx + dy * dy);                        // a straight line, as the crow flies
}

function nearestSite(sites, x, y, metric = Metric.Euclidean) {
  let nearest = 0;
  let best = Infinity;
  for (let i = 0; i < sites.length; i++) {
    const d = distance(x, y, sites[i][0], sites[i][1], metric);
    if (d < best) {   // strictly closer: on an exact tie, the lower index wins
      best = d;
      nearest = i;
    }
  }
  return nearest;
}
/*
  Explanation:
  - nearestSite() checks every site, so it costs one distance per site. That's fine
    for a few hundred sites; Lab #2 shows the fast way to get exact cell shapes.
  - Manhattan and Chebyshev distances match grid games: 4-way and 8-way movement.
  Next step: ask that question for every pixel on the map.
*/
// Step 2: Find the nearest site
// -----------------------------
// A point belongs to the site closest to it. "Closest" depends on how you measure
// distance, so the metric is a parameter.
public enum Metric { Euclidean, Manhattan, Chebyshev }

public static double Distance(double ax, double ay, double bx, double by, Metric metric = Metric.Euclidean)
{
    double dx = Math.Abs(ax - bx);
    double dy = Math.Abs(ay - by);
    if (metric == Metric.Manhattan) return dx + dy;            // city blocks: across, then down
    if (metric == Metric.Chebyshev) return Math.Max(dx, dy);   // king moves: diagonals cost the same
    return Math.Sqrt(dx * dx + dy * dy);                       // a straight line
}

public static int NearestSite(List<(double X, double Y)> sites, double x, double y, Metric metric = Metric.Euclidean)
{
    int nearest = 0;
    double best = double.PositiveInfinity;
    for (int i = 0; i < sites.Count; i++)
    {
        double d = Distance(x, y, sites[i].X, sites[i].Y, metric);
        if (d < best)   // strictly closer: on an exact tie, the lower index wins
        {
            best = d;
            nearest = i;
        }
    }
    return nearest;
}
// One distance check per site. Manhattan and Chebyshev match 4-way and 8-way grid movement.
// Next step: ask that question for every pixel (or tile) of the map.
// Step 2: Find the nearest site
// -----------------------------
// A point belongs to the site closest to it. "Closest" depends on how you measure
// distance, so the metric is a parameter.
#include <algorithm>
#include <cmath>
#include <limits>

enum class Metric { Euclidean, Manhattan, Chebyshev };

double distance(double ax, double ay, double bx, double by, Metric metric = Metric::Euclidean) {
  double dx = std::abs(ax - bx);
  double dy = std::abs(ay - by);
  if (metric == Metric::Manhattan) return dx + dy;              // city blocks: across, then down
  if (metric == Metric::Chebyshev) return std::max(dx, dy);     // king moves: diagonals cost the same
  return std::sqrt(dx * dx + dy * dy);                          // a straight line
}

int nearestSite(const std::vector<Site>& sites, double x, double y, Metric metric = Metric::Euclidean) {
  int nearest = 0;
  double best = std::numeric_limits<double>::infinity();
  for (int i = 0; i < (int)sites.size(); i++) {
    double d = distance(x, y, sites[i].x, sites[i].y, metric);
    if (d < best) {   // strictly closer: on an exact tie, the lower index wins
      best = d;
      nearest = i;
    }
  }
  return nearest;
}
// One distance check per site. Manhattan and Chebyshev match 4-way and 8-way grid movement.
// Next step: ask that question for every pixel (or tile) of the map.
// Step 2: Find the nearest site
// -----------------------------
// A point belongs to the site closest to it. The metric decides what "closest" means.

FUNCTION distance(ax, ay, bx, by, metric = EUCLIDEAN)
    DECLARE dx = ABS(ax - bx)
    DECLARE dy = ABS(ay - by)
    IF metric = MANHATTAN THEN
        RETURN dx + dy                  // city blocks
    ELSE IF metric = CHEBYSHEV THEN
        RETURN MAX(dx, dy)              // king moves
    END IF
    RETURN SQRT(dx * dx + dy * dy)      // straight line
END FUNCTION

FUNCTION nearestSite(sites, x, y, metric = EUCLIDEAN)
    DECLARE nearest = 0
    DECLARE best = INFINITY
    FOR i FROM 0 TO LENGTH(sites) - 1 DO
        DECLARE d = distance(x, y, sites[i].x, sites[i].y, metric)
        IF d < best THEN                // strictly closer: ties go to the lower index
            best = d
            nearest = i
        END IF
    END FOR
    RETURN nearest
END FUNCTION

Step 3: Color Every Pixel

Ask nearestSite() for every pixel and store the answers, and you have an owner map: one site index per pixel. That is a Voronoi diagram, on a grid. Draw each owner in its own color, or use the owner map directly as your tile map’s region layer. A border is simply wherever two neighboring pixels have different owners.

/*
  Step 3: Color every pixel
  -------------------------
  Ask nearestSite() for every pixel and store the answer. The result is an
  "owner map": one site index per pixel, which is exactly a Voronoi diagram
  on a grid, ready to draw or to use as a tile map.
*/
function voronoiGrid(sites, width, height, metric = Metric.Euclidean) {
  const owners = new Int32Array(width * height);   // one entry per pixel, row by row
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      // + 0.5 measures from the pixel's center rather than its top-left corner.
      owners[y * width + x] = nearestSite(sites, x + 0.5, y + 0.5, metric);
    }
  }
  return owners;
}
/*
  Explanation:
  - owners[y * width + x] is the index of the site that owns pixel (x, y).
  - A border is wherever two neighboring pixels have different owners.
  - Cost: width x height x sites distance checks. 720 x 400 with 20 sites is about
    5.8 million, a few milliseconds in a modern browser.
  Next step: the exact, fast version with Delaunay triangulation.
*/
// Step 3: Color every pixel
// -------------------------
// Ask NearestSite() for every pixel and store the answer: an "owner map" with one
// site index per pixel. That's a Voronoi diagram on a grid, ready to draw or to use as a tile map.
public static int[] VoronoiGrid(List<(double X, double Y)> sites, int width, int height, Metric metric = Metric.Euclidean)
{
    var owners = new int[width * height];   // one entry per pixel, row by row
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            // + 0.5 measures from the pixel's center rather than its top-left corner.
            owners[y * width + x] = NearestSite(sites, x + 0.5, y + 0.5, metric);
        }
    }
    return owners;
}
// owners[y * width + x] is the site that owns pixel (x, y). In Unity you might write
// these into a Texture2D or a Tilemap; a border is wherever two neighbors differ.
// Step 3: Color every pixel
// -------------------------
// Ask nearestSite() for every pixel and store the answer: an "owner map" with one site
// index per pixel. That's a Voronoi diagram on a grid, ready to draw or to use as a tile map.
std::vector<int> voronoiGrid(const std::vector<Site>& sites, int width, int height, Metric metric = Metric::Euclidean) {
  std::vector<int> owners(width * height);   // one entry per pixel, row by row
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      // + 0.5 measures from the pixel's center rather than its top-left corner.
      owners[y * width + x] = nearestSite(sites, x + 0.5, y + 0.5, metric);
    }
  }
  return owners;
}
// owners[y * width + x] is the site that owns pixel (x, y); a border is wherever two neighbors differ.
// Step 3: Color every pixel
// -------------------------
// Store nearestSite() for every pixel: the "owner map" is a Voronoi diagram on a grid.

FUNCTION voronoiGrid(sites, width, height, metric = EUCLIDEAN)
    DECLARE owners = NEW ARRAY OF (width * height) INTEGERS
    FOR y FROM 0 TO height - 1 DO
        FOR x FROM 0 TO width - 1 DO
            // Measure from the pixel's center.
            owners[y * width + x] = nearestSite(sites, x + 0.5, y + 0.5, metric)
        END FOR
    END FOR
    RETURN owners
END FUNCTION

// A border is wherever two neighboring pixels have different owners.

Here’s voronoiGrid() running on a 720 × 400 canvas, plus nearestSite() for a point you can drag around.

Lab: Nearest Site & Distance Metrics

Drag the white dot. The outlined shape is every point at the same distance as the nearest site: a circle, a diamond or a square, depending on the metric. No other site is ever inside it.

👉 Try this: drag the white dot onto a border and watch the runner-up distance catch up with the winner. Then switch to Manhattan and Chebyshev. Same sites, very different cells, because the shape of “equally far” changes from a circle to a diamond to a square. If your units move on a grid, the matching metric gives territories that agree with how far they can actually walk.

Step-by-Step Lab #2: Exact Cells With Delaunay Triangulation

The pixel method answers “who owns this point?” Sometimes you need the cells themselves: polygons to fill and outline, to turn into meshes, or to ask “which regions border this one?” That’s where Delaunay triangulation comes in.

A Delaunay triangulation (Boris Delaunay, 1934) connects the sites into triangles so that no site lies inside any triangle’s circumcircle, the circle through its three corners. It’s the Voronoi diagram’s dual, its mirror image:

  • Every triangle’s circumcenter is a Voronoi corner, the three-way tie from earlier.
  • Every triangle edge joins two sites whose cells share a border. So the triangulation is the region adjacency graph.

The d3-delaunay library builds both, fast. It’s based on Mapbox’s Delaunator, which also has ports for C# (NuGet package Delaunator, also on OpenUPM for Unity) and C++. The code below is JavaScript and pseudocode only, because it calls the library.

Step 4: Build and Draw the Cells

buildVoronoi() triangulates the sites and clips the cells to the map. drawVoronoi() fills each cell, strokes every edge and marks the sites.

/*
  Step 4: Exact cells with d3-delaunay
  ------------------------------------
  The pixel method answers "who owns this point?". When you need the cells
  themselves (polygons to fill, outline or hand to a physics engine) and which
  cells touch, build the Delaunay triangulation and take its dual.
*/
import { Delaunay } from "https://cdn.jsdelivr.net/npm/d3-delaunay@6/+esm";

function buildVoronoi(sites, width, height) {
  // Delaunay.from() triangulates the sites: no site lies inside any triangle's circumcircle.
  const delaunay = Delaunay.from(sites);
  // .voronoi() turns that into cells, clipped to the map's bounds [xmin, ymin, xmax, ymax].
  return delaunay.voronoi([0, 0, width, height]);
}

function drawVoronoi(ctx, voronoi, sites, colors) {
  // Fill each cell. renderCell(i, ctx) traces cell i's polygon onto the canvas path.
  for (let i = 0; i < sites.length; i++) {
    ctx.fillStyle = colors[i % colors.length];
    ctx.beginPath();
    voronoi.renderCell(i, ctx);
    ctx.fill();
  }
  // Then every edge at once, plus the map's outer border.
  ctx.strokeStyle = "#111111";
  ctx.lineWidth = 1.5;
  ctx.beginPath();
  voronoi.render(ctx);
  voronoi.renderBounds(ctx);
  ctx.stroke();
  // Finally the sites themselves, as small dots.
  ctx.fillStyle = "#111111";
  for (const [x, y] of sites) {
    ctx.beginPath();
    ctx.arc(x, y, 3, 0, 2 * Math.PI);
    ctx.fill();
  }
}
/*
  Explanation:
  - voronoi.cellPolygon(i) gives cell i's corners as [x, y] pairs.
  - voronoi.neighbors(i) lists the cells that share an edge with cell i:
    the adjacency graph for borders, trade routes or region-to-region pathfinding.
  - voronoi.delaunay.find(x, y) returns the site nearest to (x, y), like nearestSite(), but fast.
  Next step: use the cells to space the sites out evenly.
*/
// Step 4: Exact cells with d3-delaunay
// ------------------------------------
// Triangulate the sites (Delaunay), then take the dual to get exact cell polygons.

IMPORT Delaunay FROM "d3-delaunay"

FUNCTION buildVoronoi(sites, width, height)
    DECLARE delaunay = Delaunay.FROM(sites)            // no site inside any triangle's circumcircle
    RETURN delaunay.VORONOI([0, 0, width, height])     // cells clipped to the map bounds
END FUNCTION

FUNCTION drawVoronoi(ctx, voronoi, sites, colors)
    FOR i FROM 0 TO LENGTH(sites) - 1 DO
        SET ctx.fillStyle TO colors[i MOD LENGTH(colors)]
        ctx.BEGIN_PATH()
        voronoi.RENDER_CELL(i, ctx)                    // trace cell i's polygon
        ctx.FILL()
    END FOR
    SET ctx.strokeStyle TO "#111111"
    ctx.BEGIN_PATH()
    voronoi.RENDER(ctx)                                // every cell edge
    voronoi.RENDER_BOUNDS(ctx)                         // the map's outer border
    ctx.STROKE()
    FOR EACH [x, y] IN sites DO
        DRAW_DOT(ctx, x, y, 3)
    END FOR
END FUNCTION

// voronoi.CELL_POLYGON(i) gives cell i's corners; voronoi.NEIGHBORS(i) lists the cells it touches.

Lab: Voronoi & Delaunay, Two Views of One Map

Click near a site to select its cell and see its neighbors, click open space to add a site, drag a site to move it. Turn on the triangles: every Delaunay edge joins two cells that share a border.

👉 Try this: tick Delaunay triangles. Each coral line joins two sites whose cells share a border, so the triangles are the map’s neighbor graph. Now tick Circumcircles: every circle passes through three sites and contains none, and its center sits exactly on a Voronoi corner. Finally, drag a site across the map and watch its neighbor list change. In a strategy game, that list is “which provinces can this army march into.”

Step-by-Step Lab #3: Even Out the Cells With Lloyd Relaxation

Random sites clump. Some cells come out tiny and others huge, and long, thin slivers appear. For a world map, that reads as noise rather than design.

Lloyd’s algorithm (Stuart Lloyd, Bell Labs, 1957) fixes it with one simple move: send every site to the centroid (the center of mass) of its own cell, then rebuild the diagram. Crowded sites push apart, lonely ones drift into the gaps, and after a few rounds the cells are even but still organic. Amit Patel’s map generator for Realm of the Mad God used exactly this in its first version.

Step 5: Move Each Site to Its Centroid

relaxSites() reuses voronoiGrid(), adds up the pixel positions in each cell, and divides by the count. One call is one round.

/*
  Step 5: Lloyd relaxation
  ------------------------
  Random sites clump: some cells come out tiny, others huge. Lloyd's algorithm
  fixes that by moving every site to the centroid (center of mass) of its own
  cell, then rebuilding. A couple of rounds gives even, organic-looking cells.
*/
function relaxSites(sites, width, height) {
  const owners = voronoiGrid(sites, width, height);
  const sumX = new Float64Array(sites.length);   // running totals per cell
  const sumY = new Float64Array(sites.length);
  const count = new Int32Array(sites.length);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const owner = owners[y * width + x];
      sumX[owner] += x + 0.5;                      // add this pixel's center to its cell's totals
      sumY[owner] += y + 0.5;
      count[owner]++;
    }
  }
  // Each cell's centroid is the average of its pixels. A cell with no pixels keeps its site.
  return sites.map(([x, y], i) => count[i] > 0 ? [sumX[i] / count[i], sumY[i] / count[i]] : [x, y]);
}
/*
  Explanation:
  - One call is one round. Call it in a loop: for (let i = 0; i < 2; i++) sites = relaxSites(sites, w, h);
  - Each round moves sites less than the one before; after a handful the map barely changes.
  - Too many rounds makes cells look like a uniform honeycomb. One to three is the sweet spot for maps.
  Next step: turn the cells into a world.
*/
// Step 5: Lloyd relaxation
// ------------------------
// Random sites clump. Move every site to the centroid (center of mass) of its own
// cell, then rebuild. A couple of rounds gives even, organic-looking cells.
public static List<(double X, double Y)> RelaxSites(List<(double X, double Y)> sites, int width, int height)
{
    int[] owners = VoronoiGrid(sites, width, height);
    var sumX = new double[sites.Count];   // running totals per cell
    var sumY = new double[sites.Count];
    var count = new int[sites.Count];
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            int owner = owners[y * width + x];
            sumX[owner] += x + 0.5;   // add this pixel's center to its cell's totals
            sumY[owner] += y + 0.5;
            count[owner]++;
        }
    }
    var relaxed = new List<(double X, double Y)>();
    for (int i = 0; i < sites.Count; i++)
    {
        // The centroid is the average of the cell's pixels. A cell with no pixels keeps its site.
        relaxed.Add(count[i] > 0 ? (sumX[i] / count[i], sumY[i] / count[i]) : sites[i]);
    }
    return relaxed;
}
// One call is one round: for (int i = 0; i < 2; i++) sites = RelaxSites(sites, w, h);
// One to three rounds is the sweet spot for maps; many more turns them into a honeycomb.
// Step 5: Lloyd relaxation
// ------------------------
// Random sites clump. Move every site to the centroid (center of mass) of its own
// cell, then rebuild. A couple of rounds gives even, organic-looking cells.
std::vector<Site> relaxSites(const std::vector<Site>& sites, int width, int height) {
  std::vector<int> owners = voronoiGrid(sites, width, height);
  std::vector<double> sumX(sites.size(), 0.0), sumY(sites.size(), 0.0);   // running totals per cell
  std::vector<int> count(sites.size(), 0);
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      int owner = owners[y * width + x];
      sumX[owner] += x + 0.5;   // add this pixel's center to its cell's totals
      sumY[owner] += y + 0.5;
      count[owner]++;
    }
  }
  std::vector<Site> relaxed;
  for (size_t i = 0; i < sites.size(); i++) {
    // The centroid is the average of the cell's pixels. A cell with no pixels keeps its site.
    if (count[i] > 0) relaxed.push_back({sumX[i] / count[i], sumY[i] / count[i]});
    else relaxed.push_back(sites[i]);
  }
  return relaxed;
}
// One call is one round: for (int i = 0; i < 2; i++) sites = relaxSites(sites, w, h);
// Step 5: Lloyd relaxation
// ------------------------
// Move every site to the centroid of its own cell. Repeat one to three times.

FUNCTION relaxSites(sites, width, height)
    DECLARE owners = voronoiGrid(sites, width, height)
    DECLARE sumX = NEW ARRAY OF LENGTH(sites) ZEROS
    DECLARE sumY = NEW ARRAY OF LENGTH(sites) ZEROS
    DECLARE count = NEW ARRAY OF LENGTH(sites) ZEROS
    FOR y FROM 0 TO height - 1 DO
        FOR x FROM 0 TO width - 1 DO
            DECLARE owner = owners[y * width + x]
            sumX[owner] = sumX[owner] + x + 0.5
            sumY[owner] = sumY[owner] + y + 0.5
            count[owner] = count[owner] + 1
        END FOR
    END FOR
    DECLARE relaxed = EMPTY_ARRAY
    FOR i FROM 0 TO LENGTH(sites) - 1 DO
        IF count[i] > 0 THEN
            APPEND [sumX[i] / count[i], sumY[i] / count[i]] TO relaxed   // the cell's centroid
        ELSE
            APPEND sites[i] TO relaxed                                   // empty cell: keep the site
        END IF
    END FOR
    RETURN relaxed
END FUNCTION

Lab: Lloyd Relaxation

Each arrow points from a site to the center of mass of its cell. Step moves every site along its arrow and rebuilds the cells. Watch the size spread fall: cramped cells grow, huge ones shrink, and the map settles into an even, organic honeycomb.

👉 Try this: press Step a few times and watch the cell size spread. The first step makes the biggest change, and each one after moves the sites less. Press Play to run until nothing moves. One to three rounds is the sweet spot for maps. Run it to the end and the cells turn into a near-uniform honeycomb, which is great for a hex-like board and too tidy for a coastline.

Step-by-Step Lab #4: A Voronoi World Map With Biomes

Now let’s turn regions into a world. The trick is to make decisions per cell, not per pixel: every pixel of a region shares its cell’s biome, so you get clean, readable regions, and every rule works on a few dozen cells instead of thousands of pixels.

Step 6: Give Every Region a Biome

assignBiomes() makes two decisions:

  • Edge cells are ocean. Any cell that touches the map’s border becomes ocean, so the land is always an island surrounded by water. Red Blob Games’ map generator has the same rule: the map’s boundary is always water.
  • Latitude sets the climate. Inland cells pick a biome from how far down the map they sit, nudged by a little seeded randomness: tundra in the cold north, then forest, plains and swamp, and desert in the hot south.
/*
  Step 6: Give every region a biome
  ---------------------------------
  Each cell becomes a region of the world. Cells that touch the map edge turn
  into ocean, so the land is always an island. Inland cells pick a biome from
  their latitude (cold north, hot south) plus a little seeded randomness.
*/
const BIOME_COLORS = {
  Ocean: "#2E5A88",
  Tundra: "#E0FFFF",
  Forest: "#228B22",
  Plains: "#98FB98",
  Swamp: "#556B2F",
  Desert: "#EDC9AF"
};

function assignBiomes(sites, owners, width, height, seed) {
  const random = new SeededRandom(seed);
  // Mark every cell that owns a pixel on the map's border.
  const ocean = new Uint8Array(sites.length);
  for (let x = 0; x < width; x++) {
    ocean[owners[x]] = 1;                           // top row
    ocean[owners[(height - 1) * width + x]] = 1;    // bottom row
  }
  for (let y = 0; y < height; y++) {
    ocean[owners[y * width]] = 1;                   // left column
    ocean[owners[y * width + width - 1]] = 1;       // right column
  }
  return sites.map(([x, y], i) => {
    if (ocean[i]) return "Ocean";
    // t runs from 0 at the top of the map to 1 at the bottom, nudged by up to +/- 0.15.
    const t = y / height + (random.nextFloat() - 0.5) * 0.3;
    if (t < 0.3) return "Tundra";
    if (t < 0.45) return "Forest";
    if (t < 0.6) return "Plains";
    if (t < 0.72) return "Swamp";
    return "Desert";
  });
}
/*
  Explanation:
  - The biome belongs to the cell, so every pixel of a region shares it: biomes[owners[y * width + x]].
  - Swap latitude for real climate (temperature and moisture noise) and you get the
    full system from our Procedural Biome Generation tutorial.
  Next step: put it all together.
*/
// Step 6: Give every region a biome
// ---------------------------------
// Cells that touch the map edge become ocean, so the land is always an island.
// Inland cells pick a biome from their latitude (cold north, hot south) plus a little seeded randomness.
public static readonly Dictionary<string, string> BiomeColors = new Dictionary<string, string>
{
    { "Ocean", "#2E5A88" },
    { "Tundra", "#E0FFFF" },
    { "Forest", "#228B22" },
    { "Plains", "#98FB98" },
    { "Swamp", "#556B2F" },
    { "Desert", "#EDC9AF" }
};

public static string[] AssignBiomes(List<(double X, double Y)> sites, int[] owners, int width, int height, int seed)
{
    var random = new SeededRandom(seed);
    // Mark every cell that owns a pixel on the map's border.
    var ocean = new bool[sites.Count];
    for (int x = 0; x < width; x++)
    {
        ocean[owners[x]] = true;                          // top row
        ocean[owners[(height - 1) * width + x]] = true;   // bottom row
    }
    for (int y = 0; y < height; y++)
    {
        ocean[owners[y * width]] = true;                  // left column
        ocean[owners[y * width + width - 1]] = true;      // right column
    }
    var biomes = new string[sites.Count];
    for (int i = 0; i < sites.Count; i++)
    {
        if (ocean[i]) { biomes[i] = "Ocean"; continue; }
        // t runs from 0 at the top of the map to 1 at the bottom, nudged by up to +/- 0.15.
        double t = sites[i].Y / height + (random.NextFloat() - 0.5) * 0.3;
        if (t < 0.3) biomes[i] = "Tundra";
        else if (t < 0.45) biomes[i] = "Forest";
        else if (t < 0.6) biomes[i] = "Plains";
        else if (t < 0.72) biomes[i] = "Swamp";
        else biomes[i] = "Desert";
    }
    return biomes;
}
// Every pixel of a region shares its cell's biome: biomes[owners[y * width + x]].
// Step 6: Give every region a biome
// ---------------------------------
// Cells that touch the map edge become ocean, so the land is always an island.
// Inland cells pick a biome from their latitude (cold north, hot south) plus a little seeded randomness.
#include <map>
#include <string>

const std::map<std::string, std::string> BIOME_COLORS = {
  {"Ocean", "#2E5A88"},
  {"Tundra", "#E0FFFF"},
  {"Forest", "#228B22"},
  {"Plains", "#98FB98"},
  {"Swamp", "#556B2F"},
  {"Desert", "#EDC9AF"}
};

std::vector<std::string> assignBiomes(const std::vector<Site>& sites, const std::vector<int>& owners, int width, int height, int seed) {
  SeededRandom random(seed);
  // Mark every cell that owns a pixel on the map's border.
  std::vector<bool> ocean(sites.size(), false);
  for (int x = 0; x < width; x++) {
    ocean[owners[x]] = true;                          // top row
    ocean[owners[(height - 1) * width + x]] = true;   // bottom row
  }
  for (int y = 0; y < height; y++) {
    ocean[owners[y * width]] = true;                  // left column
    ocean[owners[y * width + width - 1]] = true;      // right column
  }
  std::vector<std::string> biomes;
  for (size_t i = 0; i < sites.size(); i++) {
    if (ocean[i]) { biomes.push_back("Ocean"); continue; }
    // t runs from 0 at the top of the map to 1 at the bottom, nudged by up to +/- 0.15.
    double t = sites[i].y / height + (random.NextFloat() - 0.5) * 0.3;
    if (t < 0.3) biomes.push_back("Tundra");
    else if (t < 0.45) biomes.push_back("Forest");
    else if (t < 0.6) biomes.push_back("Plains");
    else if (t < 0.72) biomes.push_back("Swamp");
    else biomes.push_back("Desert");
  }
  return biomes;
}
// Every pixel of a region shares its cell's biome: biomes[owners[y * width + x]].
// Step 6: Give every region a biome
// ---------------------------------
// Edge cells become ocean (an island); inland cells use latitude plus a little randomness.

DECLARE BIOME_COLORS = DICTIONARY
SET BIOME_COLORS["Ocean"]  = "#2E5A88"
SET BIOME_COLORS["Tundra"] = "#E0FFFF"
SET BIOME_COLORS["Forest"] = "#228B22"
SET BIOME_COLORS["Plains"] = "#98FB98"
SET BIOME_COLORS["Swamp"]  = "#556B2F"
SET BIOME_COLORS["Desert"] = "#EDC9AF"

FUNCTION assignBiomes(sites, owners, width, height, seed)
    DECLARE random = NEW SeededRandom(seed)
    DECLARE ocean = NEW ARRAY OF LENGTH(sites) FALSE
    FOR x FROM 0 TO width - 1 DO
        ocean[owners[x]] = TRUE                          // top row
        ocean[owners[(height - 1) * width + x]] = TRUE   // bottom row
    END FOR
    FOR y FROM 0 TO height - 1 DO
        ocean[owners[y * width]] = TRUE                  // left column
        ocean[owners[y * width + width - 1]] = TRUE      // right column
    END FOR
    DECLARE biomes = EMPTY_ARRAY
    FOR i FROM 0 TO LENGTH(sites) - 1 DO
        IF ocean[i] THEN
            APPEND "Ocean" TO biomes
        ELSE
            DECLARE t = sites[i].y / height + (random.nextFloat() - 0.5) * 0.3
            IF t < 0.3 THEN APPEND "Tundra" TO biomes
            ELSE IF t < 0.45 THEN APPEND "Forest" TO biomes
            ELSE IF t < 0.6 THEN APPEND "Plains" TO biomes
            ELSE IF t < 0.72 THEN APPEND "Swamp" TO biomes
            ELSE APPEND "Desert" TO biomes
            END IF
        END IF
    END FOR
    RETURN biomes
END FUNCTION

Lab: Voronoi World Map

Every region that touches the map edge becomes ocean, so the land is always an island. Inland regions pick a biome from their latitude plus a little seeded randomness: cold in the north, hot in the south.

👉 Try this: set Relax to 0 and then to 3, and watch the coastline go from ragged to rounded. Push Regions to 250 for a detailed continent, or drop it to 30 for a chunky board-game map. Every New Seed is a new island, and typing an old seed back in brings its island back.

Step-by-Step Lab #5: Influence Maps for AI

Voronoi diagrams are just as useful for game AI as for maps. Picture four enemy bases, each controlling the land nearest to it. Make each base a site, and its cell is its territory: a zone of control that updates itself whenever a base moves, grows stronger or falls.

Step 7: Weighted Territories

Real factions aren’t equal, so weightedOwner() gives each base a weight and divides its distance by it. A base with weight 2 claims land as if every point were half as far away. A weight of 0 means the base is destroyed: it’s skipped, and its neighbors absorb its land.

/*
  Step 7: Weighted territories for AI
  -----------------------------------
  Make each base a site and its cell is the land it controls. Add a weight per
  base and a strong faction pushes its border outward. A weight of 0 means the
  base is gone, and its neighbors absorb its land.
*/
function weightedOwner(bases, weights, x, y) {
  let owner = -1;          // -1 means nobody controls this point (every base destroyed)
  let best = Infinity;
  for (let i = 0; i < bases.length; i++) {
    if (weights[i] <= 0) continue;                                         // destroyed bases claim nothing
    const score = distance(x, y, bases[i][0], bases[i][1]) / weights[i];   // twice the weight = half the distance
    if (score < best) {
      best = score;
      owner = i;
    }
  }
  return owner;
}
/*
  Explanation:
  - With equal weights this is plain nearestSite(): straight borders halfway between bases.
  - Dividing distance by weight is a "multiplicatively weighted" Voronoi diagram.
    Its borders are circular arcs, and a much stronger base can surround a weak one.
  - AI uses: spawn units in their own zone, keep patrols inside it, or score how
    contested a tile is from the gap between the best and second-best score.
  Next step: use distances themselves as a texture.
*/
// Step 7: Weighted territories for AI
// -----------------------------------
// Each base is a site and its cell is the land it controls. A bigger weight pushes the
// border outward; a weight of 0 means the base is gone and its neighbors absorb its land.
public static int WeightedOwner(List<(double X, double Y)> bases, double[] weights, double x, double y)
{
    int owner = -1;   // -1 means nobody controls this point (every base destroyed)
    double best = double.PositiveInfinity;
    for (int i = 0; i < bases.Count; i++)
    {
        if (weights[i] <= 0) continue;                                       // destroyed bases claim nothing
        double score = Distance(x, y, bases[i].X, bases[i].Y) / weights[i];   // twice the weight = half the distance
        if (score < best)
        {
            best = score;
            owner = i;
        }
    }
    return owner;
}
// Equal weights give straight borders halfway between bases. Dividing by the weight makes a
// "multiplicatively weighted" Voronoi diagram, whose borders are circular arcs.
// Step 7: Weighted territories for AI
// -----------------------------------
// Each base is a site and its cell is the land it controls. A bigger weight pushes the
// border outward; a weight of 0 means the base is gone and its neighbors absorb its land.
int weightedOwner(const std::vector<Site>& bases, const std::vector<double>& weights, double x, double y) {
  int owner = -1;   // -1 means nobody controls this point (every base destroyed)
  double best = std::numeric_limits<double>::infinity();
  for (int i = 0; i < (int)bases.size(); i++) {
    if (weights[i] <= 0) continue;                                         // destroyed bases claim nothing
    double score = distance(x, y, bases[i].x, bases[i].y) / weights[i];    // twice the weight = half the distance
    if (score < best) {
      best = score;
      owner = i;
    }
  }
  return owner;
}
// Equal weights give straight borders halfway between bases. Dividing by the weight makes a
// "multiplicatively weighted" Voronoi diagram, whose borders are circular arcs.
// Step 7: Weighted territories for AI
// -----------------------------------
// Divide each base's distance by its weight. Weight 0 = destroyed base.

FUNCTION weightedOwner(bases, weights, x, y)
    DECLARE owner = -1                     // nobody, if every base is destroyed
    DECLARE best = INFINITY
    FOR i FROM 0 TO LENGTH(bases) - 1 DO
        IF weights[i] > 0 THEN
            DECLARE score = distance(x, y, bases[i].x, bases[i].y) / weights[i]
            IF score < best THEN
                best = score
                owner = i
            END IF
        END IF
    END FOR
    RETURN owner
END FUNCTION

Lab: Faction Territories

Drag a base to move it. Raise a weight and that faction's border bulges outward into a curve. Destroy a base and its neighbors split its land between them, with no extra code.

👉 Try this: raise Tide to 2.2× and watch its straight borders bulge into curves. Push one faction far above the others and its territory can wrap right around a weaker base. Then Destroy a base: the survivors split its land, and the shares update instantly. Untick Use weights to compare against the plain Voronoi diagram.

Once every tile has an owner, your AI can use it:

  • Spawning: spawn reinforcements anywhere inside their own faction’s zone.
  • Patrols: pick patrol points inside the zone, and treat the border as the line to defend.
  • Contested ground: where the best and second-best scores are close, the tile is contested. That’s where skirmishes belong.
  • Fog of war: reveal a region when any friendly unit stands in it.

Dividing distance by weight makes a multiplicatively weighted Voronoi diagram, which is why the borders curve. The other common variant, the power diagram, subtracts a weight from the squared distance instead and keeps every border straight.

Step-by-Step Lab #6: Cell Noise for Stylish Effects

So far we’ve only asked which site is nearest. Keep the distances themselves and you get a texture. F1 is the distance to the nearest site, and F2 is the distance to the second nearest. Steven Worley introduced this “cellular texture basis function” at SIGGRAPH in 1996, which is why you’ll also hear it called Worley noise. Unity’s Shader Graph ships it as its Voronoi node.

Step 8: F1, F2 and the Edges

nearestTwo() finds the closest and second-closest site in one pass. It’s the same function our Biome tutorial uses to blend regions. cellNoise() turns it into three useful values: F1, F2, and F2 − F1, which is exactly 0 on every border and grows toward the middle of each cell.

/*
  Step 8: Cell noise (F1, F2 and the edges)
  -----------------------------------------
  Instead of asking "which site is nearest?", keep the distances. F1 is the
  distance to the nearest site and F2 to the second nearest. Steven Worley
  introduced this "cellular texture" in 1996, and it's behind countless stone,
  scale, crack and force-field shaders.
*/
function nearestTwo(sites, x, y) {
  let nearest = 0;
  let second = 0;
  let d1 = Infinity;
  let d2 = Infinity;
  for (let i = 0; i < sites.length; i++) {
    const d = distance(x, y, sites[i][0], sites[i][1]);
    if (d < d1) {
      // New closest: the old closest becomes the runner-up.
      second = nearest;
      d2 = d1;
      nearest = i;
      d1 = d;
    } else if (d < d2) {
      // Not the closest, but closer than the runner-up.
      second = i;
      d2 = d;
    }
  }
  return { nearest, second, d1, d2 };
}

const CellMode = { F1: "F1", F2: "F2", Edges: "F2-F1" };

function cellNoise(sites, x, y, mode = CellMode.F1) {
  const { d1, d2 } = nearestTwo(sites, x, y);
  if (mode === CellMode.F2) return d2;
  if (mode === CellMode.Edges) return d2 - d1;   // 0 exactly on a border
  return d1;                                     // 0 exactly on a site
}
/*
  Explanation:
  - The values are distances in your map's units. Divide by the typical spacing
    between sites to get roughly 0..1 before using them as colors.
  - F2 - F1 below a small threshold = cracks, mortar or cell walls.
  - nearestTwo() is the same function our Biome tutorial uses to blend regions.
*/
// Step 8: Cell noise (F1, F2 and the edges)
// -----------------------------------------
// Keep the distances instead of just the winner. F1 is the distance to the nearest site,
// F2 to the second nearest (Steven Worley's "cellular texture", 1996).
public static (int Nearest, int Second, double D1, double D2) NearestTwo(List<(double X, double Y)> sites, double x, double y)
{
    int nearest = 0;
    int second = 0;
    double d1 = double.PositiveInfinity;
    double d2 = double.PositiveInfinity;
    for (int i = 0; i < sites.Count; i++)
    {
        double d = Distance(x, y, sites[i].X, sites[i].Y);
        if (d < d1)
        {
            // New closest: the old closest becomes the runner-up.
            second = nearest;
            d2 = d1;
            nearest = i;
            d1 = d;
        }
        else if (d < d2)
        {
            // Not the closest, but closer than the runner-up.
            second = i;
            d2 = d;
        }
    }
    return (nearest, second, d1, d2);
}

public enum CellMode { F1, F2, Edges }

public static double CellNoise(List<(double X, double Y)> sites, double x, double y, CellMode mode = CellMode.F1)
{
    var (_, _, d1, d2) = NearestTwo(sites, x, y);
    if (mode == CellMode.F2) return d2;
    if (mode == CellMode.Edges) return d2 - d1;   // 0 exactly on a border
    return d1;                                    // 0 exactly on a site
}
// Divide by the typical spacing between sites to get roughly 0..1 for colors.
// F2 - F1 below a small threshold = cracks, mortar or cell walls.
// Step 8: Cell noise (F1, F2 and the edges)
// -----------------------------------------
// Keep the distances instead of just the winner. F1 is the distance to the nearest site,
// F2 to the second nearest (Steven Worley's "cellular texture", 1996).
struct NearestHit {
  int nearest;
  int second;
  double d1;
  double d2;
};

NearestHit nearestTwo(const std::vector<Site>& sites, double x, double y) {
  int nearest = 0;
  int second = 0;
  double d1 = std::numeric_limits<double>::infinity();
  double d2 = std::numeric_limits<double>::infinity();
  for (int i = 0; i < (int)sites.size(); i++) {
    double d = distance(x, y, sites[i].x, sites[i].y);
    if (d < d1) {
      // New closest: the old closest becomes the runner-up.
      second = nearest;
      d2 = d1;
      nearest = i;
      d1 = d;
    } else if (d < d2) {
      // Not the closest, but closer than the runner-up.
      second = i;
      d2 = d;
    }
  }
  return {nearest, second, d1, d2};
}

enum class CellMode { F1, F2, Edges };

double cellNoise(const std::vector<Site>& sites, double x, double y, CellMode mode = CellMode::F1) {
  NearestHit hit = nearestTwo(sites, x, y);
  if (mode == CellMode::F2) return hit.d2;
  if (mode == CellMode::Edges) return hit.d2 - hit.d1;   // 0 exactly on a border
  return hit.d1;                                         // 0 exactly on a site
}
// Divide by the typical spacing between sites to get roughly 0..1 for colors.
// Step 8: Cell noise (F1, F2 and the edges)
// -----------------------------------------
// F1 = distance to the nearest site, F2 = to the second nearest (Worley, 1996).

FUNCTION nearestTwo(sites, x, y)
    DECLARE nearest = 0, second = 0
    DECLARE d1 = INFINITY, d2 = INFINITY
    FOR i FROM 0 TO LENGTH(sites) - 1 DO
        DECLARE d = distance(x, y, sites[i].x, sites[i].y)
        IF d < d1 THEN
            second = nearest                 // the old closest becomes the runner-up
            d2 = d1
            nearest = i
            d1 = d
        ELSE IF d < d2 THEN
            second = i
            d2 = d
        END IF
    END FOR
    RETURN (nearest, second, d1, d2)
END FUNCTION

FUNCTION cellNoise(sites, x, y, mode = F1)
    DECLARE (nearest, second, d1, d2) = nearestTwo(sites, x, y)
    IF mode = F2 THEN RETURN d2 END IF
    IF mode = EDGES THEN RETURN d2 - d1 END IF   // 0 exactly on a border
    RETURN d1                                    // 0 exactly on a site
END FUNCTION

Lab: Cell Noise Effects

👉 Try this: start with F1 (dark spots on the sites, bright ridges on the borders), then F2 − F1, the edge detector. Stone and Lava are the same two numbers dressed differently: one gray per cell with dark mortar, or glowing cracks on black. Drag Crack width and Sites to go from fine scales to big flagstones.

Putting It Together: Paint the Whole Island

Time to cash in everything from this page. Lab #4’s island already knows which biome every region is. Add Step 8’s nearestTwo() and every pixel also knows how far it is from its region’s edge, and that one number, F2 − F1, is enough to turn a flat diagram into a map you’d want in a game.

Step 9: Paint the Island

paintIsland() builds Lab #4’s map, then paints it in four passes:

  • Regions as raised tiles. Each region gets its biome color with a slightly different shade, and pixels near the edge (small F2 − F1) are lit on the top-left side and shadowed on the bottom-right, so every region looks like a beveled tile.
  • Coasts. A land pixel whose second-nearest region is ocean and sits close to the border becomes beach. An ocean pixel next to land gets lighter the closer it is: shallows.
  • Roads. Two regions are neighbors when their pixels touch, and a dashed road links their sites. It’s the same neighbor graph that Delaunay triangulation gives you in Lab #2.
  • Towns. One on every land site, with a soft shadow.

The result is a plain array of RGB bytes, so it works the same in a browser, a game engine or a command-line tool.

/*
  Step 9: Paint the island
  ------------------------
  Everything from this page in one picture. Lab #4's island gives every region a biome,
  nearestTwo() from Step 8 shades each pixel by its distance to the region's edge
  (F2 - F1), and neighboring regions are linked by roads, the same neighbor graph that
  Delaunay builds in Lab #2. The result is a plain array of RGB bytes.
*/
const BIOME_PAINT = {
  Ocean: [26, 74, 122],
  Tundra: [204, 222, 232],
  Forest: [50, 118, 64],
  Plains: [148, 182, 94],
  Swamp: [88, 108, 68],
  Desert: [218, 182, 116]
};
const SAND = [232, 214, 160];
const ROAD = [96, 66, 42];
const TOWN = [60, 44, 36];
const BLACK = [0, 0, 0];
const WHITE = [255, 255, 255];

function setPixel(pixels, width, x, y, color, light) {
  // Write one pixel, brightened or darkened by light (1 = unchanged), kept within 0..255.
  const i = (y * width + x) * 3;
  for (let c = 0; c < 3; c++) {
    pixels[i + c] = Math.min(255, Math.max(0, Math.floor(color[c] * light)));
  }
}

function stampCircle(pixels, width, height, cx, cy, radius, color, opacity) {
  // Blend a filled circle over what's already there: opacity 1 covers it, 0.4 tints it.
  for (let y = Math.max(0, Math.floor(cy - radius)); y <= Math.min(height - 1, Math.floor(cy + radius)); y++) {
    for (let x = Math.max(0, Math.floor(cx - radius)); x <= Math.min(width - 1, Math.floor(cx + radius)); x++) {
      const dx = x + 0.5 - cx;
      const dy = y + 0.5 - cy;
      if (dx * dx + dy * dy > radius * radius) continue;  // outside the circle
      const i = (y * width + x) * 3;
      for (let c = 0; c < 3; c++) {
        pixels[i + c] = Math.floor(pixels[i + c] + (color[c] - pixels[i + c]) * opacity);
      }
    }
  }
}

function paintIsland(width, height, regions, seed) {
  // 1. Lab #4's map: seeded sites, two rounds of Lloyd relaxation, owners and biomes.
  let sites = makeSites(regions, width, height, seed);
  for (let i = 0; i < 2; i++) sites = relaxSites(sites, width, height);
  const owners = voronoiGrid(sites, width, height);
  const biomes = assignBiomes(sites, owners, width, height, seed);
  const random = new SeededRandom(seed + 1);
  const tone = sites.map(() => 0.92 + random.nextFloat() * 0.16);  // every region a slightly different shade

  // 2. Every pixel: its region's color, shaded by the distance to the region's edge.
  const pixels = new Uint8Array(width * height * 3);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const { nearest, second, d1, d2 } = nearestTwo(sites, x + 0.5, y + 0.5);
      const edge = d2 - d1;  // 0 on a border, growing toward the region's middle
      const here = biomes[nearest];
      const there = biomes[second];
      const vx = x / width - 0.5;
      const vy = y / height - 0.5;
      const vignette = 1 - 0.6 * (vx * vx + vy * vy);  // a little darker toward the corners
      if (here === "Ocean") {
        // Water near land gets lighter: a band of shallows around every coast.
        const shallow = there === "Ocean" ? 0 : Math.max(0, 1 - edge / 16);
        setPixel(pixels, width, x, y, BIOME_PAINT.Ocean, (0.85 + 0.7 * shallow) * vignette);
      } else if (there === "Ocean" && edge < 3) {
        setPixel(pixels, width, x, y, SAND, vignette);  // a beach along the coast
      } else {
        // Light from the top left: each region's top-left rim is lit, its bottom-right rim in shadow.
        const dx = x + 0.5 - sites[nearest][0];
        const dy = y + 0.5 - sites[nearest][1];
        const facing = -(dx + dy) / (Math.sqrt(dx * dx + dy * dy) + 1);  // about +1.4 toward the light, -1.4 away
        const rim = Math.max(0, 1 - edge / 9);  // 1 on the edge, 0 deeper inside
        const border = here !== there && edge < 1.5 ? 0.55 : 1;  // a dark line where two biomes meet
        const light = (1 + 0.22 * facing * rim) * border * tone[nearest] * vignette;
        setPixel(pixels, width, x, y, BIOME_PAINT[here], light);
      }
    }
  }

  // 3. Roads: two land regions whose pixels touch are neighbors, so link their sites.
  const n = sites.length;
  const touches = new Uint8Array(n * n);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const a = owners[y * width + x];
      const right = x + 1 < width ? owners[y * width + x + 1] : a;
      const below = y + 1 < height ? owners[(y + 1) * width + x] : a;
      touches[a * n + right] = touches[right * n + a] = 1;
      touches[a * n + below] = touches[below * n + a] = 1;
    }
  }
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      if (!touches[i * n + j] || biomes[i] === "Ocean" || biomes[j] === "Ocean") continue;
      const [ax, ay] = sites[i];
      const [bx, by] = sites[j];
      const steps = Math.floor(Math.sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay)));
      for (let s = 6; s < steps - 6; s++) {
        if (s % 6 > 3) continue;  // skip 2 of every 6 pixels, so the road is dashed
        const t = s / steps;
        stampCircle(pixels, width, height, ax + (bx - ax) * t, ay + (by - ay) * t, 1.2, ROAD, 0.5);
      }
    }
  }

  // 4. Towns: one on every land site, with a soft shadow.
  for (let i = 0; i < n; i++) {
    if (biomes[i] === "Ocean") continue;
    const [x, y] = sites[i];
    stampCircle(pixels, width, height, x + 1.5, y + 2, 4.2, BLACK, 0.4);
    stampCircle(pixels, width, height, x, y, 4.2, TOWN, 1);
    stampCircle(pixels, width, height, x, y, 2.5, WHITE, 1);
  }
  return pixels;
}
/*
  Explanation:
  - Decisions stay per region (biome, shade), while F2 - F1 adds per-pixel detail: the beaches,
    the shallows, the biome borders and the raised-tile rims all come from that one number.
  - The rim light compares the pixel's direction from its site with the light's direction, so
    regions look like raised tiles lit from the top left.
  - stampCircle() blends, so shadows and roads sit naturally on any ground.
  Next: show the pixels on screen (or save them to a file).
*/
// Step 9: Paint the island
// ------------------------
// Everything from this page in one picture. Step 6 gives every region a biome, NearestTwo() from Step 8
// shades each pixel by its distance to the region's edge (F2 - F1), and neighboring regions are linked by
// roads. The result is a plain array of RGB bytes.
public static readonly Dictionary<string, int[]> BiomePaint = new Dictionary<string, int[]>
{
    { "Ocean", new[] { 26, 74, 122 } },
    { "Tundra", new[] { 204, 222, 232 } },
    { "Forest", new[] { 50, 118, 64 } },
    { "Plains", new[] { 148, 182, 94 } },
    { "Swamp", new[] { 88, 108, 68 } },
    { "Desert", new[] { 218, 182, 116 } }
};
static readonly int[] Sand = { 232, 214, 160 };
static readonly int[] Road = { 96, 66, 42 };
static readonly int[] Town = { 60, 44, 36 };
static readonly int[] Black = { 0, 0, 0 };
static readonly int[] White = { 255, 255, 255 };

static void SetPixel(byte[] pixels, int width, int x, int y, int[] color, double light)
{
    // Write one pixel, brightened or darkened by light (1 = unchanged), kept within 0..255.
    int i = (y * width + x) * 3;
    for (int c = 0; c < 3; c++)
        pixels[i + c] = (byte)Math.Min(255, Math.Max(0, Math.Floor(color[c] * light)));
}

static void StampCircle(byte[] pixels, int width, int height, double cx, double cy, double radius, int[] color, double opacity)
{
    // Blend a filled circle over what's already there: opacity 1 covers it, 0.4 tints it.
    for (int y = Math.Max(0, (int)Math.Floor(cy - radius)); y <= Math.Min(height - 1, (int)Math.Floor(cy + radius)); y++)
    {
        for (int x = Math.Max(0, (int)Math.Floor(cx - radius)); x <= Math.Min(width - 1, (int)Math.Floor(cx + radius)); x++)
        {
            double dx = x + 0.5 - cx;
            double dy = y + 0.5 - cy;
            if (dx * dx + dy * dy > radius * radius) continue;   // outside the circle
            int i = (y * width + x) * 3;
            for (int c = 0; c < 3; c++)
                pixels[i + c] = (byte)Math.Floor(pixels[i + c] + (color[c] - pixels[i + c]) * opacity);
        }
    }
}

public static byte[] PaintIsland(int width, int height, int regions, int seed)
{
    // 1. Step 6's map: seeded sites, two rounds of Lloyd relaxation, owners and biomes.
    var sites = MakeSites(regions, width, height, seed);
    for (int i = 0; i < 2; i++) sites = RelaxSites(sites, width, height);
    int[] owners = VoronoiGrid(sites, width, height);
    string[] biomes = AssignBiomes(sites, owners, width, height, seed);
    var random = new SeededRandom(seed + 1);
    var tone = new double[sites.Count];   // every region a slightly different shade
    for (int i = 0; i < sites.Count; i++) tone[i] = 0.92 + random.NextFloat() * 0.16;

    // 2. Every pixel: its region's color, shaded by the distance to the region's edge.
    var pixels = new byte[width * height * 3];
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            var (nearest, second, d1, d2) = NearestTwo(sites, x + 0.5, y + 0.5);
            double edge = d2 - d1;   // 0 on a border, growing toward the region's middle
            string here = biomes[nearest];
            string there = biomes[second];
            double vx = (double)x / width - 0.5;
            double vy = (double)y / height - 0.5;
            double vignette = 1 - 0.6 * (vx * vx + vy * vy);   // a little darker toward the corners
            if (here == "Ocean")
            {
                // Water near land gets lighter: a band of shallows around every coast.
                double shallow = there == "Ocean" ? 0 : Math.Max(0, 1 - edge / 16);
                SetPixel(pixels, width, x, y, BiomePaint["Ocean"], (0.85 + 0.7 * shallow) * vignette);
            }
            else if (there == "Ocean" && edge < 3)
            {
                SetPixel(pixels, width, x, y, Sand, vignette);   // a beach along the coast
            }
            else
            {
                // Light from the top left: each region's top-left rim is lit, its bottom-right rim in shadow.
                double dx = x + 0.5 - sites[nearest].X;
                double dy = y + 0.5 - sites[nearest].Y;
                double facing = -(dx + dy) / (Math.Sqrt(dx * dx + dy * dy) + 1);   // about +1.4 toward the light, -1.4 away
                double rim = Math.Max(0, 1 - edge / 9);                             // 1 on the edge, 0 deeper inside
                double border = here != there && edge < 1.5 ? 0.55 : 1;            // a dark line where two biomes meet
                double light = (1 + 0.22 * facing * rim) * border * tone[nearest] * vignette;
                SetPixel(pixels, width, x, y, BiomePaint[here], light);
            }
        }
    }

    // 3. Roads: two land regions whose pixels touch are neighbors, so link their sites.
    int n = sites.Count;
    var touches = new bool[n * n];
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            int a = owners[y * width + x];
            int right = x + 1 < width ? owners[y * width + x + 1] : a;
            int below = y + 1 < height ? owners[(y + 1) * width + x] : a;
            touches[a * n + right] = touches[right * n + a] = true;
            touches[a * n + below] = touches[below * n + a] = true;
        }
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            if (!touches[i * n + j] || biomes[i] == "Ocean" || biomes[j] == "Ocean") continue;
            var (ax, ay) = sites[i];
            var (bx, by) = sites[j];
            int steps = (int)Math.Floor(Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay)));
            for (int s = 6; s < steps - 6; s++)
            {
                if (s % 6 > 3) continue;   // skip 2 of every 6 pixels, so the road is dashed
                double t = (double)s / steps;
                StampCircle(pixels, width, height, ax + (bx - ax) * t, ay + (by - ay) * t, 1.2, Road, 0.5);
            }
        }
    }

    // 4. Towns: one on every land site, with a soft shadow.
    for (int i = 0; i < n; i++)
    {
        if (biomes[i] == "Ocean") continue;
        var (x, y) = sites[i];
        StampCircle(pixels, width, height, x + 1.5, y + 2, 4.2, Black, 0.4);
        StampCircle(pixels, width, height, x, y, 4.2, Town, 1);
        StampCircle(pixels, width, height, x, y, 2.5, White, 1);
    }
    return pixels;
}
// Decisions stay per region (biome, shade); F2 - F1 adds the per-pixel detail: beaches, shallows, borders, rims.
// Step 9: Paint the island
// ------------------------
// Everything from this page in one picture. Step 6 gives every region a biome, nearestTwo() from Step 8
// shades each pixel by its distance to the region's edge (F2 - F1), and neighboring regions are linked by
// roads. The result is a plain array of RGB bytes.
#include <algorithm>
#include <array>
#include <cmath>

using Color = std::array<int, 3>;

const std::map<std::string, Color> BIOME_PAINT = {
  {"Ocean", {26, 74, 122}},
  {"Tundra", {204, 222, 232}},
  {"Forest", {50, 118, 64}},
  {"Plains", {148, 182, 94}},
  {"Swamp", {88, 108, 68}},
  {"Desert", {218, 182, 116}}
};
const Color SAND = {232, 214, 160};
const Color ROAD = {96, 66, 42};
const Color TOWN = {60, 44, 36};
const Color BLACK = {0, 0, 0};
const Color WHITE = {255, 255, 255};

void setPixel(std::vector<unsigned char>& pixels, int width, int x, int y, const Color& color, double light) {
  // Write one pixel, brightened or darkened by light (1 = unchanged), kept within 0..255.
  int i = (y * width + x) * 3;
  for (int c = 0; c < 3; c++) {
    pixels[i + c] = static_cast<unsigned char>(std::min(255.0, std::max(0.0, std::floor(color[c] * light))));
  }
}

void stampCircle(std::vector<unsigned char>& pixels, int width, int height, double cx, double cy, double radius, const Color& color, double opacity) {
  // Blend a filled circle over what's already there: opacity 1 covers it, 0.4 tints it.
  for (int y = std::max(0, static_cast<int>(std::floor(cy - radius))); y <= std::min(height - 1, static_cast<int>(std::floor(cy + radius))); y++) {
    for (int x = std::max(0, static_cast<int>(std::floor(cx - radius))); x <= std::min(width - 1, static_cast<int>(std::floor(cx + radius))); x++) {
      double dx = x + 0.5 - cx;
      double dy = y + 0.5 - cy;
      if (dx * dx + dy * dy > radius * radius) continue;   // outside the circle
      int i = (y * width + x) * 3;
      for (int c = 0; c < 3; c++) {
        pixels[i + c] = static_cast<unsigned char>(std::floor(pixels[i + c] + (color[c] - pixels[i + c]) * opacity));
      }
    }
  }
}

std::vector<unsigned char> paintIsland(int width, int height, int regions, int seed) {
  // 1. Step 6's map: seeded sites, two rounds of Lloyd relaxation, owners and biomes.
  std::vector<Site> sites = makeSites(regions, width, height, seed);
  for (int i = 0; i < 2; i++) sites = relaxSites(sites, width, height);
  std::vector<int> owners = voronoiGrid(sites, width, height);
  std::vector<std::string> biomes = assignBiomes(sites, owners, width, height, seed);
  SeededRandom random(seed + 1);
  std::vector<double> tone;   // every region a slightly different shade
  for (size_t i = 0; i < sites.size(); i++) tone.push_back(0.92 + random.NextFloat() * 0.16);

  // 2. Every pixel: its region's color, shaded by the distance to the region's edge.
  std::vector<unsigned char> pixels(width * height * 3);
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      NearestHit hit = nearestTwo(sites, x + 0.5, y + 0.5);
      double edge = hit.d2 - hit.d1;   // 0 on a border, growing toward the region's middle
      const std::string& here = biomes[hit.nearest];
      const std::string& there = biomes[hit.second];
      double vx = static_cast<double>(x) / width - 0.5;
      double vy = static_cast<double>(y) / height - 0.5;
      double vignette = 1 - 0.6 * (vx * vx + vy * vy);   // a little darker toward the corners
      if (here == "Ocean") {
        // Water near land gets lighter: a band of shallows around every coast.
        double shallow = there == "Ocean" ? 0 : std::max(0.0, 1 - edge / 16);
        setPixel(pixels, width, x, y, BIOME_PAINT.at("Ocean"), (0.85 + 0.7 * shallow) * vignette);
      } else if (there == "Ocean" && edge < 3) {
        setPixel(pixels, width, x, y, SAND, vignette);   // a beach along the coast
      } else {
        // Light from the top left: each region's top-left rim is lit, its bottom-right rim in shadow.
        double dx = x + 0.5 - sites[hit.nearest].x;
        double dy = y + 0.5 - sites[hit.nearest].y;
        double facing = -(dx + dy) / (std::sqrt(dx * dx + dy * dy) + 1);   // about +1.4 toward the light, -1.4 away
        double rim = std::max(0.0, 1 - edge / 9);                            // 1 on the edge, 0 deeper inside
        double border = here != there && edge < 1.5 ? 0.55 : 1;             // a dark line where two biomes meet
        double light = (1 + 0.22 * facing * rim) * border * tone[hit.nearest] * vignette;
        setPixel(pixels, width, x, y, BIOME_PAINT.at(here), light);
      }
    }
  }

  // 3. Roads: two land regions whose pixels touch are neighbors, so link their sites.
  int n = static_cast<int>(sites.size());
  std::vector<bool> touches(n * n, false);
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      int a = owners[y * width + x];
      int right = x + 1 < width ? owners[y * width + x + 1] : a;
      int below = y + 1 < height ? owners[(y + 1) * width + x] : a;
      touches[a * n + right] = touches[right * n + a] = true;
      touches[a * n + below] = touches[below * n + a] = true;
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
      if (!touches[i * n + j] || biomes[i] == "Ocean" || biomes[j] == "Ocean") continue;
      double ax = sites[i].x, ay = sites[i].y;
      double bx = sites[j].x, by = sites[j].y;
      int steps = static_cast<int>(std::floor(std::sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay))));
      for (int s = 6; s < steps - 6; s++) {
        if (s % 6 > 3) continue;   // skip 2 of every 6 pixels, so the road is dashed
        double t = static_cast<double>(s) / steps;
        stampCircle(pixels, width, height, ax + (bx - ax) * t, ay + (by - ay) * t, 1.2, ROAD, 0.5);
      }
    }
  }

  // 4. Towns: one on every land site, with a soft shadow.
  for (int i = 0; i < n; i++) {
    if (biomes[i] == "Ocean") continue;
    double x = sites[i].x, y = sites[i].y;
    stampCircle(pixels, width, height, x + 1.5, y + 2, 4.2, BLACK, 0.4);
    stampCircle(pixels, width, height, x, y, 4.2, TOWN, 1);
    stampCircle(pixels, width, height, x, y, 2.5, WHITE, 1);
  }
  return pixels;
}
// Decisions stay per region (biome, shade); F2 - F1 adds the per-pixel detail: beaches, shallows, borders, rims.
// Step 9: Paint the island
// ------------------------
// Step 6's biomes + Step 8's nearestTwo() edge distance + roads between neighboring regions.

FUNCTION setPixel(pixels, width, x, y, color, light)
    DECLARE i = (y * width + x) * 3
    FOR c FROM 0 TO 2 DO
        pixels[i + c] = CLAMP(FLOOR(color[c] * light), 0, 255)
    END FOR
END FUNCTION

FUNCTION stampCircle(pixels, width, height, cx, cy, radius, color, opacity)
    FOR EACH pixel (x, y) WHOSE CENTER (x + 0.5, y + 0.5) IS WITHIN radius OF (cx, cy) DO
        DECLARE i = (y * width + x) * 3
        FOR c FROM 0 TO 2 DO
            pixels[i + c] = FLOOR(pixels[i + c] + (color[c] - pixels[i + c]) * opacity)   // blend
        END FOR
    END FOR
END FUNCTION

FUNCTION paintIsland(width, height, regions, seed)
    // 1. The world map from Step 6
    DECLARE sites = makeSites(regions, width, height, seed)
    FOR i FROM 1 TO 2 DO sites = relaxSites(sites, width, height) END FOR
    DECLARE owners = voronoiGrid(sites, width, height)
    DECLARE biomes = assignBiomes(sites, owners, width, height, seed)
    DECLARE random = SeededRandom(seed + 1)
    DECLARE tone = FOR EACH site: 0.92 + random.nextFloat() * 0.16     // a shade per region

    // 2. Every pixel, shaded by its distance to the region's edge
    DECLARE pixels = BYTE ARRAY OF width * height * 3
    FOR y FROM 0 TO height - 1 DO
        FOR x FROM 0 TO width - 1 DO
            DECLARE (nearest, second, d1, d2) = nearestTwo(sites, x + 0.5, y + 0.5)
            DECLARE edge = d2 - d1                    // 0 on a border
            DECLARE here = biomes[nearest], there = biomes[second]
            DECLARE vx = x / width - 0.5, vy = y / height - 0.5
            DECLARE vignette = 1 - 0.6 * (vx * vx + vy * vy)
            IF here = "Ocean" THEN
                DECLARE shallow = 0
                IF there != "Ocean" THEN shallow = MAX(0, 1 - edge / 16) END IF
                setPixel(pixels, width, x, y, BIOME_PAINT["Ocean"], (0.85 + 0.7 * shallow) * vignette)
            ELSE IF there = "Ocean" AND edge < 3 THEN
                setPixel(pixels, width, x, y, SAND, vignette)                 // beach
            ELSE
                DECLARE dx = x + 0.5 - sites[nearest].x, dy = y + 0.5 - sites[nearest].y
                DECLARE facing = -(dx + dy) / (SQRT(dx * dx + dy * dy) + 1)  // toward the top-left light?
                DECLARE rim = MAX(0, 1 - edge / 9)
                DECLARE border = 1
                IF here != there AND edge < 1.5 THEN border = 0.55 END IF     // biome border
                DECLARE light = (1 + 0.22 * facing * rim) * border * tone[nearest] * vignette
                setPixel(pixels, width, x, y, BIOME_PAINT[here], light)
            END IF
        END FOR
    END FOR

    // 3. Roads between land regions whose pixels touch
    DECLARE touches = n x n TABLE OF false                // n = LENGTH(sites)
    FOR EACH pixel: touches[owner][owner of right neighbor] = touches[owner][owner below] = true (both ways)
    FOR EACH pair i < j WITH touches[i][j] AND both biomes not "Ocean" DO
        DECLARE steps = FLOOR(distance(sites[i], sites[j]))
        FOR s FROM 6 TO steps - 7 DO
            IF s MOD 6 <= 3 THEN                              // dashed
                DECLARE t = s / steps
                stampCircle(pixels, width, height, LERP(sites[i], sites[j], t), 1.2, ROAD, 0.5)
            END IF
        END FOR
    END FOR

    // 4. Towns on every land site
    FOR EACH land site (x, y) DO
        stampCircle(pixels, width, height, x + 1.5, y + 2, 4.2, BLACK, 0.4)   // shadow
        stampCircle(pixels, width, height, x, y, 4.2, TOWN, 1)
        stampCircle(pixels, width, height, x, y, 2.5, WHITE, 1)
    END FOR
    RETURN pixels
END FUNCTION

Show It

In the browser, drawPixels() copies the bytes into a canvas. In C# and C++, the easiest way to see the result is to save a PPM file: a short text header followed by the raw bytes. GIMP, Krita and Photoshop open it, and in a game engine you’d copy the same bytes into a texture instead. All three languages paint the same island, byte for byte.

function drawPixels(canvas, pixels, width, height) {
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext("2d");
  const image = ctx.createImageData(width, height);
  for (let i = 0, j = 0; i < pixels.length; i += 3, j += 4) {
    image.data[j] = pixels[i];
    image.data[j + 1] = pixels[i + 1];
    image.data[j + 2] = pixels[i + 2];
    image.data[j + 3] = 255;
  }
  ctx.putImageData(image, 0, 0);
}

drawPixels(document.querySelector("canvas"), paintIsland(880, 480, 90, 123456), 880, 480);
public static class Program
{
    public static void Main()
    {
        int width = 880, height = 480;
        byte[] pixels = VoronoiGen.PaintIsland(width, height, 90, 123456);
        using var file = System.IO.File.Create("island.ppm");
        byte[] header = System.Text.Encoding.ASCII.GetBytes("P6 " + width + " " + height + " 255 ");
        file.Write(header, 0, header.Length);
        file.Write(pixels, 0, pixels.Length);
    }
}
#include <cstdio>

int main() {
  int width = 880, height = 480;
  std::vector<unsigned char> pixels = paintIsland(width, height, 90, 123456);
  FILE* file = std::fopen("island.ppm", "wb");
  std::fprintf(file, "P6 %d %d 255 ", width, height);
  std::fwrite(pixels.data(), 1, pixels.size(), file);
  std::fclose(file);
  return 0;
}
// Show it: draw the pixels on screen, or save them as an image file.

DECLARE width = 880, height = 480
DECLARE pixels = paintIsland(width, height, 90, 123456)     // same seed, same island
DRAW pixels AS AN RGB IMAGE OF width x height               // or WRITE "P6 width height 255 " + pixels TO "island.ppm"

Lab: The Whole Island, Painted

Painting…
Every pixel comes from the paintIsland() above, and the same seed paints the same picture in C# and C++. Hover (or tap) the map for a closer look, and press New World until you find a kingdom worth ruling.

👉 Try this: hover over a coastline to see the beach and shallows up close, then press New World a few times. Drop Regions to 40 for a chunky board-game kingdom, or raise it to 140 for a detailed continent with a dense road network. Found an island you like? Download PNG keeps it, and its seed brings it back anytime.

Latitude is a stand-in for climate. Swap it for temperature and moisture noise, wobble the borders and blend neighboring regions, and you have the full system from our Procedural Biome Generation tutorial, which uses the same makeSites() and nearestTwo().

Common Pitfalls

  • Unbounded cells: mathematically, the outer cells stretch to infinity. The pixel method is bounded by your map automatically, and d3-delaunay clips to the box you pass to voronoi(). If you build polygons any other way, clip them to the map.
  • Slow maps: the pixel method costs pixels × sites. A 720 × 400 map with 100 sites is 28.8 million distance checks, fine once and too slow every frame. Compute at half resolution and scale up (the world map lab does), use Delaunay for exact cells, or, for infinite textures, place one site per grid cell and check only the 3 × 3 neighboring cells.
  • Clumps and slivers: raw random sites make tiny and huge cells. One to three rounds of Lloyd relaxation fixes it, or use Poisson disk sampling to place the sites evenly to begin with.
  • Jagged borders on grids: pixel borders are staircases. For smooth rendering, use F2 − F1 to find the pixels near a border and blend there, or draw the d3 polygons with antialiasing.
  • Unrepeatable maps: Math.random() gives a different world every run, so a bug on “that one map” can’t be reproduced. Seed everything.
  • Indexes that shift: cells are numbered by their position in the sites array. Remove a site and every later cell’s index changes, so store a stable ID with each site if game state refers to regions.

Real Games That Use Voronoi Diagrams

  • Realm of the Mad God: Amit Patel’s polygon map generator was built for it. Its first version (2010) spread the points with Lloyd relaxation, turned the polygons around them into land and water regions, and kept the map’s boundary as water, much like Lab #4.
  • Minecraft (Java Edition, older versions): up to 1.16, the layered biome generator worked at a quarter of full resolution, and a final VoronoiLayer zoomed the biomes up to full size, according to community reimplementations such as mc_biome_java. The 1.18 world-generation rework replaced the layer system.
  • Hytale: its world generator includes a Voronoi cell-noise node. We take it apart in How Hytale Generates Its Worlds.
  • Unreal Engine 5: Chaos Destruction’s Uniform fracture tool fractures a mesh “using a Voronoi diagram” with a random site count and seed, for shards of similar size.
  • Unity: Shader Graph’s Voronoi node is cell noise, ready for stone, scales and force-field effects.

Extensions and Variations

  • Poisson-disk sampling: place sites with a guaranteed minimum spacing instead of relaxing random ones. Our Poisson disk sampling tutorial builds it step by step.
  • Noisy borders and blending: wobble the lookup position with noise before calling nearestTwo(), and blend across F2 − F1 near the border. Our Biome tutorial does both.
  • A region graph: voronoi.neighbors(i) gives you a graph of regions. Run rivers downhill along it, route roads between towns, or path-find between provinces instead of tiles.
  • Power diagrams: additive weights with straight borders, for factions that should grow without curving.
  • 3D Voronoi: the same nearest-site rule in 3D gives fracture shards, asteroid fields and cave chambers.
  • Combine with other techniques: use Perlin noise for height inside each region, or grow cellular automata caves only in the regions marked “underground.”

Voronoi Diagram FAQ

What’s the Difference Between a Voronoi Diagram and a Delaunay Triangulation?

They’re two views of the same structure. The Voronoi diagram is the cells around each site; the Delaunay triangulation connects every pair of sites whose cells share a border. Build either one and you can get the other.

Is Voronoi Noise the Same as Worley Noise?

Mostly, yes. “Worley noise” or “cellular noise” usually means a texture made from the distance to the nearest sites (F1, F2 and combinations), usually with one random site per grid cell so it tiles forever. Engines often label the same thing “Voronoi.”

How Many Sites Should I Use?

Pick the number from the size you want a region to be on screen. A map 720 pixels wide with 90 sites gives regions roughly 60 pixels across. For faction territories, use one site per base; for a texture, use as many as you need for the detail, then scale.

Final Thoughts

Voronoi diagrams take one rule, “every point belongs to its nearest site”, and turn it into maps, borders, territories and textures. The pixel version is a dozen lines in any language. Delaunay gives you exact polygons and the region graph, and Lloyd relaxation makes it all look designed.

Start with the world map, then steal pieces: the owner map for your tile layer, weightedOwner() for your AI, F2 − F1 for your next shader.

Next steps: combine Voronoi with Perlin noise for height, then see both working together in Procedural Biome Generation. Want caves under your island? Cellular Automata in Game Development grows them from random static. Up next in the series: Poisson disk placement, for scattering trees, rocks and loot that never clump. Which lab should we build next? Tell us in the comments.

Further Learning

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top