procgen

package
v0.4.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 14 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package procgen is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

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.

A Placement file places prefabs by rules: ParsePlacement reads a versioned *.placement.yaml whose steps sample named point sets over an area or inside shapes (grid, Poisson disk, shape), filter earlier sets (density with noise, distance to another set, subtraction of shapes), rotate, scale and jitter the points and pick prefabs from weighted lists, and Placement.Points returns bit-identical points for the same file and area on every machine and architecture.

Example
package main

import (
	"fmt"

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

func main() {
	fmt.Println(procgen.RoleStart)
}
Output:
start

Index

Examples

Constants

View Source
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.

View Source
const (
	// SamplerGrid places points on a regular lattice of cells over the area.
	SamplerGrid = "grid"
	// SamplerPoisson fills the area with points no closer than the step's minDistance to each other (Poisson disk sampling).
	SamplerPoisson = "poisson"
	// SamplerShape places count random points inside the union of the step's shapes, optionally no closer than minDistance to each other.
	SamplerShape = "shape"
)

Sampler names: a step with one of these as its sampler creates a point set.

View Source
const (
	// FilterDensity keeps each point with probability density, scaled by seeded noise when noiseFrequency is set.
	FilterDensity = "density"
	// FilterDistanceTo keeps the points whose nearest point in the set named by to lies between minDistance and maxDistance.
	FilterDistanceTo = "distanceTo"
	// FilterSubtract drops the points inside any of the step's shapes.
	FilterSubtract = "subtract"
)

Filter names: a step with one of these as its filter reads the point set of an earlier step named by input and keeps some of its points.

View Source
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.

View Source
const MaxSide = 1 << 16

MaxSide is the largest Width or Height any generator accepts.

View Source
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.

View Source
const PlacementVersion = 1

PlacementVersion is the placement file schema version this package reads and writes.

View Source
const RoomTemplatesVersion = 1

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

View Source
const RulesVersion = 1

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

Variables

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

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

View Source
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.

View Source
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.

View Source
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.

Functions

func EncodePlacement

func EncodePlacement(p *Placement) ([]byte, error)

EncodePlacement validates p and writes it as 2-space YAML with fields in a fixed order and steps in their given order, so ParsePlacement followed by EncodePlacement reproduces a file EncodePlacement wrote.

func EncodeRoomTemplates

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

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

func IsFloor(v uint32) bool

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

Types

type BSPConfig

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

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

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

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 (DoorSocket) Cells

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 (DoorSocket) Matches

func (d DoorSocket) Matches(other DoorSocket) bool

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

func (DoorSocket) Span

func (d DoorSocket) Span() int

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

type Dungeon

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

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

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

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

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

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

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

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

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

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 (*Grid) At

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

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

func (*Grid) Clone

func (g *Grid) Clone() *Grid

Clone returns a deep copy of g.

func (*Grid) Connected

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 (*Grid) Count

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

Count returns how many cells satisfy passable.

func (*Grid) Equal

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

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

func (*Grid) Fill

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

Fill writes v across r clipped to g.

func (*Grid) In

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

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

func (*Grid) Paint

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 (*Grid) Regions

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 (*Grid) Set

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

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

func (*Grid) String

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

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

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 (*LayoutGraph) Neighbors

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 (*LayoutGraph) VerifyLocks

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

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

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

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

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

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 Placement

type Placement struct {
	// Version is the schema version; it must equal PlacementVersion.
	Version int `yaml:"version"`
	// Seed seeds every step's random stream. Each step forks its own stream from Seed by its ID, so adding, removing or reordering steps leaves the points of the others unchanged.
	Seed uint64 `yaml:"seed"`
	// Steps lists the steps in the order Points runs them. A step may read only the sets of steps before it.
	Steps []PlacementStep `yaml:"steps"`
}

Placement is a procedural placement file, usually named *.placement.yaml: an ordered list of steps that each write a named point set, either by sampling an area or shapes or by filtering an earlier step's set, and optionally transform its points and name the prefabs to spawn at them, for example:

version: 1
seed: 7
steps:
  - id: scatter
    sampler: poisson
    minDistance: 2
  - id: trees
    filter: subtract
    input: scatter
    shapes:
      - circle: {x: 10, y: 10, radius: 4}
    rotation: [0, 360]
    prefab: tree

Points runs the steps over an area.

func ParsePlacement

func ParsePlacement(data []byte) (*Placement, error)

ParsePlacement decodes and validates a YAML placement file. Unknown fields and trailing YAML documents are rejected.

func (*Placement) Points

func (p *Placement) Points(width, height int) []PlacementPoint

Points runs p's steps over an area of width by height cells and returns the points of the steps that spawn (those with a prefab or a spawn list): the steps' points in step order, and each step's points ordered by Y and then X.

Every step samples from a random.Stream forked from Seed by the step's ID and draws the rest of its randomness from children of that stream forked by purpose (density, noise, transform, spawn), so the same file and area give the same points on every machine, and adding a transform or a spawn list to a step does not move its points. Grid and poisson steps sample the area; shape steps sample their shapes wherever they lie, so their points may fall outside the area. An area with no cells gives no grid or poisson points.

Points follows the steps' arithmetic without fused multiply-add, so a file gives bit-identical points on amd64 and arm64.

p must pass Validate, as every Placement ParsePlacement returns does; Points panics with Validate's error otherwise, since a step such as a poisson sampler without a minDistance would never finish.

func (*Placement) Validate

func (p *Placement) Validate() error

Validate checks p against the version 1 schema: the version, at least one step and one that spawns, unique non-empty step IDs, exactly one known sampler or filter per step with the fields it reads and no others, inputs that name earlier steps, finite numbers in range, well-formed shapes, and either a prefab or a weighted spawn list of named prefabs.

type PlacementCircle

type PlacementCircle struct {
	X      float64 `yaml:"x"`
	Y      float64 `yaml:"y"`
	Radius float64 `yaml:"radius"`
}

PlacementCircle is a disc of Radius centered on X, Y.

type PlacementMode

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 PlacementPoint

type PlacementPoint struct {
	// X and Y are the point's position in cells.
	X, Y float32
	// Rotation is the point's rotation in degrees; 0 unless a step set Rotation.
	Rotation float32
	// Scale is the point's uniform scale; 1 unless a step set Scale.
	Scale float32
	// ID identifies the point: the step's ID, a dash and the point's index within the step, such as "trees-3".
	ID string
	// Step is the ID of the step that produced the point.
	Step string
	// Prefab is the prefab to spawn at the point.
	Prefab string
}

PlacementPoint is one point a Placement step produced.

type PlacementShape

type PlacementShape struct {
	// Circle is a disc.
	Circle *PlacementCircle `yaml:"circle,omitempty,flow"`
	// Polygon lists at least three [x, y] vertices of a simple polygon, in either winding; a point is inside by the even-odd rule.
	Polygon [][2]float64 `yaml:"polygon,omitempty,flow"`
}

PlacementShape is a circle or a polygon in cell coordinates; exactly one of its fields is set.

type PlacementSpawn

type PlacementSpawn struct {
	// Prefab names the prefab; it must be non-empty.
	Prefab string `yaml:"prefab"`
	// Weight is the entry's relative chance, a positive number; 0 or absent means 1.
	Weight float64 `yaml:"weight,omitempty"`
}

PlacementSpawn is one entry of a step's weighted spawn list.

type PlacementStep

type PlacementStep struct {
	// ID names the step and the point set it writes; it must be non-empty and unique. It prefixes the IDs of the step's points and names the step's random stream.
	ID string `yaml:"id"`
	// Sampler selects how the step samples points: SamplerGrid, SamplerPoisson or SamplerShape.
	Sampler string `yaml:"sampler,omitempty"`
	// Filter selects how the step filters the set named by Input: FilterDensity, FilterDistanceTo or FilterSubtract.
	Filter string `yaml:"filter,omitempty"`
	// Input names the earlier step whose set a filter reads; filters only, required.
	Input string `yaml:"input,omitempty"`
	// To names the earlier step whose set FilterDistanceTo measures distances to; required there.
	To string `yaml:"to,omitempty"`
	// Spacing is the distance in cells between neighboring lattice points of a grid step, at least 1; 0 means 1. Grid only.
	Spacing int `yaml:"spacing,omitempty"`
	// Count is how many points to keep or place. A grid step keeps Count of its lattice points chosen at random (0 keeps all, and a Count above the lattice size keeps all); a shape step places Count points and requires it.
	Count int `yaml:"count,omitempty"`
	// MinDistance is a distance in cells: the minimum spacing between a poisson step's points (required, positive), an optional minimum spacing between a shape step's points, or the distance below which FilterDistanceTo drops a point.
	MinDistance float64 `yaml:"minDistance,omitempty"`
	// MaxDistance is the distance above which FilterDistanceTo drops a point; 0 means no limit. FilterDistanceTo needs MinDistance or MaxDistance.
	MaxDistance float64 `yaml:"maxDistance,omitempty"`
	// Shapes are the areas a shape step samples inside (their union) or a subtract filter removes points from; required by both.
	Shapes []PlacementShape `yaml:"shapes,omitempty"`
	// Density is the probability in (0, 1] that FilterDensity keeps a point; required there.
	Density float64 `yaml:"density,omitempty"`
	// NoiseFrequency, when positive, scales FilterDensity's probability at each point by seeded simplex noise sampled at the point times NoiseFrequency and mapped to [0, 1], so points thin out in patches instead of evenly.
	NoiseFrequency float64 `yaml:"noiseFrequency,omitempty"`
	// Rotation is a [min, max] range in degrees; each point of the step gets a rotation drawn uniformly from it. Any step.
	Rotation []float64 `yaml:"rotation,omitempty,flow"`
	// Scale is a [min, max] range of positive factors; each point of the step gets a scale drawn uniformly from it. Any step.
	Scale []float64 `yaml:"scale,omitempty,flow"`
	// Jitter moves each point of the step by a random offset inside a circle of this radius in cells. Any step.
	Jitter float64 `yaml:"jitter,omitempty"`
	// Prefab names the one prefab to spawn at each of the step's points. A step with Prefab or Spawn adds its points to Points' result; a step with neither only feeds later steps.
	Prefab string `yaml:"prefab,omitempty"`
	// Spawn is a weighted list of prefabs; each point spawns one of them, chosen at random by weight. It replaces Prefab when a step spawns more than one kind.
	Spawn []PlacementSpawn `yaml:"spawn,omitempty"`
}

PlacementStep is one step of a Placement. It has exactly one of Sampler and Filter; each field below names the samplers and filters that read it, and a field set on a step that does not read it is refused.

type Point

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

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 (Rect) Center

func (r Rect) Center() Point

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

func (Rect) Contains

func (r Rect) Contains(p Point) bool

Contains reports whether p lies inside r.

type RoomLevel

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

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

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

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

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 (*RoomTemplate) EffectiveWeight

func (t *RoomTemplate) EffectiveWeight() float64

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

func (*RoomTemplate) HasTag

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

HasTag reports whether t carries tag.

func (*RoomTemplate) Size

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

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

func (*RoomTemplate) ToGrid

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

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

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

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

func (*RoomTemplates) ByID

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

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

func (*RoomTemplates) Validate

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

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

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

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

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

func (*Rules) Index

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 (*Rules) Validate

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 (*Rules) Walkable

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

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 (Side) Delta

func (s Side) Delta() Point

Delta returns the unit cell step pointing outward from s.

func (Side) Opposite

func (s Side) Opposite() Side

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

func (Side) RotateCW

func (s Side) RotateCW() Side

RotateCW returns s rotated clockwise by 90 degrees.

func (Side) Valid

func (s Side) Valid() bool

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

type TileRule

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

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL