Procedural Generation Basics: Noise, WFC, BSP Dungeons and AI
Procedural generation basics for game devs - Perlin noise, Wave Function Collapse, BSP dungeons, terrain - and when an AI agent should build the level instead.

Procedural generation means writing rules that build game content, instead of placing every tile, tree and room by hand. The basics fit in four classic techniques: noise (Perlin or Simplex) for terrain and natural variation, Wave Function Collapse for tile-based layouts that follow adjacency rules, BSP (binary space partitioning) for dungeons made of rooms and corridors, and seeds so that the same input always gives the same world. In 2026 there is also a practical question in front of all of them: do you need a level that is different on every run, or one good level? If you need one good level, an AI agent can now build it by hand directly in the engine. If you need a new level every run, the agent can write the procedural generator for you.
Two Approaches: Agent-Built Levels or Agent-Written Generators
In our experience with AI Game Developer, "generate a level" hides two different jobs.
The first job is a handcrafted level that you would otherwise build yourself. A tutorial island, a boss arena, a town hub. Here the AI agent works like a level designer with infinite patience: it places objects, sculpts terrain, paints layers and arranges props directly in the open editor, then takes a screenshot and adjusts. The result is a normal scene with no generator to maintain.
The second job is a level that must be unique on every run. A roguelike dungeon, an endless runner, a survival map with a new seed every game. Here you need code that runs at play time: a procedural generator. The agent writes that generator, runs it in the editor, looks at the output for a few seeds, and fixes the rules until the results are good.
A quick way to choose:
- If players see the level once and it must be memorable, let the agent build it by hand.
- If players replay the game and expect a new layout each time, have the agent write a generator.
- If you need hundreds of similar but not identical spaces (forests, rock fields, city blocks), use a generator in the editor, then let the agent or you hand-fix the important spots.
- If you are prototyping and do not yet know, start with a hand-built level: it is faster to judge fun on one fixed level.
The trade-off is control against variety. A hand-built level is exactly what you approved, and it can tell a story through placement. A generator gives replay value and scale, but every rule has edge cases: unreachable rooms, a tree in a doorway, a spawn point inside a wall. Generators need validation code and testing across many seeds.
The Foundation: Seeds and Determinism
Before any algorithm, get one thing right: every random choice in a generator should come from a seeded random number generator that you control. Then seed 1234 always produces the same level, which gives you reproducible bugs, shareable worlds, daily challenges and tests.
Rules we recommend:
- Create one random generator per generation run from an explicit seed, and pass it down. Do not call a global random function in the middle of the generator.
- Never use the engine's frame time, physics or dictionary iteration order as an input. They change between runs and break determinism.
- Log the seed with every generated level, in development builds at least.
- Split the seed per system (layout, loot, decoration), so that a change in decoration rules does not reshuffle the whole map.
In Unity C# a minimal version looks like this:
using System;
public sealed class LevelSeed
{
public readonly int Seed;
public LevelSeed(int seed) { Seed = seed; }
// One independent stream per subsystem: layout, loot, decoration.
public Random Stream(string name)
{
unchecked
{
int hash = Seed;
foreach (char c in name) hash = hash * 31 + c;
return new Random(hash);
}
}
}Note that the string hash is computed by hand: in .NET, string.GetHashCode can differ between runs, so it is not safe for seeds.
Perlin Noise for Terrain and Natural Variation
Noise functions return smooth random values: nearby inputs give nearby outputs. Perlin noise, invented by Ken Perlin in the 1980s, and its successor Simplex noise are the standard for heightmaps, cave density, biome maps, cloud textures and the small variations that make a scene look natural (tree scale, rock rotation, grass colour).
A single layer of noise looks like soft rolling hills. Real-looking terrain comes from adding several layers, called octaves: each octave has a higher frequency (more detail) and a lower amplitude (less influence). The two settings that control it are lacunarity (how much the frequency grows per octave, usually 2) and persistence (how much the amplitude shrinks, usually 0.5).
In Unity, Mathf.PerlinNoise(x, y) returns a value roughly between 0 and 1; Unity's documentation notes that the result can be slightly below 0 or above 1, so clamp it if you need a strict range. Godot has the FastNoiseLite resource with several noise types, and Unreal offers noise nodes in materials and in its PCG graphs.
Here is a fractal heightmap for a Unity Terrain:
using UnityEngine;
public static class NoiseTerrain
{
public static void Apply(Terrain terrain, int seed,
float scale = 0.004f, int octaves = 5,
float persistence = 0.5f, float lacunarity = 2f)
{
TerrainData data = terrain.terrainData;
int res = data.heightmapResolution;
float[,] heights = new float[res, res];
var rng = new System.Random(seed);
float offsetX = rng.Next(-10000, 10000);
float offsetY = rng.Next(-10000, 10000);
float worldStep = data.size.x / (res - 1);
for (int y = 0; y < res; y++)
for (int x = 0; x < res; x++)
{
float amplitude = 1f, frequency = 1f, sum = 0f, norm = 0f;
for (int o = 0; o < octaves; o++)
{
float sx = (x * worldStep * scale + offsetX) * frequency;
float sy = (y * worldStep * scale + offsetY) * frequency;
sum += Mathf.PerlinNoise(sx, sy) * amplitude;
norm += amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
heights[y, x] = Mathf.Clamp01(sum / norm);
}
data.SetHeights(0, 0, heights);
}
}The seed only moves the sample offset, which is the usual trick: Mathf.PerlinNoise has no seed parameter, so you sample a different region of the same infinite noise field.
Practical tips:
- Shape the noise after you sample it. Raising the value to a power (for example Mathf.Pow(h, 1.6f)) flattens valleys and sharpens peaks. A falloff toward the edges turns a heightmap into an island.
- Use a second, low-frequency noise as a biome or moisture map, and pick textures and vegetation from height plus moisture.
- Place objects with noise plus a minimum distance (Poisson disc sampling) instead of pure random, or forests look like static.
- Keep scale in world units, not heightmap pixels, so a resolution change keeps the shape.
Wave Function Collapse for Tile-Based Levels
Wave Function Collapse (WFC) was published by Maxim Gumin in 2016 (github.com/mxgmn/WaveFunctionCollapse). It fills a grid with tiles so that every pair of neighbours follows the adjacency rules you give it, or rules it learns from a small example image. According to its repository, WFC generates levels in Bad North, Caves of Qud and Townscaper, among others.
The algorithm in plain words:
- Every cell starts with all tiles possible.
- Pick the cell with the fewest remaining options (the lowest entropy), breaking ties with the seeded random generator.
- Collapse it: choose one of its options, weighted by how common each tile should be.
- Propagate: remove options from the neighbours that are no longer compatible, and repeat that outward until nothing changes.
- Go back to step 2 until every cell has one tile. If a cell ends up with zero options, it is a contradiction: restart with a new seed, or backtrack.
Where WFC is strong: towns, roads, pipes, interiors, anything where local rules ("water touches sand, never grass") define what looks right. Where it is weak: it has no sense of the big picture. It does not know that the level needs an entrance, an exit and a path between them. In practice you pre-place those (fix certain cells before collapsing), then run WFC around them, then check connectivity with a flood fill.
Tips:
- Start with a small tile set of 5 to 15 tiles. Each new tile multiplies the ways rules can conflict.
- Tile weights matter as much as rules. Too many rare tiles and the output looks noisy.
- Expect contradictions on large grids. Generate in chunks, or keep restarts cheap.
BSP Dungeons: Rooms and Corridors
Binary space partitioning is the classic way to build a roguelike dungeon. You take the whole map rectangle, split it in two with a random horizontal or vertical cut, split each half again, and continue until the pieces are close to room size. Then you place one room inside each leaf and connect neighbouring rooms with corridors. Because the rooms never overlap and every room is connected, the whole dungeon is reachable, which is the main advantage of BSP over scattering rooms at random.
The split recursion is the heart of it:
using System;
using System.Collections.Generic;
public static class BspDungeon
{
const int MinLeaf = 10;
// Splits the area until the pieces are room-sized and adds each leaf in tree order.
public static void Split(int x, int y, int w, int h, Random rng, List<(int X, int Y, int W, int H)> leaves)
{
bool canH = h >= MinLeaf * 2, canV = w >= MinLeaf * 2;
if (!canH && !canV) { leaves.Add((x, y, w, h)); return; }
if (canH && (!canV || rng.Next(2) == 0))
{
int cut = rng.Next(MinLeaf, h - MinLeaf + 1);
Split(x, y, w, cut, rng, leaves);
Split(x, y + cut, w, h - cut, rng, leaves);
}
else
{
int cut = rng.Next(MinLeaf, w - MinLeaf + 1);
Split(x, y, cut, h, rng, leaves);
Split(x + cut, y, w - cut, h, rng, leaves);
}
}
}Call it with the full map, for example BspDungeon.Split(0, 0, 80, 60, new Random(seed), leaves). Then place a room of random size inside each leaf and carve an L-shaped corridor from each room to the next one in the list. Because the leaves come out in tree order, neighbours in the list are usually siblings, and the chain keeps every room reachable.
What BSP gives you and what it does not:
- Good: guaranteed connectivity, no overlapping rooms, easy to control density with the minimum leaf size.
- Weak: the result looks like a tree, because it is one. Add a few extra corridors between nearby rooms to create loops.
- Weak: no gameplay structure. Choose the start and the boss room afterwards, for example the two rooms farthest apart by path distance, and place keys and locks along the path between them.
Terrain at Scale: Engine Tools Before Custom Code
For open worlds you rarely write everything from scratch. The engines already ship tools for it, and they are often the best place to start:
- Unity: the built-in Terrain system with heightmaps, texture layers, trees and detail meshes. The noise code above writes straight into it.
- Unreal Engine: Landscape for the ground and the Procedural Content Generation framework (PCG) for scattering forests, rocks and props by rules. Epic declared PCG production-ready in Unreal Engine 5.7 (November 2025).
- Godot: no built-in heightmap terrain in the core engine; the community Terrain3D addon is a popular choice, along with GridMap for 3D tile levels and TileMap layers for 2D.
Procedural Generation with an AI Agent in Practice
This is where the two approaches from the start of the post meet real tools. AI Game Developer connects an AI agent to Unity, Unreal and Godot, and the agent works in the live editor: it writes short code and runs it immediately inside the running editor (C# in Unity, Python in Unreal, also Godot), then checks the result with screenshots of the viewport.
For a hand-built level, the agent uses engine extensions directly. The Unity Terrain extension lets it create terrains, sculpt and sample heights, paint texture layers and scatter trees; Tilemap, ProBuilder and Splines cover 2D maps, greybox geometry and paths. In Unreal the Landscape extension covers the ground, and the PCG extension lets it author PCG graphs, place them on volumes, generate and read back what they made, for example forests and rocks over a landscape, filtered by slope and height and kept off roads. In Godot there are extensions for Terrain3D, GridMap, Tilemap and CSG. You describe the level ("a valley with a river, a village on the east bank") and correct it in plain words.
For a generator, the agent writes the code you saw above, adapted to your game, and then does what a human would do: runs it for a handful of seeds, looks at the screenshots, and fixes the rules. A request that works well in our experience:
- Describe the content and the constraints: "BSP dungeon, 80 by 60 tiles, 8 to 14 rooms, start and boss room far apart, one loop at least".
- Ask for a seed parameter and a validation step: a flood fill that fails the run if any room is unreachable.
- Ask the agent to run seeds 1 to 20 in the editor and report which fail validation, with screenshots of three different results.
- Judge the screenshots yourself and say what to change: "rooms are too uniform, allow some 3 by 3 closets and one large hall".
- Ask for tests that generate many seeds and assert the invariants, so later changes cannot break them silently.
For large generators, turn on plan mode first so the agent proposes the structure (passes, data types, where seeds split) before it writes anything: ai-game.dev/blog/plan-mode-ai-agent-game-development. Long sessions over many generated objects are also where our RQL query tools help, because they cut the tokens an agent spends on engine data; the benchmark is at ai-game.dev/docs/rql.
A Checklist Before You Ship Procedural Content
- Every random choice comes from a seeded generator, and the seed is logged.
- A validation pass rejects broken output: unreachable areas, blocked doors, spawns inside geometry, missing exits.
- You have tested at least a few hundred seeds automatically, not only the ones you looked at.
- Important places (start, boss, story moments) are placed by rules or by hand, not left to chance.
- Generation time is measured on your lowest target hardware, and long work is split across frames or done during loading.
- Generated content has hand-made accents: a few authored rooms or landmarks mixed into the procedural parts make the whole world feel designed.
Get Started
Pick the approach first. If you need one great level, describe it to an agent and let it build the level in the editor. If you need a new level every run, start with seeds, then add noise for terrain, BSP for dungeons or WFC for tile layouts, and let the agent write and test the generator across many seeds. AI Game Developer works with Unity, Unreal and Godot (ai-game.dev/engines/unity, ai-game.dev/engines/unreal, ai-game.dev/engines/godot), and you can download the desktop app at ai-game.dev/download.

