# 5. Deeper Procgen Tests Performance and Pitfalls Part of [[Deeper Procedural Generation]]. Previous: [[4. Deeper Procgen Tile Sets Builders and Bake vs Runtime]]. ## 5.1 The tests Generators are where tests pay off most, because a broken generator still produces *something*, and it often looks plausible. Put this file in `Assets/Procedural/Tests/` with an Editor-only test asmdef that references `Procgen.Core`, then run **Window > General > Test Runner > EditMode > Run All**. `Assets/Procedural/Tests/PgenTests.cs`: **`PgenTests.cs`** ```csharp using System; using System.Collections.Generic; using NUnit.Framework; public class PgenTests { // Road tiles: sockets are "g" (grass edge) or "r" (road edge). static WfcModel Roads() { var m = new WfcModel(); m.Add("grass", "g", "g", "g", "g", weight: 6, source: 0); m.Add("straight", "r", "g", "r", "g", weight: 2, rotate: true, walkable: true, source: 1); m.Add("corner", "r", "r", "g", "g", weight: 1, rotate: true, walkable: true, source: 2); m.Add("tee", "r", "r", "g", "r", weight: 0.5, rotate: true, walkable: true, source: 3); m.Add("cross", "r", "r", "r", "r", weight: 0.2, walkable: true, source: 4); return m; } static readonly int[] Dx = { 0, 1, 0, -1 }; static readonly int[] Dy = { 1, 0, -1, 0 }; static void AssertAllEdgesMatch(WfcModel m, GeneratedMap map) { for (var y = 0; y < map.height; y++) for (var x = 0; x < map.width; x++) for (var d = 0; d < 4; d++) { int nx = x + Dx[d], ny = y + Dy[d]; if (nx < 0 || ny < 0 || nx >= map.width || ny >= map.height) continue; var a = m.Tiles[map.At(x, y)].sockets[d]; var b = m.Tiles[map.At(nx, ny)].sockets[(int)WfcModel.Opposite((Dir)d)]; Assert.AreEqual(a, b, quot;({x},{y}) dir {d}"); } } [Test] public void RotationsAreGeneratedWithoutDuplicates() { var m = Roads(); // grass 1, straight 2 (0 and 90), corner 4, tee 4, cross 1 Assert.AreEqual(12, m.Count); var straight90 = m.Tiles[m.IndexOf("straight@90")]; Assert.AreEqual("g,r,g,r", string.Join(",", straight90.sockets)); var corner90 = m.Tiles[m.IndexOf("corner@90")]; Assert.AreEqual("g,r,r,g", string.Join(",", corner90.sockets)); // north+east turned to east+south } [Test] public void SameSeedSameMap() { var a = MapGenerator.Generate(Roads(), 12, 12, 42); var b = MapGenerator.Generate(Roads(), 12, 12, 42); Assert.IsTrue(a != null && b != null); Assert.AreEqual(string.Join(",", a.tiles), string.Join(",", b.tiles)); Assert.AreEqual(a.attempts, b.attempts); } [Test] public void DifferentSeedsDiffer() { var a = MapGenerator.Generate(Roads(), 12, 12, 1); var b = MapGenerator.Generate(Roads(), 12, 12, 2); Assert.AreNotEqual(string.Join(",", a.tiles), string.Join(",", b.tiles)); } [Test] public void EveryNeighbourFits() { var m = Roads(); for (ulong seed = 0; seed < 20; seed++) { var map = MapGenerator.Generate(m, 10, 8, seed); Assert.IsTrue(map != null, "seed " + seed); AssertAllEdgesMatch(m, map); } } [Test] public void PresetsAreHonoured() { var m = Roads(); var grass = m.MaskOf(t => t.id == "grass"); var cross = m.MaskOf(t => t.id == "cross"); var map = MapGenerator.Generate(m, 9, 9, 7, preset: s => { for (var i = 0; i < 9; i++) { s.Restrict(i, 0, grass); s.Restrict(i, 8, grass); s.Restrict(0, i, grass); s.Restrict(8, i, grass); } s.Restrict(4, 4, cross); // a crossroads in the middle }); Assert.IsTrue(map != null); for (var i = 0; i < 9; i++) { Assert.AreEqual("grass", m.Tiles[map.At(i, 0)].id); Assert.AreEqual("grass", m.Tiles[map.At(0, i)].id); } Assert.AreEqual("cross", m.Tiles[map.At(4, 4)].id); AssertAllEdgesMatch(m, map); } [Test] public void ConnectivityConstraintRejectsSplitNetworks() { var m = Roads(); var grass = m.MaskOf(t => t.id == "grass"); var accepted = 0; for (ulong seed = 0; seed < 10; seed++) { var map = MapGenerator.Generate(m, 10, 10, seed, maxAttempts: 200, preset: s => { for (var i = 0; i < 10; i++) { s.Restrict(i, 0, grass); s.Restrict(i, 9, grass); s.Restrict(0, i, grass); s.Restrict(9, i, grass); } }, validate: g => MapGenerator.WalkableConnected(m, g, "r")); if (map == null) continue; accepted++; Assert.IsTrue(MapGenerator.WalkableConnected(m, map, "r")); } Assert.IsTrue(accepted >= 8, "accepted " + accepted); } [Test] public void ImpossiblePresetFailsCleanly() { var m = new WfcModel(); m.Add("a", "x", "x", "x", "x"); m.Add("b", "y", "y", "y", "y"); var a = m.MaskOf(t => t.id == "a"); var b = m.MaskOf(t => t.id == "b"); // a and b can never touch, so forcing them side by side must fail every attempt var map = MapGenerator.Generate(m, 2, 1, 1, maxAttempts: 5, preset: s => { s.Restrict(0, 0, a); s.Restrict(1, 0, b); }); Assert.IsTrue(map == null); } [Test] public void RandomIsDeterministicAndInRange() { var a = new SeededRandom(123); var b = new SeededRandom(123); var counts = new int[6]; for (var i = 0; i < 60000; i++) { var v = a.Range(0, 6); Assert.AreEqual(v, b.Range(0, 6)); counts[v]++; } foreach (var c in counts) Assert.IsTrue(c > 9500 && c < 10500, "count " + c); // about 10000 each for (var i = 0; i < 1000; i++) { var d = a.NextDouble(); Assert.IsTrue(d >= 0 && d < 1); } } [Test] public void DerivedStreamsAreStableAndIndependent() { Assert.AreEqual(SeededRandom.Derive(42, "rooms"), SeededRandom.Derive(42, "rooms")); Assert.AreNotEqual(SeededRandom.Derive(42, "rooms"), SeededRandom.Derive(42, "loot")); Assert.AreNotEqual(SeededRandom.Derive(42, "rooms"), SeededRandom.Derive(43, "rooms")); Assert.AreNotEqual(SeededRandom.Derive(42, 0), SeededRandom.Derive(42, 1)); } [Test] public void SeedZeroStillWorks() { var r = new SeededRandom(0); Assert.AreNotEqual(r.NextULong(), r.NextULong()); } [Test] public void WeightsShiftTheMix() { var m = Roads(); int grass = 0, total = 0; for (ulong seed = 0; seed < 10; seed++) { var map = MapGenerator.Generate(m, 16, 16, seed); foreach (var t in map.tiles) { total++; if (m.Tiles[t].id == "grass") grass++; } } Assert.IsTrue(grass > total / 3, quot;grass {grass} of {total}"); // weight 6 of ~19 per cell, but neighbours pull it up } } ``` | Test | Guards against | |---|---| | `RotationsAreGeneratedWithoutDuplicates` | wrong rotation direction; duplicate symmetric variants skewing weights | | `SameSeedSameMap` | any hidden randomness (global `Random`, dictionary order, time) | | `DifferentSeedsDiffer` | a seed that's ignored | | `EveryNeighbourFits` | propagation bugs, over 20 seeds | | `PresetsAreHonoured` | borders and landmarks being overwritten | | `ConnectivityConstraintRejectsSplitNetworks` | validators that are never called, or wrong | | `ImpossiblePresetFailsCleanly` | a map returned despite an unsatisfiable preset (this caught a real bug) | | `RandomIsDeterministicAndInRange` | out-of-range values, and bias in `Range` (60,000 rolls of a d6) | | `DerivedStreamsAreStableAndIndependent` | streams that collide, or change between runs | | `SeedZeroStillWorks` | the all-zeros xorshift trap | | `WeightsShiftTheMix` | weights being ignored | Output from the run used for this note (compiled outside Unity against NUnit's API): ``` PASS RotationsAreGeneratedWithoutDuplicates PASS SameSeedSameMap PASS DifferentSeedsDiffer PASS EveryNeighbourFits PASS PresetsAreHonoured PASS ConnectivityConstraintRejectsSplitNetworks PASS ImpossiblePresetFailsCleanly PASS RandomIsDeterministicAndInRange PASS DerivedStreamsAreStableAndIndependent PASS SeedZeroStillWorks PASS WeightsShiftTheMix 11 passed, 0 failed ``` The first run failed `ImpossiblePresetFailsCleanly`. The preset forced two tiles that can never touch side by side. The first `Restrict` propagated, which narrowed the second cell to the first tile type, so the second `Restrict` found nothing left and returned false. The preset ignored that return value, and `Run` went on to build a map that broke the preset. The fix was to make failure sticky: `Failed` is set on any contradiction and `Run` checks it first. ## 5.2 Performance Measured outside Unity on the box that wrote this (.NET, JIT): **50 maps of 32 × 32 in about 2.6 s, so roughly 50 ms per map**, with no border or validator. That's fine for a loading screen or a bake, but too slow to do mid-frame. Expect IL2CPP to be in the same range, and slower on Quest or mobile. Where the time goes, and what to do: - **`LowestEntropyCell` scans every cell** on every collapse, which is O(cells²) over a whole map. For big maps, cache each cell's entropy and update only the cells that propagation touched, or keep a priority queue. - **Logs are recomputed** each time. Precompute `w · log w` per tile. - **Generate off the main thread.** The core has no Unity types, so run `MapGenerator.Generate` in a `Task.Run` or an `Awaitable.BackgroundThreadAsync` section and place prefabs back on the main thread. See [[2. Awaitable Waits and Thread Switches]]. - **Chunk it.** For endless worlds, generate one chunk at a time, presetting each chunk's edges from its already-generated neighbours. ## 5.3 Pitfalls 1. **Using `UnityEngine.Random` anywhere in generation.** One call shifts everything after it. Search the generator folder for `Random.` before shipping. 2. **Iterating a `Dictionary` or `HashSet` to make choices.** Their order isn't guaranteed. Sort first, or use lists. 3. **`string.GetHashCode()` in seeds.** It's randomised per process in modern .NET. Use the FNV-1a in `SeededRandom.Derive`. 4. **Floats in generation logic across platforms.** Comparing floats from different hardware can differ in the last bit. This solver's only float use is weights and entropy, where a one-bit difference could in principle change a tie-break. If you need cross-platform identical maps (lockstep multiplayer), switch weights to integers and entropy to a count of options. 5. **Editing the tile set after baking.** Baked indices point to variants by position. The fingerprint check catches it and regenerates; don't silence the warning. 6. **Rotation the wrong way.** Socket rotation and prefab rotation must both be clockwise seen from above. Test with one corner tile on a 1 × 1 map preset to each rotation. 7. **Too few transition tiles.** If a socket appears on only one kind of edge, WFC paints itself into corners. A dead-end tile, or grass that can meet anything, makes sets much more forgiving. 8. **Raising `maxAttempts` to hide a bad validator.** If maps routinely need dozens of attempts, change weights or presets (part 3). 9. **Seed not shown to the player.** Show `LastSeed` on the pause or game-over screen, so it can be shared and reported. ## Related - [[Game Programming Patterns (Review)]]: its *Game Loop* advice on keeping heavy work out of the frame applies directly to generation. - [[Level Up! (Review)]]: test the experience, not just the algorithm. Play ten seeds in a row before you trust it. - [[Procedural Generation]], [[Tilemaps and Tilesets]].