castrum

package module
v0.4.0 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: 21 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.

README

castrum

Castrum is an ECS framework for building 2D games in Go. Its built on Ebitengine which provides rendering, input, audio and window management.

Documentation

Status

Castrum is pre-1.0 and should be treated as unstable. Migration notes will be provided between versions to assist in seamless upgrades and the goal will be to minimise breaking changes as much as possible.

The name

A castrum (Latin) was a Roman fortified camp: a garrison built to a standard layout from local materials, quickly, wherever the legions needed to hold ground. The name fits an engine that aims to be the standard-built base your game stands on - small, planned, and hard to knock over.

How this is made

Castrum is developed in Go with an AI-assisted workflow. In my own development, I use AI mainly for implementation and planning, and am reducing its use for documentation and whole-feature implementation. Contributors may use AI more broadly, including for prose and documentation, provided they follow the disclosure and review expectations in CONTRIBUTING.md.

Contributing

See the CONTRIBUTING.md file for guidelines on how to contribute to Castrum, including reporting issues, suggesting features, and submitting pull requests.

We welcome contributions from the community, whether it's fixing bugs, adding new features, improving documentation, or providing examples. Please follow the contribution guidelines to ensure a smooth and productive collaboration.

If you are new to Castrum or open-source contributions in general, consider starting with issues labeled as "good first issue" or "help wanted" to get familiar with the codebase and contribution process.

Thank you for considering contributing to Castrum! Your efforts help make the engine better for everyone in the community.

Documentation

Overview

Package castrum assembles a game world and runs its systems through a platform-specific runner.

Use New to construct a Game, then start it with the runner's Run.

Index

Constants

View Source
const (
	// TransformKey identifies [core.Transform] in save data.
	TransformKey = "core.Transform"
	// ColliderKey identifies [collision.Collider] in save data.
	ColliderKey = "collision.Collider"
	// SpriteKey identifies [sprite.Sprite] in save data.
	SpriteKey = "sprite.Sprite"
	// TextKey identifies [sprite.Text] in save data.
	TextKey = "sprite.Text"
	// PrimitiveKey identifies [sprite.Primitive] in save data.
	PrimitiveKey = "sprite.Primitive"
	// AnimatorKey identifies [animation.Animator] in save data.
	AnimatorKey = "animation.Animator"
)

Save keys identify engine components on disk. Changing a key breaks existing save files.

View Source
const (
	// TextureAssetKey identifies [asset.TextureData] in asset declarations.
	TextureAssetKey = "asset.TextureData"
	// FontAssetKey identifies [asset.FontData] in asset declarations.
	FontAssetKey = "asset.FontData"
	// SheetAssetKey identifies [asset.Sheet] in asset declarations.
	SheetAssetKey = "asset.Sheet"
	// AudioAssetKey identifies [asset.AudioData] in asset declarations.
	AudioAssetKey = "asset.AudioData"
)

Asset keys identify engine asset types in data files. Changing a key breaks existing data files.

Variables

This section is empty.

Functions

func NewAssetCodecs added in v0.4.0

func NewAssetCodecs() *asset.Codecs

NewAssetCodecs returns asset defaults with JSON codecs for audio.Preferences and input.Preferences. Preference validation and application remain explicit.

Custom codecs may be registered before or after passing the result to WithAssetCodecs, asset.NewLoader, or asset.NewSaver. Each call returns independent codecs.

func WithAssetCodecs added in v0.4.0

func WithAssetCodecs(codecs *asset.Codecs) option

WithAssetCodecs supplies codec configuration for the game's content loader. The loader reads the registrations on each call, so later changes affect that game. Nil selects NewAssetCodecs.

func WithBindings added in v0.0.3

func WithBindings(bindings input.Bindings) option

WithBindings configures the game's input bindings without changing its deadzone. Nil disables the action map.

func WithFilesystem added in v0.0.3

func WithFilesystem(filesystem fs.FS) option

WithFilesystem sets the filesystem used to resolve game assets. Built-in assets under "builtin/" remain available.

func WithFixedTPS

func WithFixedTPS(tps int) option

WithFixedTPS sets the fixed simulation rate in ticks per second. The default is 60. New returns an error if the rate is invalid.

func WithInputPreferences added in v0.4.0

func WithInputPreferences(p input.Preferences) option

WithInputPreferences configures the game's initial bindings and deadzone. New validates and copies the values; it does not retain a preference group. Later WithBindings options override only the bindings.

func WithMaxFrameTime

func WithMaxFrameTime(d time.Duration) option

WithMaxFrameTime sets the maximum elapsed time accepted for one frame. The default is 250 ms. New returns an error if d is not positive.

func WithMaxTicksPerFrame

func WithMaxTicksPerFrame(n int) option

WithMaxTicksPerFrame sets the maximum number of fixed ticks run in one display frame. The default is 5. New returns an error if n is not positive.

func WithResource added in v0.4.0

func WithResource[T any](value T) option

WithResource registers value as a world resource when New builds the game. A nil value, or one whose Validate() error fails, makes New panic. A type already registered by the engine or another option also makes New panic; use WithResourceOverride to replace it. Resources apply after the engine's own resources and before features, in option order.

func WithResourceOverride added in v0.4.0

func WithResourceOverride[T any](value T) option

WithResourceOverride replaces the resource or provider of type T when New builds the game. It makes New panic if T is not already registered at that point in option order, or if value is nil or fails Validate().

func WithResourceProvider added in v0.4.0

func WithResourceProvider[T any](ctor func(*core.World) (T, error)) option

WithResourceProvider registers ctor to build the world resource of type T when New builds the game. ctor runs on first use and may read other resources from the world. A type already registered makes New panic; use WithResourceOverride to replace it.

func WithScenes added in v0.3.0

func WithScenes() option

WithScenes enables the scene system and provides a scene Director resource. Passing it more than once, or together with [WithDefaultSystems], has no additional effect.

func WithState added in v0.4.0

func WithState[S comparable](machine *state.Machine[S]) option

WithState provides machine as a world resource and enables its system in core.PhasePreStartup and core.PhasePreFrame. Repeated options register machines in order. New returns an error for a nil machine or duplicate machine resource type.

func WithTitle

func WithTitle(title string) option

WithTitle sets the game's title.

Types

type Game

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

Game owns the world, configuration, and system schedules for a game. A runner drives the platform loop and supplies the window, draw surface, and input.

Call Game methods and access its world and context only from the thread that runs its systems.

func New

func New(opts ...option) *Game

New creates a Game with default options overridden by opts. It panics if the configuration is invalid or game initialization fails.

func (*Game) AddSystem

func (g *Game) AddSystem(phase core.Phase, name string, system core.SystemFunc, options ...SystemOption) error

AddSystem registers a named system in phase. By default it runs after previously registered user systems. Before and After change its position, and InGroup assigns it to a group.

AddSystem returns an error for an invalid phase, an empty name, an empty option value, an invalid option, multiple position or group options, a name already registered in the phase, a target not yet registered, or a startup phase once Game.Startup has begun.

Systems added during a phase run are eligible on the next run of that phase.

func (*Game) Advance

func (g *Game) Advance(elapsed time.Duration) error

Advance runs one frame followed by any fixed ticks due. Runners pass the time since the previous frame.

A frame runs core.PhasePreFrame, core.PhaseFrame, and core.PhasePostFrame with DeltaTime capped by WithMaxFrameTime. The gametime.Real resource records the original elapsed time. Each fixed tick runs core.PhasePreFixed, core.PhaseFixed, and core.PhasePostFixed. Advance discards the remaining accumulated time when it reaches the limit set by WithMaxTicksPerFrame.

Pause and time scale changes made during any frame phase affect the fixed ticks in the same call. Changes made during fixed ticks take effect on the next call.

If the scaled elapsed time or the resulting accumulated time cannot be represented as a time.Duration, Advance returns an error after the frame phases without changing the accumulator.

func (*Game) Alpha

func (g *Game) Alpha() float64

Alpha returns the fixed-loop remainder as a fraction of the tick interval for render interpolation.

func (*Game) BeginRun added in v0.4.0

func (g *Game) BeginRun() error

BeginRun marks the game as started by a runner and returns an error on subsequent calls.

func (*Game) Context

func (g *Game) Context() *core.Context

Context returns the live context. Runners use it when running their draw systems; game code receives it as a system argument.

func (*Game) Frame added in v0.4.0

func (g *Game) Frame() uint64

Frame returns the number of frames advanced by Game.Advance.

func (*Game) InsertResource added in v0.4.0

func (g *Game) InsertResource[T any](value T) error

InsertResource sets value as a world resource on an existing game. It returns an error without changing the world if T is already registered, or if value is nil or fails Validate(). Use Game.ReplaceResource to replace a resource.

func (*Game) MainCamera added in v0.0.3

func (g *Game) MainCamera() core.Entity

MainCamera returns the default camera created by New, positioned at the world origin with zoom 1. Set its core.Transform to move it. A user-spawned primary camera takes precedence.

func (*Game) Options

func (g *Game) Options() Options

Options returns a shallow copy of the game's configuration.

func (*Game) Pause added in v0.2.0

func (g *Game) Pause()

Pause suspends fixed updates and preserves the accumulated time.

No time is added toward fixed ticks while paused. Frame updates and audio continue, and Game.TimeScale is unchanged. See Game.Advance for when the change takes effect.

func (*Game) Paused added in v0.2.0

func (g *Game) Paused() bool

Paused reports whether fixed updates are stopped by Game.Pause.

func (*Game) Quit

func (g *Game) Quit()

Quit requests termination. The active runner observes it and stops.

func (*Game) Quitting

func (g *Game) Quitting() bool

Quitting reports whether Game.Quit was called.

func (*Game) ReplaceResource added in v0.4.0

func (g *Game) ReplaceResource[T any](value T) error

ReplaceResource replaces the resource of type T on an existing game. It returns an error without changing the world if T is not registered, or if value is nil or fails Validate().

func (*Game) Resume added in v0.2.0

func (g *Game) Resume()

Resume re-enables fixed updates after Game.Pause; see Game.Advance for timing.

func (*Game) SetGroupEnabled added in v0.3.0

func (g *Game) SetGroupEnabled(group string, enabled bool) error

SetGroupEnabled enables or disables a registered group across all phases. The state also applies to systems registered in the group later. It panics for an empty group name and returns an error if the group has no registered systems. A change affects subsequent systems, including later systems in the current phase.

func (*Game) SetTimeScale added in v0.2.0

func (g *Game) SetTimeScale(scale float64) error

SetTimeScale sets the multiplier for elapsed time added toward fixed ticks.

It returns an error and leaves the scale unchanged if scale is not positive and finite. Frame timing is unchanged. See Game.Advance for when the change takes effect.

func (*Game) Startup

func (g *Game) Startup() error

Startup runs core.PhasePreStartup, core.PhaseStartup, and core.PhasePostStartup once, after resolving eager resources. Runners call it before entering the platform loop. A second call returns an error, even if the first call failed.

func (*Game) TimeScale added in v0.2.0

func (g *Game) TimeScale() float64

TimeScale returns the multiplier applied to the time accumulated toward fixed ticks: 0.5 is half speed, 2 is fast forward. The default is 1.

func (*Game) World

func (g *Game) World() *core.World

World returns the game's core.World.

type Options

type Options struct {
	// Title is the title displayed by the runner.
	Title string

	// Filesystem supplies game asset files. Engine-shipped assets under
	// "builtin/" are available alongside it. If nil, game assets resolve from
	// the current working directory.
	Filesystem fs.FS

	// AssetCodecs configures the game's loader, which reads it on each call.
	// Nil selects [NewAssetCodecs].
	AssetCodecs *asset.Codecs

	// FixedTPS is the number of fixed simulation ticks per second.
	FixedTPS int

	// MaxFrameTime is the maximum elapsed time accepted for one frame.
	MaxFrameTime time.Duration

	// MaxTicksPerFrame is the maximum number of fixed ticks run in one display
	// frame.
	MaxTicksPerFrame int

	// InputBindings configures the engine-owned [input.ActionMap]. If nil, no
	// action map is created, but the runner's raw input snapshot remains
	// available.
	InputBindings input.Bindings
	// InputDeadzone is the map-wide gamepad axis threshold. Zero selects
	// [input.DefaultDeadzone].
	InputDeadzone float64
	// contains filtered or unexported fields
}

Options contains the configuration used to create a Game. Use New with option constructors to apply defaults and validate values.

Window and graphics settings belong to the runner.

func (Options) FixedDT

func (o Options) FixedDT() time.Duration

FixedDT returns the interval between fixed simulation ticks. New derives it from Options.FixedTPS.

type SystemOption added in v0.4.0

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

SystemOption configures a system registration passed to Game.AddSystem. Its zero value is invalid.

func After added in v0.4.0

func After(target string) SystemOption

After places a system immediately after a registered user system in the same phase.

func Before added in v0.4.0

func Before(target string) SystemOption

Before places a system immediately before a registered user system in the same phase.

func InGroup added in v0.4.0

func InGroup(group string) SystemOption

InGroup assigns a system to a named group controlled by Game.SetGroupEnabled. A new group starts enabled.

Directories

Path Synopsis
Package animation provides state-based sprite animation and playback signals.
Package animation provides state-based sprite animation and playback signals.
Package asset loads and saves typed data using format-specific codecs.
Package asset loads and saves typed data using format-specific codecs.
Package audio provides backend-independent playback.
Package audio provides backend-independent playback.
Package builtin provides engine-shipped assets, currently the Go Regular font.
Package builtin provides engine-shipped assets, currently the Go Regular font.
Package collision detects overlaps between entity colliders and records them in Contacts.
Package collision detects overlaps between entity colliders and records them in Contacts.
Package core provides World-owned entities and resources, Query iteration over components, and the [System] and Context contracts for updating a game.
Package core provides World-owned entities and resources, Query iteration over components, and the [System] and Context contracts for updating a game.
genquery command
Command genquery generates typed query rows and queries for arities 1 through the maximum selected with -max.
Command genquery generates typed query rows and queries for arities 1 through the maximum selected with -max.
Package debug provides the world-owned Panel used to show status readouts, recent messages, and built-in frame and tick rates in the development overlay.
Package debug provides the world-owned Panel used to show status readouts, recent messages, and built-in frame and tick rates in the development overlay.
Package ebitrun provides the default Ebitengine-backed Runner for castrum.
Package ebitrun provides the default Ebitengine-backed Runner for castrum.
examples
audio
Package audioassets embeds the music loops and stings shared by the audio examples.
Package audioassets embeds the music loops and stings shared by the audio examples.
Package gametime is the home of the engine's time work: the fixed loop's state as the Simulation resource and countdowns as Timer components.
Package gametime is the home of the engine's time work: the fixed loop's state as the Simulation resource and countdowns as Timer components.
Package geom provides Vector2 and the shapes Circle, Rect, and Segment for spatial calculations, along with Lerp and easing curves for interpolation.
Package geom provides Vector2 and the shapes Circle, Rect, and Segment for spatial calculations, along with Lerp and easing curves for interpolation.
Package input provides backend-independent keyboard, mouse, and gamepad types.
Package input provides backend-independent keyboard, mouse, and gamepad types.
internal
ecs
Package ecs stores entities in archetypes grouped by component type sets.
Package ecs stores entities in archetypes grouped by component type sets.
runtime
Package runtime provides ordered execution of systems for a core phase.
Package runtime provides ordered execution of systems for a core phase.
spatial
Package spatial provides a uniform grid for broad-phase spatial queries.
Package spatial provides a uniform grid for broad-phase spatial queries.
Package render defines camera state and collects sprites into ordered DrawList values for a renderer to draw.
Package render defines camera state and collects sprites into ordered DrawList values for a renderer to draw.
Package scene builds and runs scenes for the Castrum engine.
Package scene builds and runs scenes for the Castrum engine.
Package serialization maps stable keys in JSON data to game component and resource types.
Package serialization maps stable keys in JSON data to game component and resource types.
Package settings provides typed groups of player preferences.
Package settings provides typed groups of player preferences.
Package signal provides typed, pull-based broadcasts for systems.
Package signal provides typed, pull-based broadcasts for systems.
Package sprite defines the visual components: one component per visual concept - Sprite for textures and sheet regions, Text for text, and Primitive for geometry.
Package sprite defines the visual components: one component per visual concept - Sprite for textures and sheet regions, Text for text, and Primitive for geometry.
Package spritesheet builds asset.Sheet region maps from texture bounds.
Package spritesheet builds asset.Sheet region maps from texture bounds.
Package state provides generic state machines whose transitions are driven by scheduled system updates.
Package state provides generic state machines whose transitions are driven by scheduled system updates.
Package tween provides caller-advanced Tween playheads for duration-based transitions.
Package tween provides caller-advanced Tween playheads for duration-based transitions.

Jump to

Keyboard shortcuts

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