Playground
Wave function collapse (tiled model)

Tiles that fit by rule

Wave function collapse Every cell starts with all tiles possible. The algorithm picks the cell with the fewest options, fixes one tile there by chance and removes all tiles from the neighbours that no longer fit. This repeats until every cell has one tile. The name comes from quantum mechanics, but the method is plain constraint solving. Wikipedia

Entropy The entropy of a cell says how open it still is: ln(sum of weights) - sum(weight * ln(weight)) / sum of weights over its possible tiles. Orange cells are open, the stronger the color, the more open. The lowest value goes first, so forced cells are solved early and dead ends stay rare. Wikipedia

Original work

How it works

Each cell keeps a set of possible tiles. A tile has one edge type per side, and two tiles fit when the touching edges are equal.

  • The tile sets are small: a few base tiles, each with its rotations. Rarer tiles (dead ends, crossings) have a lower weight.
  • A cell is a bit mask over the tiles. Removing a tile is one bit operation.
  • After a collapse a stack propagates the change: a neighbour keeps only tiles that fit one of the tiles still possible next to it.
  • A seeded random generator drives every choice, so the seed in the link gives the same picture. A contradiction restarts the grid with the same generator.

Source code:wfc-solver.tswfc.model.ts

Note Simplifications in this demo:

  • Only the simple tiled model: hand-made tiles with edge types, no learning from an example image.
  • On a contradiction (a cell with no tile left) the grid restarts from zero. There is no backtracking.
  • The border is closed: no pipe or road leaves the grid.
Seed
Grid size
Steps/s
Frames/s: 0Collapsed cells: 0 / 400Restarts: 0