quot;{id}@{r * 90}", sockets = (string[])sockets.Clone(), weight = weight, rotation = r, source = source, walkable = walkable }); } // rotate a quarter turn clockwise: what faced north now faces east sockets = new[] { sockets[3], sockets[0], sockets[1], sockets[2] }; } _compat = null; } public ulong Compatible(int tile, Dir d) { if (_compat == null) Build(); return _compat[tile, (int)d]; } public int IndexOf(string id) => _tiles.FindIndex(t => t.id == id); public ulong MaskOf(Func<WfcTile, bool> predicate) { ulong m = 0; for (var i = 0; i < _tiles.Count; i++) if (predicate(_tiles[i])) m |= 1UL << i; return m; } public static Dir Opposite(Dir d) => (Dir)(((int)d + 2) & 3); void Build() { _compat = new ulong[_tiles.Count, 4]; for (var a = 0; a < _tiles.Count; a++) for (var d = 0; d < 4; d++) for (var b = 0; b < _tiles.Count; b++) if (_tiles[a].sockets[d] == _tiles[b].sockets[(int)Opposite((Dir)d)]) _compat[a, d] |= 1UL << b; } } /// <summary> /// Wave Function Collapse on a grid. Every cell starts as "any tile". Repeatedly: pick the cell with /// the fewest options (lowest entropy), collapse it to one tile by weight, then propagate: remove /// options from neighbours that no longer fit, and from their neighbours, until nothing changes. /// A cell with zero options is a contradiction: the attempt fails and the caller retries. /// </summary> public sealed class WfcSolver { static readonly int[] Dx = { 0, 1, 0, -1 }; static readonly int[] Dy = { 1, 0, -1, 0 }; readonly WfcModel _model; readonly ulong[] _cells; readonly Stack<int> _stack = new Stack<int>(); public WfcSolver(WfcModel model, int width, int height) { if (model.Count == 0) throw new ArgumentException("The model has no tiles."); _model = model; Width = width; Height = height; _cells = new ulong[width * height]; } public int Width { get; } public int Height { get; } public int Collapses { get; private set; } /// <summary>True once any restriction or propagation in this attempt hit a contradiction.</summary> public bool Failed { get; private set; } public ulong Possible(int x, int y) => _cells[x + y * Width]; /// <summary>Starts a fresh attempt with every option open.</summary> public void Reset() { for (var i = 0; i < _cells.Length; i++) _cells[i] = _model.AllMask; Collapses = 0; Failed = false; _stack.Clear(); } /// <summary>Limits a cell to a set of tiles before solving (borders, an entrance, a hand-placed landmark).</summary> public bool Restrict(int x, int y, ulong mask) { var i = x + y * Width; var next = _cells[i] & mask; if (next == 0) { Failed = true; return false; } // remembered, so Run() can't quietly ignore it if (next != _cells[i]) { _cells[i] = next; _stack.Push(i); } return Propagate(); } /// <summary>Runs one attempt to completion. Returns false on a contradiction.</summary> public bool Run(SeededRandom rng) { if (Failed) return false; while (true) { var cell = LowestEntropyCell(rng); if (cell < 0) return true; // every cell has exactly one option _cells[cell] = 1UL << PickWeighted(_cells[cell], rng); Collapses++; _stack.Push(cell); if (!Propagate()) return false; } } /// <summary>The single tile index at a cell, or -1 if it isn't collapsed.</summary> public int TileAt(int x, int y) { var m = Possible(x, y); if (m == 0 || (m & (m - 1)) != 0) return -1; var i = 0; while ((m & 1UL) == 0) { m >>= 1; i++; } return i; } bool Propagate() { while (_stack.Count > 0) { var i = _stack.Pop(); int x = i % Width, y = i / Width; for (var d = 0; d < 4; d++) { int nx = x + Dx[d], ny = y + Dy[d]; if (nx < 0 || ny < 0 || nx >= Width || ny >= Height) continue; ulong allowed = 0, m = _cells[i]; for (var t = 0; m != 0; t++, m >>= 1) if ((m & 1UL) != 0) allowed |= _model.Compatible(t, (Dir)d); var n = nx + ny * Width; var next = _cells[n] & allowed; if (next == _cells[n]) continue; if (next == 0) { _cells[n] = 0; _stack.Clear(); Failed = true; return false; } _cells[n] = next; _stack.Push(n); } } return true; } int LowestEntropyCell(SeededRandom rng) { var best = -1; var bestEntropy = double.MaxValue; for (var i = 0; i < _cells.Length; i++) { var m = _cells[i]; if ((m & (m - 1)) == 0) continue; // 0 or 1 option: nothing to choose double sum = 0, sumLog = 0; for (var t = 0; m != 0; t++, m >>= 1) { if ((m & 1UL) == 0) continue; var w = _model.Tiles[t].weight; sum += w; sumLog += w * Math.Log(w); } var entropy = Math.Log(sum) - sumLog / sum + rng.NextDouble() * 1e-6; // tiny noise breaks ties randomly if (entropy < bestEntropy) { bestEntropy = entropy; best = i; } } return best; } int PickWeighted(ulong mask, SeededRandom rng) { double total = 0; var m = mask; for (var t = 0; m != 0; t++, m >>= 1) if ((m & 1UL) != 0) total += _model.Tiles[t].weight; var r = rng.NextDouble() * total; m = mask; var last = -1; for (var t = 0; m != 0; t++, m >>= 1) { if ((m & 1UL) == 0) continue; last = t; r -= _model.Tiles[t].weight; if (r < 0) return t; } return last; // floating-point leftovers land on the last option } } /// <summary>The result of a generation: tile indices per cell, the seed, and how many tries it took.</summary> public sealed class GeneratedMap { public int width, height; public int[] tiles; // x + y * width public ulong seed; public int attempts; public int At(int x, int y) => tiles[x + y * width]; } /// <summary> /// Seeded generate-and-test: run WFC, then check whole-map constraints that local adjacency can't /// express (everything walkable is connected, at least N road tiles...). Each attempt uses its own /// derived seed, so attempt 3 of seed 42 is always the same map. /// </summary> public static class MapGenerator { public delegate void Preset(WfcSolver solver); public delegate bool Validate(GeneratedMap map); public static GeneratedMap Generate(WfcModel model, int width, int height, ulong seed, int maxAttempts = 50, Preset preset = null, Validate validate = null) { var solver = new WfcSolver(model, width, height); for (var attempt = 0; attempt < maxAttempts; attempt++) { var rng = new SeededRandom(SeededRandom.Derive(seed, attempt)); solver.Reset(); preset?.Invoke(solver); if (!solver.Run(rng)) continue; var map = new GeneratedMap { width = width, height = height, tiles = new int[width * height], seed = seed, attempts = attempt + 1 }; for (var y = 0; y < height; y++) for (var x = 0; x < width; x++) map.tiles[x + y * width] = solver.TileAt(x, y); if (validate == null || validate(map)) return map; } return null; } /// <summary>True if every walkable cell can reach every other through walkable neighbours whose sockets join.</summary> public static bool WalkableConnected(WfcModel model, GeneratedMap map, string joinSocket) { var start = -1; var walkable = 0; for (var i = 0; i < map.tiles.Length; i++) if (model.Tiles[map.tiles[i]].walkable) { walkable++; if (start < 0) start = i; } if (walkable == 0) return false; var seen = new bool[map.tiles.Length]; var queue = new Queue<int>(); queue.Enqueue(start); seen[start] = true; var reached = 0; int[] dx = { 0, 1, 0, -1 }, dy = { 1, 0, -1, 0 }; while (queue.Count > 0) { var i = queue.Dequeue(); reached++; int x = i % map.width, y = i / map.width; var tile = model.Tiles[map.tiles[i]]; for (var d = 0; d < 4; d++) { if (tile.sockets[d] != joinSocket) continue; int nx = x + dx[d], ny = y + dy[d]; if (nx < 0 || ny < 0 || nx >= map.width || ny >= map.height) continue; var n = nx + ny * map.width; if (seen[n] || !model.Tiles[map.tiles[n]].walkable) continue; seen[n] = true; queue.Enqueue(n); } } return reached == walkable; } } ``` This part covers `WfcModel` and `WfcSolver`. `MapGenerator` and `GeneratedMap` are part 3. ## 2.4 WfcModel - **`Add` generates rotations.** Rotating a quarter turn clockwise moves each socket one place round: the old North becomes the new East. Rotations whose sockets match one already added are skipped, which is why a straight road gives two variants, not four. Each variant remembers its `rotation` and `source` so the builder can place the right prefab at the right angle (part 4). - **`Compatible(tile, dir)`** is a precomputed table: for each tile and direction, a **bitmask** of the tiles allowed next to it. It's built lazily on first use. - **At most 64 variants**, because a cell's options are one `ulong`, one bit per variant. Checking "is tile 5 possible here" is a single AND. For larger sets, swap `ulong` for an array of `ulong`s or `System.Collections.BitArray`. ## 2.5 WfcSolver **Cells** are an array of masks, `x + y × width`. A cell with one bit set is collapsed. **Choosing the next cell: lowest entropy.** Not just "fewest options": the solver uses Shannon entropy over the weights: ``` H = log(Σw) − (Σ w·log w) / Σw ``` A cell that could be grass (weight 6) or a cross (0.2) is almost certainly grass, so its entropy is low, even though it has two options. Collapsing the most certain cells first means contradictions show up early, while they're cheap. A tiny random amount (10⁻⁶) is added so that ties, which are common at the start, break randomly instead of always picking the top-left cell. That would leave a visible sweep pattern. **Collapsing** picks one option by weight with `SeededRandom.NextDouble`. Weights are what make the map look right: grass at 6 and cross at 0.2 is why the example map is mostly fields with occasional junctions. **Propagating** uses a stack of cells whose options just shrank. For each such cell and each direction: 1. OR together the compatibility masks of every tile still possible in the cell. That's everything the neighbour may still be. 2. AND that into the neighbour's mask. 3. If the neighbour lost options, push it, because its own neighbours may now lose options too. If it lost *all* options, it's a contradiction. This is the arc-consistency idea from constraint solving (AC-3), specialised to a grid. It runs until the stack is empty, so after each collapse every cell is consistent with every neighbour. **Contradictions are sticky.** Once a `Restrict` or a propagation fails, `Failed` stays true until `Reset`, and `Run` returns false immediately. The first version of this code returned false from `Restrict` but let `Run` carry on, so a preset that could never work still produced a map. A test caught it (part 5). ## 2.6 Why not backtrack? When a contradiction happens, this solver throws the attempt away and the generator retries with a new derived seed. Backtracking (undoing the last choice and trying another) is more efficient on hard tile sets, but it needs a stack of saved grids and is much harder to read. With a forgiving tile set like this one, contradictions are rare: 200 out of 200 bordered maps solved on the first attempt. Add backtracking only if you measure frequent restarts. ## Related - [[Game Programming Patterns (Review)]]: *Data Locality* — the whole solver is a flat array of 64-bit masks, which is why it's fast without any clever code. - [[Level Up! (Review)]]: weights are a design tool: they set the mood of the map more than the rules do. - [[Tilemaps and Tilesets]] for drawing a 2D result with a Tilemap instead of prefabs.