Skip to main content

Castrum 0.4.0

· 9 min read
Leonard Atorough
Castrum Developer

A samurai stands beneath clouds and a crescent moon in a pixel-art mountain landscape

Castrum 0.4 is the largest update to the framework to date, bringing with it several foundational changes. The update introduces a lot of breaking changes. Please see the migration guide for a list of all breaking changes and how to update.

New to Castrum? Start with the Getting Started guide.

Over a month has passed since the version 0.3 release. Since then I've been busy rethinking how I want several of the engine's systems to work. I ended up refactoring quite a lot of it and getting carried away in a wave of changes. Castrum 0.4 is the result. It brings major improvements to the ECS and scene systems, breaking changes to animation and audio features, and much more.

Improving the ECS foundation​

Castrum 0.4 improves the ECS foundation with typed storage, queries and change tracking.

Typed component storage​

Component values are now stored as their actual types, rather than boxed as any. While relatively small, this storage change unlocked the next stage of the redesign: a better way to write queries.

Typed queries​

Queries can now be typed as well as dynamic. Typed queries unlock significant improvements in performance and ergonomics, and allow for easier component mutation. For example, let's consider the following dynamic query in 0.3:

query := core.NewQuery(world).With(Position{}, Velocity{})

for entry := range query.Execute() {
velocity, _ := entry.Component[Velocity]()
entry.Update(func(position *Position) {
position.X += velocity.X
})
}

Now you can write this as a typed query:

query := core.NewQuery2[Position, Velocity](world)

for _, row := range query.Execute() {
pos, vel := row.A, row.B
pos.X += vel.X
}

Below is a comparison of typed and dynamic queries in 0.4:

Comparison of typed and dynamic queries in 0.4

The dynamic and typed benchmark implementations are available for inspection.

Component change tracking​

Castrum now provides a way to track changes to components through the opt-in TrackChanges interface.

type Health struct{ Amount int }

func (Health) TrackChanges() {}

healthQuery := core.NewQuery1[Health](world).Changed()

for entity, row := range healthQuery.Execute() {
updateHealthBar(entity.ID(), row.A.Amount)
}

Scenes redesign​

0.4 changes the scene system. A Scene is now a builder function that accepts properties and produces a Node. This redesign means a function can be defined once and spawned with different properties. In addition, scenes can preload assets.

type roomProps struct {
Name string
Position geom.Vector2
}

var roomScene = scene.Of(func(p roomProps) scene.Node {
return scene.Node{
Key: "room",
Assets: []scene.Preload{scene.Warm[asset.FontData](builtin.Font)},
Components: []any{core.Transform{Position: p.Position}},
Children: []scene.Node{{
Key: "label",
Components: []any{
core.Transform{Position: p.Position},
sprite.Text{Asset: builtin.Font, Text: p.Name, TextSize: 24},
},
}},
}
})

Spawning a scene is done through the director with the desired props:

director, err := world.Resource[*scene.Director]()
// handle error

instanceId, err := director.Load(roomScene, roomProps{
Name: "Hangar",
Position: geom.Vector2{X: 320, Y: 180},
})
// handle error

Data-driven scenes​

Castrum 0.4 also brings in support for authoring entities and whole scenes as data, through the brand new serialization package. The package brings a registry for component and resource types, serialised file formats for scenes and functions to spawn entities from file or construct Scene functions.

{
"key": "crate",
"components": [
{ "type": "core.Transform", "value": { "position": { "x": 100, "y": 80 } } },
{ "type": "sprite.Sprite", "value": { "asset": "art/crate.png" } }
],
"assets": [{ "type": "asset.TextureData", "id": "art/crate.png" }]
}

This file can then be loaded and turned into a scene with the registry.

func loadCrate(loader *asset.Loader, registry *serialization.Registry) (scene.Scene, error) {
file, err := loader.Load[serialization.File]("scenes/crate.json")
if err != nil {
return nil, err
}
return file.Scene(registry)
}

The asset workflow has grown up around this too. Spritesheet regions can now be described in JSON, and typed codecs support loading and saving data.

ECS-driven animation​

This version ships a redesigned animation workflow. Animation now works through reusable animation collections called Sets and an entity's Animator component. A Set is a named collection of states, with each state describing a sequence of tracks and how it should play. The animator holds a reference to its set and declares which state it wants.

sets, err := animation.NewSets(map[string]animation.Set{
"samurai": {
Name: "samurai",
States: map[string]animation.State{
"idle": {Name: "idle", Loop: animation.Loop, Tracks: []animation.Track{idle}},
"run": {Name: "run", Loop: animation.Loop, Tracks: []animation.Track{run}},
"attack": {Name: "attack", Next: "idle", Tracks: []animation.Track{attack}},
},
},
})
if err != nil {
return err
}
if err := world.InsertResource(sets); err != nil {
return err
}

We can then give an entity an animator and request an attack when the game needs one:

samurai, err := world.NewEntity(core.Transform{}, animation.Animator{Set: "samurai", State: "idle"})
if err != nil {
return err
}

// Later, when the character attacks:
if err := samurai.Update(world, func(animator *animation.Animator) {
animator.State = "attack"
}); err != nil {
return err
}

States can also contain multiple tracks for layered animations, blend when entering a new state, and emit signals when playback starts or completes.

Visual API improvements​

Visual components​

In 0.4, visual concepts now have their own separate components. Sprite for textures and spritesheet regions, Text for text, and Primitive for shapes. They share a Style for things like colour, layer and visibility, but each component describes its own visual.

Now we can give the same entity both a rectangle and a label:

if _, err := world.NewEntity(
core.Transform{},
sprite.Primitive{
Shape: sprite.ShapeRect,
Rect: geom.Vector2{X: 120, Y: 40},
},
sprite.Text{Asset: builtin.Font, Text: "Ready", TextSize: 16},
); err != nil {
return err
}

Audio Improvements​

Player component​

Castrum 0.4 ships with a new audio Player component. A Player is made up of a playback Source, a collection of audio asset IDs, and Settings for playback control. The audio system handles these plays automatically, with better playback management and track handling.

func addMusic(world *core.World) (core.Entity, error) {
player, err := audio.NewPlayer(
audio.Tracks("audio/exploration.mp3", "audio/battle.mp3"),
audio.Settings{
Bus: "music",
Volume: 1,
Load: audio.LoadStream,
Loop: audio.LoopAll,
},
)
if err != nil {
return core.Entity{}, err
}
return world.NewEntity(player)
}

Audio mixer​

The audio Mixer lets you group audio into distinct, string-named buses. Buses can be paused, muted or have their volume adjusted independently. The Mixer provides a master bus and functions for global pause and muting. Additionally, the mixer provides fade handling for each bus.

mixer := world.MustResource[*audio.Mixer]()

if err := mixer.SetBusVolume("music", 0.5); err != nil {
return err
}
if err := mixer.Fade("music", 0.1, 2*time.Second); err != nil {
return err
}

Spatial audio​

Spatial audio is now available for sounds placed in the world, with distance attenuation controlled by an opt-in Listener resource. A camera-following listener requires a primary camera with a Transform; its range controls where sound fades to silence.

func configureSpatialAudio(world *core.World) {
listener := world.MustResource[*audio.Listener]()
listener.Enabled = true
listener.Mode = audio.FollowCamera
listener.Range = 600
}

func playImpact(world *core.World, position geom.Vector2) error {
_, err := audio.OneShotAt(
world,
audio.Track("audio/impact.wav"),
audio.Settings{Bus: "effects", Volume: 1, Spatial: true},
position,
)
return err
}

Settings and player preferences​

Castrum 0.4 adds a settings package to help hold player preferences without tying them to a particular menu or save format. There are ready-made preference types for audio levels, input bindings and startup display settings.

if err := prefs.Update(func(p audio.Preferences) audio.Preferences {
p.Master = 0.5
return p
}); err != nil {
return err
}

Time rework​

Time has a home in the gametime package. The engine now makes both real time and simulation time available as resources, alongside the timers that previously lived in their own package. The package also ships a new Scheduler for running tasks at intervals.

func scheduleSpawns(world *core.World) error {
scheduler, err := world.Resource[*gametime.Scheduler]()
if err != nil {
return err
}
return scheduler.Every("spawn enemy", 120, spawnEnemy)
}

State machines​

Castrum now supports state machines for managing game modes. State machines are resources that can be added to your game world and used to provide state machine logic for different game states.

modes := state.New[string]().WithInitial("menu")
modes.OnEnter("playing", startGame)
game := castrum.New(castrum.WithState(modes))

// Later, when the player starts the game:
if err := modes.Request("playing"); err != nil {
return err
}

Systems and scheduling​

Systems are now simply functions that take a context and return an error. castrum.After and castrum.Before are new functions to help control system order within a phase. I've also added pre- and post-phases to each main phase (startup, frame, fixed) for more fine-grained control.

if err := game.AddSystem(core.PhaseFixed, "move", movePlayer); err != nil {
return err
}
if err := game.AddSystem(core.PhaseFixed, "follow", followPlayer, castrum.After("move")); err != nil {
return err
}

Other additions and improvements​

  • Raycasting: Find the closest collider along a segment, useful for aiming or checking line of sight.
  • Signals: Readers can now consume their unread signals with a callback, making event-handling systems a little less repetitive.
  • Safety and reliability: This release includes fixes for collision contacts, geometry, asset loading and resource handling, along with checks against structural world changes during query iteration.
  • Documentation and examples: Migration guidance is available for breaking changes, and the examples have been reorganised into standalone programs.
  • Dynamic queries: With and Without are now Require and Exclude; ComponentPtr also allows in-place updates.
  • Camera: The Camera component now encapsulates its view and framing.
  • Game setup: Core systems such as animation, collision and timers are wired up by default, while optional features such as scenes are enabled as needed.
  • Input as Resources: Input Actions and Snapshot are now treated as resources, simplifying access in systems.

What's Next​

Castrum is still early, and the next step is to see how these foundations hold up in games beyond my own. If you try it, I’d especially value feedback on what works, where you get stuck, and what you need to build your game.

To try Castrum, start with the Getting Started guide. Runnable examples showcasing many of the features in this release can be found in the examples directory.