spawn

package
v0.4.0-rc.1 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: 12 Imported by: 0 modules, 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 spawn is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package spawn schedules deterministic enemy spawn events from versioned YAML. A document defines named spawn points and paths, timed, sequential or player-called waves with groups and reward hooks, and keyframed curves for endless and survivors-like modes. A Director advances elapsed time without creating game entities itself.

Index

Examples

Constants

View Source
const CurrentVersion = 1

CurrentVersion is the YAML spawn document version.

View Source
const SchemaURL = "https://nsgo.games/schemas/spawn.v1.json"

SchemaURL is where the JSON Schema of version 1 spawn schedule files (*.spawn.yaml) is published.

Variables

This section is empty.

Functions

func Validate

func Validate(d *Document) error

Validate checks version, maxLive, points, paths, waves, groups, curves, keyframes, and spawnAt specs.

Types

type ClearMode

type ClearMode string

ClearMode determines how a wave starts and when it counts as cleared.

const (
	// ClearTimed starts the wave at elapsed run time At (default when Clear is empty).
	ClearTimed ClearMode = "timed"
	// ClearAllDead starts the wave At seconds after the preceding wave clears, and clears once every enemy it spawned is dead.
	ClearAllDead ClearMode = "allDead"
	// ClearCalled waits for Director.CallWave to start the wave, and clears once every enemy it spawned is dead.
	ClearCalled ClearMode = "called"
)

type Curve

type Curve struct {
	// Name optionally identifies the curve.
	Name string `yaml:"name,omitempty"`
	// MaxLive optionally overrides Document.MaxLive for this curve when keyframes do not set MaxLive.
	MaxLive int `yaml:"maxLive,omitempty" schema:"minimum=0"`
	// Budgets optionally caps the tracked live count per enemy kind for this curve.
	Budgets map[string]int `yaml:"budgets,omitempty"`
	// RingRadius places spawns this far beyond the view rectangle when SpawnAt is omitted.
	RingRadius float64 `yaml:"ringRadius,omitempty" schema:"minimum=0"`
	// SpawnAt overrides the placement geometry for this curve; when omitted, a ring around target with RingRadius is used.
	SpawnAt *SpawnAt `yaml:"spawnAt,omitempty"`
	// Keyframes define the curve's spawn rate, enemy mix weights, and optional live cap in strictly increasing At order.
	Keyframes []Keyframe `yaml:"keyframes" schema:"required,minItems=1"`
}

Curve is a time-based spawn stream driven by keyframed spawn rates, enemy mixes, and optional live-cap curves.

type Director

type Director struct {
	// contains filtered or unexported fields
}

Director advances waves and curves and emits deterministic Spawn events without creating game entities.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/random"
	"github.com/nsgo-dev/game/pkg/spawn"
)

func main() {
	doc, err := spawn.Parse([]byte(`version: 1
maxLive: 3
waves:
  - at: 0
    groups:
      - enemy: bat
        count: 2
        interval: 1
        ringRadius: 2
  - at: 2
    groups:
      - enemy: slime
        count: 2
        ringRadius: 1
`))
	if err != nil {
		fmt.Println(err)
		return
	}
	dir := spawn.NewDirector(doc, random.New(7))
	view := spawn.Rect{Min: spawn.Vec2{X: -10, Y: -10}, Max: spawn.Vec2{X: 10, Y: 10}}

	step := func(dt float64) {
		var names []string
		outside := true
		for _, s := range dir.Step(dt, view, spawn.Vec2{}) {
			names = append(names, fmt.Sprintf("%s@wave%d", s.Enemy, s.Wave))
			outside = outside && !view.Contains(s.Position)
		}
		fmt.Printf("t=%.1f %v live=%d outside=%v\n", dir.State().Elapsed, names, dir.Live(), outside)
	}
	step(0.5)
	step(1)
	// The second slime waits: maxLive is 3.
	step(1)
	// Two enemies die, which frees room under the cap.
	dir.SetLive(1)
	step(0.5)
}
Output:
t=0.5 [bat@wave0] live=1 outside=true
t=1.5 [bat@wave0] live=2 outside=true
t=2.5 [slime@wave1] live=3 outside=true
t=3.0 [slime@wave1] live=2 outside=true

func NewDirector

func NewDirector(doc *Document, stream *random.Stream) *Director

NewDirector returns a deterministic director for a deep copy of doc and stream. It panics if doc or stream is nil.

func (*Director) AllWavesCleared

func (d *Director) AllWavesCleared() bool

AllWavesCleared reports whether every wave in Document.Waves has cleared.

func (*Director) AppendRewards

func (d *Director) AppendRewards(dst []WaveReward) []WaveReward

AppendRewards appends pending WaveRewards to dst, clears the pending queue, and returns the extended slice.

func (*Director) AppendStep

func (d *Director) AppendStep(dst []Spawn, dt float64, view Rect, target Vec2) []Spawn

AppendStep is Step writing into dst instead of a new slice, and returns the extended slice, so a game can reuse one buffer and allocate nothing while it emits spawns. Pass nil to start a new slice, as Step does.

func (*Director) CallWave

func (d *Director) CallWave() (int, bool)

CallWave starts the next uncalled ClearCalled wave and returns its document index and true, or (-1, false) when no uncalled ClearCalled wave remains.

func (*Director) CurveMaxLive

func (d *Director) CurveMaxLive(curve int) int

CurveMaxLive returns the effective live cap applied to curve at the current elapsed time: SetMaxLive when overridden at runtime, else the curve's keyframed or curve-level cap, else Document.MaxLive.

func (*Director) DrainRewards

func (d *Director) DrainRewards() []WaveReward

DrainRewards returns and clears every pending WaveReward emitted by cleared waves.

func (*Director) Live

func (d *Director) Live() int

Live returns the number of live entities the cap counts: the last SetLive value plus every spawn Step has emitted since.

func (*Director) LiveKind

func (d *Director) LiveKind(enemy string) int

LiveKind returns the tracked live count for enemy used against Curve.Budgets.

func (*Director) MaxLive

func (d *Director) MaxLive() int

MaxLive returns the live cap a step applies: the SetMaxLive value when one is set, else the document's maxLive.

func (*Director) MaxPerStep

func (d *Director) MaxPerStep() int

MaxPerStep returns the per-step spawn cap, 0 when one step may emit as many spawns as the live cap allows.

func (*Director) NextCalledWave

func (d *Director) NextCalledWave() int

NextCalledWave returns the index of the next uncalled ClearCalled wave, or -1 if none remain.

func (*Director) NextWaveIn

func (d *Director) NextWaveIn() (wave int, wait float64, ok bool)

NextWaveIn returns the next wave scheduled to start on time (a timed wave, a called wave with a start delay, or an allDead wave whose predecessor has cleared) and the seconds remaining until it starts.

func (*Director) SetLive

func (d *Director) SetLive(n int)

SetLive sets the live-entity count used by the cap, such as after enemies die. Negative values count as 0. Setting Live to 0 also clears tracked per-wave and per-kind live counts and settles cleared waves.

func (*Director) SetLiveKind

func (d *Director) SetLiveKind(enemy string, n int)

SetLiveKind sets the tracked live count for enemy used against Curve.Budgets. Negative values count as 0.

func (*Director) SetMaxLive

func (d *Director) SetMaxLive(n int)

SetMaxLive replaces the document's maxLive while the director runs, so a game can grow or shrink the live cap with difficulty, time or the number of players; 0 or less restores the document's value. Lowering it below Live emits nothing until enough enemies die, and the spawns the cap holds back stay due. Like MaxPerStep it is runtime configuration and is not part of State.

func (*Director) SetMaxPerStep

func (d *Director) SetMaxPerStep(n int)

SetMaxPerStep caps how many spawns one step emits, so a refill of the live cap spreads over several steps instead of arriving as one burst on the same ring at the same instant; 0 or less removes the cap. The spawns a step holds back stay due, so later steps emit them as room opens. The cap is runtime state, like the director's other settings, and is not part of State.

func (*Director) SetState

func (d *Director) SetState(s State)

SetState restores a director snapshot taken from a director of the same document.

func (*Director) SetWaveLive

func (d *Director) SetWaveLive(wave, n int)

SetWaveLive sets the tracked live count of enemies from wave and settles it if cleared. Negative values count as 0.

func (*Director) SkipDue

func (d *Director) SkipDue() int

SkipDue marks every spawn that is due at the current elapsed time as done, including the spawns the cap or the per-step limit held back, across both waves and curves, so a director that kept stepping while the game wanted no spawns does not release its whole backlog later. It returns how many spawns it dropped. Spawns that come due afterwards are emitted as usual.

func (*Director) Spawning

func (d *Director) Spawning() bool

Spawning reports whether any started or called wave still has enemies left to emit.

func (*Director) State

func (d *Director) State() State

State returns a replay-safe snapshot of director state.

func (*Director) Step

func (d *Director) Step(dt float64, view Rect, target Vec2) []Spawn

Step advances elapsed time by dt seconds and emits the spawns that are due, placed according to each group's or curve's SpawnAt (or RingPosition around target outside view). It never lets Live exceed MaxLive (or a curve's live cap), and emits at most MaxPerStep per step when set. A dt that is not positive and finite emits nothing. A game that steps every frame should call AppendStep with a reused buffer instead.

func (*Director) WaveActive

func (d *Director) WaveActive(wave int) bool

WaveActive reports whether wave has started and has not yet cleared.

func (*Director) WaveCleared

func (d *Director) WaveCleared(wave int) bool

WaveCleared reports whether wave has cleared.

func (*Director) WaveLive

func (d *Director) WaveLive(wave int) int

WaveLive returns the tracked live count of enemies from wave.

func (*Director) WaveSpawning

func (d *Director) WaveSpawning(wave int) bool

WaveSpawning reports whether wave has been started or called and still has enemies left to emit.

type Document

type Document struct {
	// Version is the schema version; it must equal CurrentVersion (1).
	Version int `yaml:"version" schema:"required"`
	// MaxLive is the default maximum number of live enemies allowed at once, 1 or more.
	MaxLive int `yaml:"maxLive" schema:"required,minimum=1"`
	// Points declares named 2D spawn points referenced by SpawnAt specs with kind "point".
	Points map[string]Vec2 `yaml:"points,omitempty"`
	// Paths declares named waypoint lists whose first point is used by SpawnAt specs with kind "path".
	Paths map[string][]Vec2 `yaml:"paths,omitempty"`
	// Waves are timed, sequential (allDead), or player-called enemy waves.
	Waves []Wave `yaml:"waves,omitempty"`
	// Curves are time-based spawn streams for endless and survivors-like modes.
	Curves []Curve `yaml:"curves,omitempty"`
}

Document defines named spawn points and paths, waves, endless curves, and the default live-enemy cap.

func LoadFS

func LoadFS(fsys fs.FS, name string) (*Document, error)

LoadFS reads, decodes, and validates the spawn file at name in fsys. Errors are *loaderr.Error values naming name.

func Parse

func Parse(data []byte) (*Document, error)

Parse decodes and validates one versioned spawn document. It refuses unknown fields and a second YAML document, and returns a *loaderr.Error.

func (*Document) Encode

func (d *Document) Encode() ([]byte, error)

Encode validates and writes a deterministic spawn document.

type Group

type Group struct {
	// Enemy is the enemy kind name emitted in Spawn.Enemy.
	Enemy string `yaml:"enemy" schema:"required"`
	// Count is how many enemies the group spawns, 1 or more.
	Count int `yaml:"count" schema:"required,minimum=1"`
	// Delay is the seconds from the wave's start to the group's first spawn, 0 or more.
	Delay float64 `yaml:"delay,omitempty" schema:"minimum=0"`
	// Interval is the seconds between consecutive spawns, 0 or more; 0 spawns all Count at once.
	Interval float64 `yaml:"interval,omitempty" schema:"minimum=0"`
	// RingRadius places spawns this far beyond the view rectangle when SpawnAt is omitted.
	RingRadius float64 `yaml:"ringRadius,omitempty" schema:"minimum=0"`
	// SpawnAt overrides the placement geometry for this group; when omitted, a ring around target with RingRadius is used.
	SpawnAt *SpawnAt `yaml:"spawnAt,omitempty"`
}

Group describes repeated enemy spawns: Count spawns of Enemy, starting Delay seconds after its wave starts and one more every Interval seconds (or all at once when Interval is 0), placed via SpawnAt or RingRadius beyond the view.

type Keyframe

type Keyframe struct {
	// At is the run time in seconds where this keyframe takes effect, 0 or more.
	At float64 `yaml:"at" schema:"minimum=0"`
	// Rate is the spawn rate in enemies per second at At, linearly interpolated between adjacent keyframes.
	Rate float64 `yaml:"rate" schema:"minimum=0"`
	// Mix maps each enemy kind to its non-negative selection weight at At, linearly interpolated between adjacent keyframes.
	Mix map[string]float64 `yaml:"mix" schema:"required"`
	// MaxLive optionally sets the live-enemy cap at At, linearly interpolated between keyframes that set it.
	MaxLive int `yaml:"maxLive,omitempty" schema:"minimum=0"`
}

Keyframe is one control point on a Curve at run time At seconds.

type Rect

type Rect struct {
	// Min is the minimum (top-left in 2D screen coordinates) corner.
	Min Vec2 `yaml:"min"`
	// Max is the maximum (bottom-right in 2D screen coordinates) corner.
	Max Vec2 `yaml:"max"`
}

Rect is an axis-aligned view or spawn rectangle.

func (Rect) Contains

func (r Rect) Contains(p Vec2) bool

Contains reports whether p lies inside r.

type Spawn

type Spawn struct {
	// Enemy is the spawned enemy kind name.
	Enemy string
	// Position is where to place the enemy.
	Position Vec2
	// Wave is the index of the wave in Document.Waves as written, or -1 for spawns emitted by a Curve.
	Wave int
	// Curve is the index of the curve in Document.Curves as written, or -1 for spawns emitted by a Wave.
	Curve int
	// SpawnPoint is the SpawnAt.Name (named point or path) when one was used, or empty otherwise.
	SpawnPoint string
}

Spawn is one emitted enemy event.

type SpawnAt

type SpawnAt struct {
	// Kind selects the placement geometry: "ring", "point", "path", or "rectEdge".
	Kind SpawnShape `yaml:"kind" schema:"required,enum=ring|point|path|rectEdge"`
	// Name references an entry in Document.Points (for kind "point") or Document.Paths (for kind "path").
	Name string `yaml:"name,omitempty"`
	// Point is an inline position for kind "point" when Name is omitted.
	Point *Vec2 `yaml:"point,omitempty"`
	// Step optionally shifts the k-th spawn of a group by (k * Step.X, k * Step.Y) for kind "point".
	Step *Vec2 `yaml:"step,omitempty"`
	// Rect is an explicit rectangle for kind "rectEdge"; when omitted, the view rectangle passed to Step is used.
	Rect *Rect `yaml:"rect,omitempty"`
	// Margin is the distance outside the view or Rect for kind "ring" or "rectEdge", 0 or more.
	Margin float64 `yaml:"margin,omitempty" schema:"minimum=0"`
	// Edge optionally restricts kind "rectEdge" to one side: "any" (default), "top", "bottom", "left", or "right".
	Edge string `yaml:"edge,omitempty" schema:"enum=any|top|bottom|left|right"`
}

SpawnAt describes where a wave group or curve places spawned enemies.

type SpawnShape

type SpawnShape string

SpawnShape selects the placement geometry of a SpawnAt specification.

const (
	// ShapeRing places spawns on a circle around the target outside the view rectangle by Margin.
	ShapeRing SpawnShape = "ring"
	// ShapePoint places spawns at a named point from Document.Points or an inline Point, optionally shifted by Step per spawn in a group.
	ShapePoint SpawnShape = "point"
	// ShapePath places spawns at the start (first point) of a named path from Document.Paths.
	ShapePath SpawnShape = "path"
	// ShapeRectEdge places spawns along the edge of Rect (or the view rectangle passed to Step when Rect is omitted) expanded by Margin.
	ShapeRectEdge SpawnShape = "rectEdge"
)

type State

type State struct {
	// Elapsed is the accumulated run time in seconds.
	Elapsed float64 `yaml:"elapsed"`
	// Next holds how many enemies each wave group has emitted so far.
	Next []int `yaml:"next"`
	// Live is the tracked total live-enemy count.
	Live int `yaml:"live"`
	// Random is the PRNG stream state.
	Random random.State `yaml:"random"`
	// WaveCalled records which waves have been called via CallWave.
	WaveCalled []bool `yaml:"waveCalled,omitempty"`
	// WaveStarted records which waves have started.
	WaveStarted []bool `yaml:"waveStarted,omitempty"`
	// WaveStart records the run time at which each wave started (or is scheduled to start).
	WaveStart []float64 `yaml:"waveStart,omitempty"`
	// WaveCleared records which waves have cleared.
	WaveCleared []bool `yaml:"waveCleared,omitempty"`
	// WaveClear records the run time at which each wave cleared.
	WaveClear []float64 `yaml:"waveClear,omitempty"`
	// WaveLive records the tracked live count per wave.
	WaveLive []int `yaml:"waveLive,omitempty"`
	// CurveEmitted records how many spawns each curve has emitted so far.
	CurveEmitted []int `yaml:"curveEmitted,omitempty"`
	// LiveByKind records the tracked live count per budgeted enemy kind.
	LiveByKind map[string]int `yaml:"liveByKind,omitempty"`
	// PendingRewards holds cleared-wave rewards not yet drained.
	PendingRewards []WaveReward `yaml:"pendingRewards,omitempty"`
}

State is a serializable director snapshot for saves and replays.

type Vec2

type Vec2 struct {
	// X is the horizontal coordinate.
	X float64 `yaml:"x"`
	// Y is the vertical coordinate.
	Y float64 `yaml:"y"`
}

Vec2 is a 2D position.

func RectEdgePosition

func RectEdgePosition(s *random.Stream, rect Rect, margin float64, edge string) Vec2

RectEdgePosition chooses a deterministic point on the perimeter of rect expanded by margin. edge restricts placement to "top" (Min.Y - margin), "bottom" (Max.Y + margin), "left" (Min.X - margin), or "right" (Max.X + margin); "" or "any" picks uniformly by perimeter length. A negative margin counts as 0. It draws one value from s.

func RingPosition

func RingPosition(s *random.Stream, target Vec2, view Rect, margin float64) Vec2

RingPosition chooses a deterministic point on a circle around target that lies outside view: its radius is the distance from target to view's farthest corner plus margin, so a margin above 0 keeps the point off view's edge. A negative margin counts as 0. It draws one value from s.

type Wave

type Wave struct {
	// Name optionally identifies the wave for UI or logging.
	Name string `yaml:"name,omitempty"`
	// At is when the wave starts in seconds: elapsed run time for timed waves, or delay after the previous wave clears (or after CallWave) for allDead and called waves.
	At float64 `yaml:"at,omitempty" schema:"minimum=0"`
	// Clear selects the wave's start and clear condition: "" or "timed" (default), "allDead", or "called".
	Clear ClearMode `yaml:"clear,omitempty" schema:"enum=timed|allDead|called"`
	// Duration optionally sets the seconds after a timed wave starts before it counts as cleared (0 clears once all its spawned enemies are dead).
	Duration float64 `yaml:"duration,omitempty" schema:"minimum=0"`
	// Reward is an optional hook name reported via Director.DrainRewards when the wave clears.
	Reward string `yaml:"reward,omitempty"`
	// Groups are the enemy groups this wave spawns.
	Groups []Group `yaml:"groups,omitempty"`
}

Wave schedules groups of enemies with an optional clear condition and reward hook name.

type WaveReward

type WaveReward struct {
	// Wave is the index of the cleared wave in Document.Waves as written.
	Wave int `yaml:"wave"`
	// Reward is the wave's Reward hook name.
	Reward string `yaml:"reward"`
}

WaveReward is emitted once when a wave with a non-empty Reward clears.

Jump to

Keyboard shortcuts

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