NSGo Game

Entities

A small, zero-reflection entity-component-system (ECS) for NSGo games: generational entities, typed sparse-set components, allocation-free queries, topologically ordered systems, prefabs and JSON world snapshots integrated with game/save.

import "github.com/nsgo-dev/game/packages/game/entities"

Architectural decision

Before implementing entities (#136), three designs were compared for representing game objects in packages/game:

  1. A small, zero-reflection, generational-index ECS with typed sparse-set storage (chosen).
  2. An object-oriented scene tree of heap-allocated nodes with virtual update methods.
  3. A reflection-driven archetype ECS with dynamic component tables and query planners.

Option (1) was chosen for five reasons:

  • Zero-allocation hot loops: entities are 64-bit generational handles (32-bit slot index + 32-bit generation) recycled through a free list, and each component type lives in a contiguous typed sparse set (Store[T]). Creating and destroying 100k entities in steady state, accessing components, and iterating queries perform zero heap allocations.
  • Zero reflection: Go generics identify component stores through zero-sized type tags and keep all component access, queries and prefab builders statically typed with no reflect imports.
  • Safe handle lifetimes: destroying an entity increments its slot generation before recycling it, so stale Entity handles never alias newly spawned entities.
  • Explicit, deterministic execution: systems declare Before and After constraints resolved once by Kahn's topological sort with registration-order tie-breaking. Cycles and missing targets fail cleanly, and Order() exposes the exact execution sequence for debug overlays.
  • Clean serialization boundaries: only component types registered with RegisterCodec[T] are written to deterministic WorldSnapshot JSON values and saved through game/save, keeping transient runtime handles (sprites, audio voices) out of save files while preserving entity IDs and cross-entity references.

Entities and World

An Entity is a uint64 carrying a 32-bit slot index and a 32-bit generation (entities.Zero is the invalid handle and is never alive). World owns entities and their component stores.

  • NewWorld() returns a fresh world (the zero value of World is also ready to use).
  • Spawn(), Destroy(e), Alive(e) and Count() manage entity lifetimes with free-list recycling.
  • Clear() removes all entities and components while bumping generations and keeping slice capacities for zero-allocation reuse. Reset() releases backing storage.
  • Attach(cx) binds the world to an NSGo *core.Scope so Dispose() runs automatically when the scope is disposed.
world := entities.NewWorld()
world.Attach(cx)

hero := world.Spawn()
world.Alive(hero) // true
world.Destroy(hero)
world.Alive(hero) // false, even after the slot is recycled

Components and queries

Each component type T is stored in a typed sparse set (*Store[T]). Top-level generic functions operate directly on a *World, and Component[T](w) returns the underlying *Store[T] for direct inner-loop access.

  • Set[T](w, e, v), Get[T](w, e), Has[T](w, e) and Remove[T](w, e) attach, read, check and detach components in O(1) time.
  • Each1[A], Each2[A, B] and Each3[A, B, C] iterate over the smallest sparse set and check O(1) membership in the others, visiting exact matches in deterministic order with zero reflection and zero heap allocations. Returning false stops iteration early.
type Position struct{ X, Y float64 }
type Velocity struct{ DX, DY float64 }

entities.Set(world, hero, Position{X: 10, Y: 20})
entities.Set(world, hero, Velocity{DX: 60, DY: 0})

entities.Each2[Position, Velocity](world, func(e entities.Entity, p *Position, v *Velocity) bool {
	p.X += v.DX * dt.Seconds()
	p.Y += v.DY * dt.Seconds()
	return true
})

Systems and update order

Scheduler runs named systems in a deterministic topological order on each game.Loop fixed step.

  • AddSystem(name, fn, opts...) registers a system with optional Before(other) and After(other) constraints. Targets may be registered in any order.
  • Build() validates constraints and resolves execution order with Kahn's algorithm, breaking ties by registration order. Unknown targets return ErrUnknownSystem and cycles return ErrSystemCycle.
  • Order() returns the resolved names and String() formats them as "a -> b -> c" for debug overlays.
  • Step(w, dt) resolves if needed and runs each system in order with zero steady-state allocations.
sched := entities.NewScheduler()
_ = sched.AddSystem("input", readInput)
_ = sched.AddSystem("physics", stepPhysics, entities.After("input"))
_ = sched.AddSystem("render", syncSprites, entities.After("physics"))

loop := &game.Loop{
	Rate: 60,
	Update: func(dt time.Duration) {
		_ = sched.Step(world, dt)
	},
}

Prefabs

A Prefab is a named template that stamps a preset group of components onto newly spawned entities.

  • NewPrefab(name) creates a template, and Clone(name) derives a variant without mutating the original.
  • With[T](p, v) attaches a value component copied per entity.
  • WithFunc[T](p, make) invokes make() on each spawn so slices, maps and pointers are never shared across entities.
  • Spawn(w) and SpawnN(w, n) create independent entities from the template.
goblin := entities.NewPrefab("goblin")
entities.With(goblin, Position{X: 10, Y: 20})
entities.WithFunc(goblin, func() Inventory {
	return Inventory{Items: []string{"dagger"}}
})

squad := goblin.SpawnN(world, 5)

Saving and loading a world

Worlds serialize to deterministic WorldSnapshot JSON values and integrate directly with game/save.

  • RegisterCodec[T](w, typeName) registers a JSON codec for component type T. Unregistered components are omitted from snapshots.
  • w.Snapshot() emits live entities in ascending slot-index order and components in ascending codec-name order, preserving exact indices and generations so cross-entity Entity references stay valid after restore.
  • w.Restore(snap) decodes into a temporary world first and commits atomically, leaving w untouched if any codec is missing or decoding fails.
  • SaveWorld(store, slot, w) and LoadWorld(store, slot, w) persist and restore worlds through save.Store (both save.NewStorageStore and save.NewFileStore, including schema versions and migrations).
_ = entities.RegisterCodec[Position](world, "position")
_ = entities.RegisterCodec[Velocity](world, "velocity")

store := save.NewStorageStore(cx.Storage(), "game")
if err := entities.SaveWorld(store, "slot1", world); err != nil {
	return err
}

fresh := entities.NewWorld()
_ = entities.RegisterCodec[Position](fresh, "position")
_ = entities.RegisterCodec[Velocity](fresh, "velocity")
if err := entities.LoadWorld(store, "slot1", fresh); err != nil {
	return err
}
Edit this page