GitHub快速開始

API 參考取自原始碼中的 Go 文件註解,以英文撰寫。

package procgen

import "github.com/nsgo-dev/game/pkg/procgen"

概覽

Package procgen generates seeded, deterministic 2D levels on a tile grid: BSP rooms joined by corridors, cellular-automata caves, wave function collapse over a YAML rule set, and hand-made room templates placed on a dungeon layout graph.

Every generator draws all of its randomness from a random.Stream, so the same seed and configuration produce the same Grid, cell for cell, on every operating system and architecture. BSP, Cave and GenerateRooms always leave their walkable cells as one 4-connected region, and so does WFC unless WFCConfig.AllowDisconnected is set or its rules have no walkable tile; Regions and Connected check this, and a game can run the same check on a level it edits afterwards.

A Grid holds one uint32 value per cell. BSP, Cave and GenerateRooms write Wall and Floor (room templates may also use custom tile values); WFC writes indexes into its Rules' tiles. Paint copies a Grid into a tilemap.Tilemap layer through a value-to-GID function, and GridFromTilemap reads a tilemap layer back into a Grid.

索引

常數

const (
	// Wall is a solid cell. It is also the value of every cell of a new Grid.
	Wall uint32 = 0
	// Floor is a walkable cell.
	Floor uint32 = 1
)

Cell values written by BSP and Cave.

const MaxCells = 1 << 24

MaxCells is the largest Width*Height any generator accepts. It keeps cell counts within int on 32-bit targets and cell indexes within int32, and bounds a level's memory.

const MaxSide = 1 << 16

MaxSide is the largest Width or Height any generator accepts.

const MaxWFCCells = 1 << 12

MaxWFCCells is the largest Width*Height WFC accepts, 64 by 64. Each collapse rescans the grid and, with the connectivity constraint, searches the walkable area again, so one attempt costs roughly the square of the cell count: a 32 by 24 level takes tens of milliseconds, 64 by 64 about a second, and 128 by 128 would take more than ten. Build a larger map from smaller WFC pieces, or use BSP or Cave for it.

const RoomTemplatesVersion = 1

RoomTemplatesVersion is the room template set schema version this package reads and writes.

const RulesVersion = 1

RulesVersion is the WFC rule file schema version this package reads and writes.

變數

var ErrInvalidConfig = errors.New("procgen: invalid config")

ErrInvalidConfig is wrapped by every error a generator returns for a configuration it cannot use.

var ErrNoFloor = errors.New("procgen: generated level has no floor")

ErrNoFloor is returned when a generator ends with no walkable cell, for example a cave whose noise smoothed into solid rock. Retrying with another seed usually succeeds.

var ErrNoLayout = errors.New("procgen: room placement found no valid layout")

ErrNoLayout is returned when room placement exhausts its attempts without finding a non-overlapping, connected layout that satisfies the graph and templates.

var ErrNoSolution = errors.New("procgen: wave function collapse found no solution")

ErrNoSolution is returned when WFC exhausts its attempts without a level that satisfies the rules and, unless disabled, the connectivity constraint.

函式

func EncodeRoomTemplates(rt *RoomTemplates) ([]byte, error)

EncodeRoomTemplates validates rt and writes it as deterministic 2-space YAML with fields in fixed order, so ParseRoomTemplates followed by EncodeRoomTemplates reproduces the exact bytes.

func EncodeRules(r *Rules) ([]byte, error)

EncodeRules validates r and writes it as 2-space YAML with fields in a fixed order and tiles and neighbors in their given order, so ParseRules followed by EncodeRules reproduces a file EncodeRules wrote.

func IsFloor(v uint32) bool

IsFloor reports whether v is Floor. It is the passable function for grids made by BSP and Cave.

型別

type BSPConfig struct {
	// Width and Height are the level's size in cells. The outermost ring of cells is always Wall, so both must be at least MinLeaf+2 and at most MaxSide, and Width*Height at most MaxCells.
	Width, Height int
	// MinLeaf is the smallest side of a partition, in cells; a partition is split while one of its sides is at least twice MinLeaf. The default is 10, and it must be at least MinRoom+2*Padding.
	MinLeaf int
	// MinRoom is the smallest side of a room, in cells. The default is 4.
	MinRoom int
	// MaxRoom caps a room's side, in cells; 0 leaves rooms as large as their partition allows. When set it must be at least MinRoom.
	MaxRoom int
	// Padding is the number of Wall cells kept between a room and the edges of its partition. The default and minimum is 1, which keeps neighbouring rooms from merging.
	Padding int
	// Loops adds this many extra corridors between randomly chosen rooms on top of the spanning corridors, so the level has cycles. The default is 0.
	Loops int
}

BSPConfig configures BSP. Zero fields take the defaults given on each field.

type CaveConfig struct {
	// Width and Height are the level's size in cells, from 3 to MaxSide each, with Width*Height at most MaxCells. The outermost ring of cells is always Wall.
	Width, Height int
	// WallChance is the probability, in (0, 1), that an inner cell starts as Wall. The default is 0.45.
	WallChance float64
	// Steps is the number of smoothing passes. Zero takes the default of 5, so a cave always gets at least one pass.
	Steps int
	// WallAt turns a cell into Wall when at least this many of its 8 neighbours are Wall, cells outside the grid counting as Wall. It must be in [1, 8]. The default is 5.
	WallAt int
	// FloorAt turns a cell into Floor when at most this many of its 8 neighbours are Wall; a cell between FloorAt and WallAt keeps its value. It must be in [0, WallAt). When WallAt is 0 and FloorAt is 0, both take their defaults, 5 and 3; once WallAt is set, FloorAt is used as given, so 0 means only cells with no Wall neighbour become Floor.
	FloorAt int
	// MinRegion fills with Wall every separate cave region of fewer cells than this before regions are joined. The largest region is always kept. The default is 0, which keeps every region.
	MinRegion int
	// Join connects every remaining region to the largest with the shortest tunnel through rock. When false, every region but the largest is filled with Wall instead.
	Join bool
}

CaveConfig configures Cave. Zero fields take the defaults given on each field.

type Corridor struct {
	// From and To index the rooms the corridor joins in Dungeon.Rooms.
	From, To int
	// Path lists the corridor's cells in order from the center of room From to the center of room To.
	Path []Point
}

Corridor is a passage BSP carved between two rooms.

type DoorSocket struct {
	// Side is north, south, east or west.
	Side Side `yaml:"side"`
	// Offset is the 0-based cell position along Side from its left (north/south) or top (east/west) edge.
	Offset int `yaml:"offset"`
	// Width is the opening's span in cells along Side; 0 defaults to 1.
	Width int `yaml:"width,omitempty"`
	// Channel optionally restricts matching to sockets with the same Channel.
	Channel string `yaml:"channel,omitempty"`
}

DoorSocket is an opening on one side of a room template where another room can attach.

func (d DoorSocket) Cells(w, h int) []Point

Cells returns the room-local cell coordinates covered by d on a w-by-h room.

func (d DoorSocket) Matches(other DoorSocket) bool

Matches reports whether d can connect to other on an opposing room edge.

func (d DoorSocket) Span() int

Span returns the socket's width in cells, treating 0 as 1.

type Dungeon struct {
	// Grid holds Wall and Floor cells.
	Grid *Grid
	// Rooms lists every room in the order of the partition tree's leaves, left or top child first.
	Rooms []Rect
	// Corridors lists the spanning corridors, innermost partitions first, followed by the extra Loops corridors.
	Corridors []Corridor
}

Dungeon is the result of BSP.

func BSP(s *random.Stream, cfg BSPConfig) (*Dungeon, error)

BSP partitions a level with binary space partitioning, places one room in each leaf partition and joins sibling partitions with L-shaped corridors, so every Floor cell is reachable from every other.

All randomness comes from s, so the same stream state and cfg produce the same Dungeon. It returns an error wrapping ErrInvalidConfig when cfg cannot be satisfied.

type GraphConfig struct {
	// CriticalPath is the number of rooms on the main path from Start to Goal, inclusive.
	// The default is 5; when set it must be at least 2.
	CriticalPath int
	// Branches is the number of side rooms attached off the critical path and earlier branches.
	// Additional key rooms may be added if a lock tier has no available branch room. The default is 0.
	Branches int
	// BranchMaxDepth limits how far a branch chain may extend from the critical path.
	// The default is 2; when Branches > 0 it must be at least 1.
	BranchMaxDepth int
	// Loops is the desired number of extra cycle edges added within the same lock tier.
	// Edges are chosen between nodes of opposite spanning-tree parity so cycles have even length
	// and can be embedded on an orthogonal room grid. The default is 0.
	Loops int
	// Locks is the number of lock/key pairs placed along the critical path.
	// Each key is placed in a tier strictly before its lock so it is always reachable without passing the lock.
	// The default is 0; it must be at most CriticalPath - 1.
	Locks int
	// MaxDegree caps how many passages may connect to a single room.
	// The default is 4 (matching the four cardinal sides of a 2D room).
	MaxDegree int
}

GraphConfig configures GenerateGraph. Zero fields take the defaults given on each field.

type GraphEdge struct {
	// From and To are node IDs in LayoutGraph.Nodes.
	From int
	To   int
	// LockID is non-empty when this passage is locked and requires the key with matching KeyID.
	LockID string
	// Loop is true when this edge adds a cycle beyond the spanning tree.
	Loop bool
}

GraphEdge is an undirected passage between two rooms in a LayoutGraph.

type GraphNode struct {
	// ID is the node's 0-based index in LayoutGraph.Nodes.
	ID int
	// Role is start, goal, critical, branch or key.
	Role RoomRole
	// Depth is the shortest-path edge count from Start.
	Depth int
	// Tier is the lock-progression zone (0 is reachable without any keys, k requires keys 1..k).
	Tier int
	// Tag is the preferred room template tag for this node (such as "start", "goal" or "key").
	Tag string
	// KeyID is non-empty when this room holds the key for locked edges with the matching LockID.
	KeyID string
}

GraphNode is one room in a LayoutGraph.

type Grid struct {
	Width  int
	Height int
	Cells  []uint32
}

Grid is a Width by Height block of cell values stored row by row in Cells, so the cell at (x, y) is Cells[y*Width+x].

func Cave(s *random.Stream, cfg CaveConfig) (*Grid, error)

Cave grows a cave with a cellular automaton: inner cells start as Wall with probability WallChance, Steps smoothing passes apply the WallAt and FloorAt rule, and the resulting regions are then reduced to one connected cave, either by keeping only the largest or, with Join, by tunnelling every region into it.

All randomness comes from s, so the same stream state and cfg produce the same Grid. It returns an error wrapping ErrInvalidConfig for an unusable cfg, and ErrNoFloor when smoothing leaves no Floor cell.

func GridFromTilemap(m *tilemap.Tilemap, layer int, passable func(gid uint32) bool) *Grid

GridFromTilemap converts one layer of a tilemap (such as one loaded from a Tiled .tmj file with tilemap.LoadTiled) into a Grid of Wall and Floor cells. A cell is marked Floor when passable returns true for its GID (or when GID == 0 if passable is nil).

func NewGrid(width, height int) *Grid

NewGrid returns a width by height Grid with every cell set to Wall. Negative sizes are treated as 0.

func WFC(s *random.Stream, cfg WFCConfig) (*Grid, error)

WFC fills a Width by Height grid with the simple tiled model of wave function collapse: each step collapses a cell with the fewest remaining tiles, chosen at random among ties, to one tile picked by weight, then propagates the adjacency rules to its neighbours. A contradiction restarts the solve.

Unless cfg.AllowDisconnected is set, a path constraint keeps the walkable tiles connected while the wave collapses: cells that can no longer reach the walkable cells lose their walkable tiles, and a cell whose removal would split the walkable cells loses its non-walkable tiles.

Each Grid cell holds the index of its tile in cfg.Rules.Tiles. All randomness comes from s, so the same stream state and cfg produce the same Grid. It returns an error wrapping ErrInvalidConfig for an unusable cfg and ErrNoSolution when every attempt fails.

func (g *Grid) At(x, y int) uint32

At returns the value at (x, y), or Wall when (x, y) lies outside g.

func (g *Grid) Clone() *Grid

Clone returns a deep copy of g.

func (g *Grid) Connected(passable func(v uint32) bool) bool

Connected reports whether the cells that satisfy passable form at most one 4-connected region. A grid with no passable cell is connected.

func (g *Grid) Count(passable func(v uint32) bool) int

Count returns how many cells satisfy passable.

func (g *Grid) Equal(o *Grid) bool

Equal reports whether g and o have the same size and cell values.

func (g *Grid) Fill(r Rect, v uint32)

Fill writes v across r clipped to g.

func (g *Grid) In(x, y int) bool

In reports whether (x, y) lies inside g.

func (g *Grid) Paint(m *tilemap.Tilemap, layer, col, row int, gid func(v uint32) uint32)

Paint writes every cell of g into layer of m with its top left at (col, row), mapping each value to a tile GID with gid. Cells that fall outside the layer are skipped, and the layer's static cache is invalidated as tilemap.Tilemap.SetTile does.

func (g *Grid) Regions(passable func(v uint32) bool) [][]Point

Regions returns the 4-connected regions of cells that satisfy passable, largest first; regions of equal size keep the order of their first cell in row-major order, and the cells of each region are listed in row-major order.

func (g *Grid) Set(x, y int, v uint32)

Set writes v at (x, y); calls outside g are ignored.

func (g *Grid) String() string

String draws g as text, one line per row: '.' for Floor, '#' for Wall and, for any other value v, the letter 'a'+v-2 up to 'z' and '?' beyond. It is meant for tests and debugging.

type LayoutGraph struct {
	// Start is the entrance node ID (always 0).
	Start int
	// Goal is the exit/boss node ID.
	Goal int
	// CriticalPath lists the node IDs along the main route from Start to Goal.
	CriticalPath []int
	// Nodes holds every room node indexed by GraphNode.ID.
	Nodes []GraphNode
	// Edges holds every undirected passage between rooms.
	Edges []GraphEdge
	// Locks lists every lock/key pair in progression order.
	Locks []LockKey
}

LayoutGraph is the abstract room-and-passage topology of a dungeon.

func GenerateGraph(s *random.Stream, cfg GraphConfig) (*LayoutGraph, error)

GenerateGraph builds a deterministic dungeon LayoutGraph from s with a critical path from Start to Goal, optional side branches, lock/key progression pairs and same-tier cycles.

Every lock's key is placed in a progression tier strictly preceding its lock, and loop edges only connect rooms within the same tier, so every key is reachable from Start without passing its lock and no loop bypasses a lock.

func (g *LayoutGraph) Neighbors(nodeID int) []int

Neighbors returns the IDs of all nodes directly connected to nodeID by an edge in g, in edge order.

func (g *LayoutGraph) VerifyLocks() error

VerifyLocks checks that g's lock/key structure is sound: every lock has a valid key node, progressive traversal from Start collects every key without ever crossing a lock whose key has not yet been collected, every lock's key is reachable without crossing that lock, and Goal is reachable once keys are collected.

type LockKey struct {
	// ID matches GraphNode.KeyID and GraphEdge.LockID.
	ID string
	// KeyNode is the ID of the node holding this key.
	KeyNode int
	// EdgeIndex is the index into LayoutGraph.Edges of the locked passage.
	EdgeIndex int
}

LockKey records a lock/key pair in progression order.

type Neighbor struct {
	// Left is the tile on the left of a horizontal pair.
	Left string `yaml:"left,omitempty"`
	// Right is the tile on the right of a horizontal pair.
	Right string `yaml:"right,omitempty"`
	// Up is the tile on top of a vertical pair.
	Up string `yaml:"up,omitempty"`
	// Down is the tile below in a vertical pair.
	Down string `yaml:"down,omitempty"`
}

Neighbor allows one ordered pair of adjacent tiles: either Left and Right for a horizontal pair or Up and Down for a vertical pair, never both.

type PlaceConfig struct {
	// Mode selects PlacementStitch (default) or PlacementGrid.
	Mode PlacementMode
	// GridCols and GridRows set the coarse grid size in PlacementGrid mode.
	// When both are 0, a square grid large enough for the graph is chosen automatically.
	GridCols int
	GridRows int
	// Attempts is the deterministic retry budget before returning ErrNoLayout. The default is 50.
	Attempts int
	// Padding adds this many Wall cells around the stitched bounding box in Grid. The default is 0.
	Padding int
	// ResolveGrid optionally loads the tile Grid for a RoomTemplate with Source set.
	// When nil, Source-only templates stamp a default walled floor footprint of Width by Height.
	ResolveGrid func(t *RoomTemplate) (*Grid, error)
	// Passable defines which cell values count as walkable for connectivity verification.
	// When nil, IsFloor is used (or non-Wall when a template uses custom tile letters 'a'..'z').
	Passable func(v uint32) bool
}

PlaceConfig configures PlaceRooms. Zero fields take the defaults given on each field.

type PlacedDoor struct {
	// FromRoom and ToRoom are NodeIDs of the connected rooms.
	FromRoom int
	ToRoom   int
	// FromSide is the side of FromRoom where the doorway opens; ToSide is its opposite on ToRoom.
	FromSide Side
	ToSide   Side
	// Cells lists the doorway's Grid cells across both rooms' shared boundary.
	Cells []Point
	// LockID is non-empty when this doorway is locked.
	LockID string
	// Channel is the matched DoorSocket.Channel.
	Channel string
}

PlacedDoor is one stitched connection between two PlacedRooms.

type PlacedRoom struct {
	// NodeID is the room's node ID in RoomLevel.Graph.
	NodeID int
	// TemplateID is the ID of the RoomTemplate chosen for this room.
	TemplateID string
	// Source is the RoomTemplate.Source path (.tmj or scene) when the template references an external file.
	Source string
	// Bounds is the room's cell rectangle inside RoomLevel.Grid.
	Bounds Rect
	// GridSlot is the room's coarse (col, row) slot in PlacementGrid mode; zero in PlacementStitch mode.
	GridSlot Point
	// Rotation is the clockwise rotation applied to the template in degrees (0, 90, 180 or 270).
	Rotation int
	// Tags is a copy of the chosen template's tags.
	Tags []string
	// Role is the graph node's role (start, goal, critical, branch or key).
	Role RoomRole
	// KeyID is non-empty when this room holds the key for the matching locked door.
	KeyID string
}

PlacedRoom is one room template instantiated in a RoomLevel.

type PlacementMode string

PlacementMode selects how rooms are arranged in 2D space.

const (
	// PlacementStitch places variable-sized room templates by aligning matching door sockets without overlap.
	PlacementStitch PlacementMode = "stitch"
	// PlacementGrid places uniform-sized room templates on a Spelunky-style coarse grid of room slots.
	PlacementGrid PlacementMode = "grid"
)
type Point struct {
	X, Y int
}

Point is a cell position: X is the column and Y the row, both from 0 at the top left.

type Rect struct {
	X, Y, W, H int
}

Rect is an axis-aligned block of cells covering columns [X, X+W) and rows [Y, Y+H).

func (r Rect) Center() Point

Center returns the cell at the middle of r, rounded toward its top left.

func (r Rect) Contains(p Point) bool

Contains reports whether p lies inside r.

type RoomLevel struct {
	// Grid holds the stamped level tiles; Connected(passable) always holds.
	Grid *Grid
	// Rooms lists each placed room, indexed by NodeID.
	Rooms []PlacedRoom
	// Doors lists every stitched doorway corresponding to Graph.Edges.
	Doors []PlacedDoor
	// Graph is the dungeon layout graph realized by Rooms and Doors.
	Graph *LayoutGraph
}

RoomLevel is the result of GenerateRooms or PlaceRooms.

func GenerateRooms(s *random.Stream, cfg RoomsConfig) (*RoomLevel, error)

GenerateRooms generates a dungeon layout graph and places hand-made room templates onto a Grid, retrying deterministically from s up to cfg.Attempts times.

In PlacementStitch mode, rooms of arbitrary sizes are stitched by matching door sockets without overlap and same-tier loops are closed where aligned sockets meet. In PlacementGrid mode (Spelunky-style), uniform-sized rooms are laid out on a coarse grid of room slots so critical path, branches, lock/key tiers and loops align naturally.

func PlaceRooms(s *random.Stream, graph *LayoutGraph, templates *RoomTemplates, cfg PlaceConfig) (*RoomLevel, error)

PlaceRooms places an existing LayoutGraph using templates according to cfg, retrying deterministically from s up to cfg.Attempts times.

type RoomRole string

RoomRole identifies a node's structural role in a dungeon LayoutGraph.

const (
	// RoleStart is the entrance room where the player begins.
	RoleStart RoomRole = "start"
	// RoleGoal is the exit or boss room at the end of the critical path.
	RoleGoal RoomRole = "goal"
	// RoleCritical is an interior room along the critical path from Start to Goal.
	RoleCritical RoomRole = "critical"
	// RoleBranch is an optional side room off the critical path.
	RoleBranch RoomRole = "branch"
	// RoleKey is a room holding a key that unlocks a locked passage later in the dungeon.
	RoleKey RoomRole = "key"
)
type RoomTemplate struct {
	// ID uniquely identifies the template within its RoomTemplates set.
	ID string `yaml:"id"`
	// Weight is the template's relative selection frequency; 0 defaults to 1. Negative, NaN and infinite values are refused.
	Weight float64 `yaml:"weight,omitempty"`
	// Tags classify the room for graph roles or game logic (such as "start", "goal", "key", "combat", "shop").
	Tags []string `yaml:"tags,omitempty"`
	// Width and Height are the room's dimensions in cells. Required when Source is set; optional when Tiles is set (and must match Tiles if provided).
	Width  int `yaml:"width,omitempty"`
	Height int `yaml:"height,omitempty"`
	// Source names an external .tmj tilemap or scene file that holds this room's tiles/entities. Mutually exclusive with Tiles.
	Source string `yaml:"source,omitempty"`
	// AllowRotate permits the placer to rotate this template in 90-degree increments.
	AllowRotate bool `yaml:"allowRotate,omitempty"`
	// Doors lists the room's door sockets.
	Doors []DoorSocket `yaml:"doors"`
	// Tiles holds an inline ASCII tile grid, one string per row: '#' is Wall, '.' is Floor, and 'a'..'z' map to values 2..27. Mutually exclusive with Source.
	Tiles []string `yaml:"tiles,omitempty"`
}

RoomTemplate describes one hand-made room: either an inline tile grid or a reference to an external .tmj or scene file, together with door sockets, tags and relative weight.

func (t *RoomTemplate) EffectiveWeight() float64

EffectiveWeight returns t.Weight, or 1 when Weight is 0.

func (t *RoomTemplate) HasTag(tag string) bool

HasTag reports whether t carries tag.

func (t *RoomTemplate) Size() (w, h int)

Size returns the template's width and height in cells.

func (t *RoomTemplate) ToGrid() (*Grid, error)

ToGrid decodes t's inline Tiles into a Grid, or synthesizes a walled floor footprint for a Source-only template.

type RoomTemplates struct {
	// Version is the schema version; it must equal RoomTemplatesVersion.
	Version int `yaml:"version"`
	// Rooms lists the room templates in deterministic order.
	Rooms []RoomTemplate `yaml:"rooms"`
}

RoomTemplates is a versioned YAML collection of hand-made room templates for dungeon generation.

func ParseRoomTemplates(data []byte) (*RoomTemplates, error)

ParseRoomTemplates decodes and validates a YAML room template set. Unknown fields and trailing YAML documents are rejected.

func (rt *RoomTemplates) ByID(id string) *RoomTemplate

ByID returns the template with the given ID, or nil if not found.

func (rt *RoomTemplates) Validate() error

Validate checks rt against the version 1 schema: version, non-empty rooms, unique IDs, valid finite non-negative weights whose sum is finite, valid dimensions, mutually exclusive Tiles or Source, non-overlapping in-bounds door sockets, and valid inline tile characters.

type RoomsConfig struct {
	// Templates is the room template set to draw from. It must be valid.
	Templates *RoomTemplates
	// Graph configures the layout graph (critical path, branches, loops, locks).
	Graph GraphConfig
	// Mode selects PlacementStitch (default) or PlacementGrid.
	Mode PlacementMode
	// GridCols and GridRows set the coarse grid size in PlacementGrid mode.
	// When both are 0, a grid large enough for the graph is chosen automatically.
	GridCols int
	GridRows int
	// Attempts is the deterministic retry budget before returning ErrNoLayout. The default is 50.
	Attempts int
	// Padding adds this many Wall cells around the stitched bounding box in Grid. The default is 0.
	Padding int
	// ResolveGrid optionally loads the tile Grid for a RoomTemplate with Source set.
	ResolveGrid func(t *RoomTemplate) (*Grid, error)
	// Passable defines which cell values count as walkable for connectivity verification.
	Passable func(v uint32) bool
}

RoomsConfig configures GenerateRooms. Zero fields take the defaults given on each field.

type Rules struct {
	// Version is the schema version; it must equal RulesVersion.
	Version int `yaml:"version"`
	// Tiles lists the tiles. WFC writes a tile's index in this list into each Grid cell.
	Tiles []TileRule `yaml:"tiles"`
	// Neighbors lists the allowed adjacent pairs.
	Neighbors []Neighbor `yaml:"neighbors"`
}

Rules is a wave function collapse rule set: the tiles a level may use and which tiles may sit next to each other. It is written by hand as a YAML file, for example:

version: 1
tiles:
  - name: floor
    weight: 4
    walkable: true
  - name: wall
    weight: 1
neighbors:
  - {left: floor, right: floor}
  - {left: floor, right: wall}
  - {up: floor, down: floor}

Each neighbor entry allows one ordered pair: Left directly left of Right, or Up directly above Down. A pair that is not listed is forbidden, so a symmetric rule lists both orders.

func ParseRules(data []byte) (*Rules, error)

ParseRules decodes and validates a YAML rule set. Unknown fields and trailing YAML documents are rejected.

func (r *Rules) Index(name string) int

Index returns the index of the tile named name, or -1 when r has no such tile.

func (r *Rules) Validate() error

Validate checks r against the version 1 schema: the version, at least one tile, unique non-empty names, positive finite weights whose sum is finite, and neighbor entries that name known tiles as exactly one horizontal or vertical pair, each listed once.

func (r *Rules) Walkable(v uint32) bool

Walkable reports whether the tile at index v is walkable. It is the passable function for grids made by WFC with r; indexes outside r are not walkable.

type Side string

Side is one of the four cardinal edges of a room template.

const (
	// SideNorth is the top edge (y = 0) of a room.
	SideNorth Side = "north"
	// SideSouth is the bottom edge (y = Height-1) of a room.
	SideSouth Side = "south"
	// SideEast is the right edge (x = Width-1) of a room.
	SideEast Side = "east"
	// SideWest is the left edge (x = 0) of a room.
	SideWest Side = "west"
)
func (s Side) Delta() Point

Delta returns the unit cell step pointing outward from s.

func (s Side) Opposite() Side

Opposite returns the cardinal side facing s, or empty for an invalid side.

func (s Side) RotateCW() Side

RotateCW returns s rotated clockwise by 90 degrees.

func (s Side) Valid() bool

Valid reports whether s is one of SideNorth, SideSouth, SideEast or SideWest.

type TileRule struct {
	// Name identifies the tile in Neighbors; it must be non-empty and unique.
	Name string `yaml:"name"`
	// Weight is the tile's relative frequency when a cell collapses; it must be positive and finite.
	Weight float64 `yaml:"weight"`
	// Walkable marks the tile as passable for the connectivity check.
	Walkable bool `yaml:"walkable,omitempty"`
}

TileRule is one tile of a Rules set.

type WFCConfig struct {
	// Width and Height are the level's size in cells, from 1 to MaxSide each, with Width*Height at most MaxWFCCells.
	Width, Height int
	// Rules is the tile set and its adjacency rules. It must be valid.
	Rules *Rules
	// Attempts is how many times WFC restarts after a contradiction before returning ErrNoSolution. The default is 20.
	Attempts int
	// AllowDisconnected turns off the connectivity constraint, so walkable tiles may form several regions or none. By default, whenever Rules has a walkable tile, every level WFC returns has at least one walkable cell and all of its walkable cells form one 4-connected region.
	AllowDisconnected bool
}

WFCConfig configures WFC. Zero fields take the defaults given on each field.