Skip to content

← All work

Case study

Fantasy World

A procedural world-map generator in the browser: plates, terrain, climate, rivers, peoples and nations from a single seed.

Role
Solo
Stack
  • TypeScript
  • Next.js
  • d3-delaunay
  • Web Workers
  • Three.js
  • Zustand
Links
Live (opens in a new tab)Source (opens in a new tab)
A generated world map in the political view: ten nations in different colours, with rivers, capitals and a legend.
The political view of the world for the seed "portfolio".

Type a seed and get a complete world: terrain, rivers and lakes, climate and biomes, population, nations, provinces, peoples, capitals and trade hubs. Every stage is a simulation or a graph algorithm rather than painted noise, and the whole thing is deterministic.

Voronoi cells per world by default
15,000
pipeline stages, cached separately
5
terrain presets, from archipelago to rifted
6
of capitals land on the main city (was 54%)
96%

The pipeline

Each stage takes the previous stage’s mesh and returns a new one, and reports progress to the UI.

  1. Mesh

    jittered points, Delaunay / Voronoi, Lloyd relaxation

  2. Topography

    plates, noise, uplift, erosion

  3. Hydrology

    climate, biomes, lakes, rivers

  4. Population

    climate fitness, water access, cities

  5. Geopolitics

    peoples, nations, provinces, capitals

  • Mesh: one Lloyd relaxation pass moves points 70% of the way to their cell’s centroid, cutting the spread of cell areas from 0.19 to 0.14 (coefficient of variation) while keeping the map slightly irregular.
  • Plates: 4 to 7 plates with random velocities; a breadth-first search over the mesh gives every cell its distance to the nearest boundary and that boundary’s kind, so convergent edges raise mountain belts and divergent ones open rifts.
  • Sea level: elevations are re-scaled (order preserved) so each preset hits a target share of land. Before this, land swung from 10% to 53% between seeds; now it stays within about 3 points.
  • Climate: three wind belts by latitude, moisture carried along the wind so windward slopes get rain and lee sides a rain shadow, then Whittaker-style biomes from temperature and aridity.
  • Nations: a Dijkstra-style flood from all seeds at once, where crossing a river, a ridge or into another people costs extra, so borders tend to follow geography and peoples without being forced to.

Rivers that always reach somewhere

Raw terrain has pits that would trap water. A priority-flood fills them first: starting from the coast and always expanding from the lowest cell, every neighbour is raised to at least the current height plus a small epsilon, so every land cell ends with a way down to the sea. Flow is then accumulated from high to low, rivers are traced from their sources, later rivers join earlier ones at confluences, and each gets a Strahler order.

Tests check the invariants: every river ends at the sea, a lake, another river or the map edge.

src/services/hydrology/river/flow.ts (excerpt)View source (opens in a new tab)
// Seed the heap with land cells on the coast, then always grow from the lowest.
while (heap.size > 0) {
  const current = heap.pop();
  for (const neighborId of cells[current].neighbors) {
    if (isLand[neighborId] === 0 || queued[neighborId] === 1) continue;
    queued[neighborId] = 1;
    const floor = filled[current] + epsilon;
    if (filled[neighborId] < floor) {
      filled[neighborId] = floor; // raise the pit: water can now flow out
      raisedCells += 1;
    }
    heap.push(neighborId, filled[neighborId]);
  }
}

Determinism, and a bug only a JIT could cause

All randomness goes through one seeded generator (an FNV-1a hash of the seed feeding an LCG), and loops and sort comparators have fixed tie-breaks. Even so, a reload test was flaky: the same seed sometimes gave a different world.

The cause was a shuffle written as sort(() => random() - 0.5). A random comparator is not a valid ordering, so the result depends on the sort implementation, and Chrome’s Maglev JIT sorted differently from the interpreter. The fix was a proper seeded shuffle, and a guard test now fails if generation code calls Math.random() or sorts with a random comparator.

Keeping the page responsive

  • Generation runs in a Web Worker that posts stage progress; d3-delaunay objects cannot be cloned across threads, so the main thread rebuilds them from the returned points.
  • A cache keeps intermediate stages: changing only the number of nations re-runs geopolitics, not terrain and hydrology.
  • Hover lookups are coalesced to one delaunay.find per animation frame; the 3D view is one merged vertex-coloured mesh, loaded only when opened.

Trade-offs

An irregular Voronoi mesh instead of a square grid

Square cells give blocky coasts and borders, and their neighbourhoods are not uniform.

Gain
Natural-looking shapes, and a neighbour graph every algorithm can share
Cost
Geometry work up front, and the mesh must be rebuilt on the main thread after each worker run

Rivers and ridges as costs, not hard borders

Real borders often follow rivers and mountains, but not always.

Gain
Borders follow geography and peoples without looking ruled
Cost
Borders are harder to predict, so clean-up passes repair fragments and tiny nations

Status

Live, with terrain painting, route finding between two points, shareable links and JSON export. The repository’s documents describe every stage and keep a list of the realism gaps still to fix, such as terrain that should come more fully from plate tectonics.