entities

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: 17 Imported by: ? 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 entities is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package entities provides 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.

Architectural Decision (#136)

Three architectures were weighed for representing game objects in github.com/nsgo-dev/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 tables and query planners.

This package chooses (1) for five reasons:

  • Predictable, allocation-free 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. Spawning, destroying, accessing and querying components perform zero heap allocations in steady state and avoid GC pointer chasing.
  • Zero reflection: Go generics identify component stores via zero-sized type tags and keep all component access, queries and prefab builders statically typed with no reflect imports.
  • Safe handle lifetimes: stale Entity handles are automatically invalidated when a slot is destroyed and recycled, eliminating dangling references without weak pointers or runtime bookkeeping.
  • Explicit, deterministic execution: systems declare Before/After ordering constraints resolved once via Kahn's topological sort with registration-order tie-breaking, making frame order inspectable (for debug overlays) and reproducible across runs and platforms.
  • Clean serialization boundaries: only component types explicitly registered with RegisterCodec are written into deterministic WorldSnapshot JSON values and persisted through game/save, keeping transient runtime state (such as sprite handles or audio voices) out of save files while preserving entity IDs and cross-entity references.

All methods on World and Scheduler are designed to be called on the engine's goroutine, matching game.Loop and NSGo's core.Scope. Heavy per-entity systems that update each entity solely from its own components (or read-only state) can fan out deterministically across cores with ParEach1..ParEach4 and chunk-ordered ParReduce1..ParReduce4, which automatically fall back to an allocation-free inline loop on js/wasm or with one worker.

Index

Examples

Constants

View Source
const DefaultParChunkSize = 64

DefaultParChunkSize is the number of driver-store dense entries processed per chunk when ParOptions.ChunkSize is zero or negative.

Variables

View Source
var (
	// ErrCycle reports a SetParent call that would create a cycle in the hierarchy, including parenting an entity to itself.
	ErrCycle = errors.New("entities: hierarchy cycle")
	// ErrDeadEntity reports a hierarchy operation attempted on Zero or an entity that is not alive in the World.
	ErrDeadEntity = errors.New("entities: dead entity")
	// ErrNotDecomposable reports a keep-world reparent whose exact relative
	// transform contains shear and cannot be stored as a Transform2D.
	ErrNotDecomposable = errors.New("entities: relative transform is not decomposable to TRS")
	// ErrNoParent reports a sibling-order operation such as MoveChild on an entity that has no parent.
	ErrNoParent = errors.New("entities: entity has no parent")
	// ErrIndexOutOfRange reports a MoveChild target index outside [0, childCount).
	ErrIndexOutOfRange = errors.New("entities: child index out of range")
)
View Source
var (
	// ErrEmptySystemName reports a system or ordering constraint with an empty name.
	ErrEmptySystemName = errors.New("entities: empty system name")
	// ErrDuplicateSystem reports registering a system whose name is already present in the Scheduler.
	ErrDuplicateSystem = errors.New("entities: duplicate system name")
	// ErrNilSystem reports registering a system with a nil update function.
	ErrNilSystem = errors.New("entities: nil system function")
	// ErrUnknownSystem reports a Before/After constraint or SetEnabled call naming a system that was never registered.
	ErrUnknownSystem = errors.New("entities: unknown system dependency")
	// ErrSystemCycle reports a cycle in the system ordering constraints.
	ErrSystemCycle = errors.New("entities: cyclic system dependency")
	// ErrInvalidProcessMode reports registering a system with an unrecognized ProcessMode value.
	ErrInvalidProcessMode = errors.New("entities: invalid process mode")
)
View Source
var (
	// ErrEmptyCodecName reports registering a component codec with an empty type name.
	ErrEmptyCodecName = errors.New("entities: empty codec name")
	// ErrDuplicateCodec reports registering a codec name or component type that is already registered on the World.
	ErrDuplicateCodec = errors.New("entities: duplicate codec registration")
	// ErrUnknownCodec reports a snapshot containing a component type that has no registered codec on the target World.
	ErrUnknownCodec = errors.New("entities: unknown component codec")
	// ErrInvalidSnapshot reports a malformed WorldSnapshot (such as zero generation, duplicate entity index, or out-of-range index).
	ErrInvalidSnapshot = errors.New("entities: invalid world snapshot")
)
View Source
var ErrParallelMutation = errors.New("entities: structural mutation forbidden during parallel query")

ErrParallelMutation reports a structural World or Store mutation attempted while a parallel query (ParEach1..ParEach4 or ParReduce1..ParReduce4) is running.

View Source
var ErrWorldDisposed = errors.New("entities: world is disposed")

ErrWorldDisposed reports an operation attempted on a World that has been disposed.

Functions

func AddedSince

func AddedSince[T any](w *World, since uint64, fn func(Entity, *T) bool)

AddedSince visits components added after since.

func ChangedSince

func ChangedSince[T any](w *World, since uint64, fn func(Entity, *T) bool)

ChangedSince visits components changed after since.

func CodecName

func CodecName[T any](w *World) (string, bool)

CodecName returns the codec name registered for component type T on w and whether one is registered.

func Each1

func Each1[A any](w *World, fn func(Entity, *A) bool)

Each1 visits every live entity in w carrying component A in deterministic dense order until fn returns false. It performs no reflection and zero heap allocations.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or collect entities and add components after Each returns.

func Each1Opt

func Each1Opt[A, Opt any](w *World, fn func(Entity, *A, *Opt) bool)

Each1Opt visits every live entity in w carrying A, passing a pointer to Opt (or nil when Opt is absent), until fn returns false. It drives iteration from the required sparse set in deterministic dense order with no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each1OptWithout

func Each1OptWithout[A, Opt, X any](w *World, fn func(Entity, *A, *Opt) bool)

Each1OptWithout visits every live entity in w carrying A, skipping any that also carry X, passing a pointer to Opt (or nil when Opt is absent), until fn returns false. It drives iteration from the required sparse set in deterministic dense order with no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each1Slice

func Each1Slice[A any](w *World, fn func(Entity, *A, time.Duration) bool)

Each1Slice visits entities carrying A whose stable SliceOf handle belongs to the slice returned by World.Slice, passing the slice's accumulated dt to fn. It is Each1 with slice membership and dt, and keeps Each1's deterministic order and zero heap allocations.

The component pointers and the dt are valid only during the callback, with the same store-growth rules as Each1.

func Each1Without

func Each1Without[A, X any](w *World, fn func(Entity, *A) bool)

Each1Without visits entities carrying A but skips any that also carry X. It keeps the allocation-free dense iteration and deterministic order of Each1.

func Each2

func Each2[A, B any](w *World, fn func(Entity, *A, *B) bool)

Each2 visits every live entity in w carrying both A and B until fn returns false. It drives iteration from the smaller sparse set and checks membership in the other in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each2Opt

func Each2Opt[A, B, Opt any](w *World, fn func(Entity, *A, *B, *Opt) bool)

Each2Opt visits every live entity in w carrying A and B, passing a pointer to Opt (or nil when Opt is absent), until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each2OptWithout

func Each2OptWithout[A, B, Opt, X any](w *World, fn func(Entity, *A, *B, *Opt) bool)

Each2OptWithout visits every live entity in w carrying A and B, skipping any that also carry X, passing a pointer to Opt (or nil when Opt is absent), until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each2Slice

func Each2Slice[A, B any](w *World, fn func(Entity, *A, *B, time.Duration) bool)

Each2Slice visits entities carrying A and B whose stable SliceOf handle belongs to the slice returned by World.Slice, passing the slice's accumulated dt to fn. It keeps Each2's smallest-store deterministic traversal and zero heap allocations.

func Each2Without

func Each2Without[A, B, X any](w *World, fn func(Entity, *A, *B) bool)

Each2Without visits entities carrying both A and B, skipping any that also carry the exclusion component X. It drives iteration from the smaller included sparse set, keeps the deterministic order of Each2, and performs no reflection and zero heap allocations, matching the exclusion contract of Each1Without.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

func Each3

func Each3[A, B, C any](w *World, fn func(Entity, *A, *B, *C) bool)

Each3 visits every live entity in w carrying A, B and C until fn returns false. It drives iteration from the smallest of the three sparse sets and checks membership in the other two in O(1) time, with deterministic order, no reflection and zero heap allocations.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each3Opt

func Each3Opt[A, B, C, Opt any](w *World, fn func(Entity, *A, *B, *C, *Opt) bool)

Each3Opt visits every live entity in w carrying A, B and C, passing a pointer to Opt (or nil when Opt is absent), until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each3OptWithout

func Each3OptWithout[A, B, C, Opt, X any](w *World, fn func(Entity, *A, *B, *C, *Opt) bool)

Each3OptWithout visits every live entity in w carrying A, B and C, skipping any that also carry X, passing a pointer to Opt (or nil when Opt is absent), until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each3Slice

func Each3Slice[A, B, C any](w *World, fn func(Entity, *A, *B, *C, time.Duration) bool)

Each3Slice visits entities carrying A, B and C whose stable SliceOf handle belongs to the slice returned by World.Slice, passing the slice's accumulated dt to fn. It keeps Each3's smallest-store deterministic traversal and zero heap allocations.

func Each3Without

func Each3Without[A, B, C, X any](w *World, fn func(Entity, *A, *B, *C) bool)

Each3Without visits entities carrying A, B and C, skipping any that also carry the exclusion component X. It drives iteration from the smallest included sparse set, keeps the deterministic order of Each3, and performs no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

func Each4

func Each4[A, B, C, D any](w *World, fn func(Entity, *A, *B, *C, *D) bool)

Each4 visits every live entity in w carrying A, B, C and D, until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each4Without

func Each4Without[A, B, C, D, X any](w *World, fn func(Entity, *A, *B, *C, *D) bool)

Each4Without visits every live entity in w carrying A, B, C and D, skipping any that also carry X, until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each5

func Each5[A, B, C, D, E any](w *World, fn func(Entity, *A, *B, *C, *D, *E) bool)

Each5 visits every live entity in w carrying A, B, C, D and E, until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each5Without

func Each5Without[A, B, C, D, E, X any](w *World, fn func(Entity, *A, *B, *C, *D, *E) bool)

Each5Without visits every live entity in w carrying A, B, C, D and E, skipping any that also carry X, until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each6

func Each6[A, B, C, D, E, F any](w *World, fn func(Entity, *A, *B, *C, *D, *E, *F) bool)

Each6 visits every live entity in w carrying A, B, C, D, E and F, until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func Each6Without

func Each6Without[A, B, C, D, E, F, X any](w *World, fn func(Entity, *A, *B, *C, *D, *E, *F) bool)

Each6Without visits every live entity in w carrying A, B, C, D, E and F, skipping any that also carry X, until fn returns false. It drives iteration from the smallest required sparse set (first on ties) and checks membership in the remaining stores in O(1) time, with deterministic order, no reflection and zero heap allocations.

A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores; use World.Commands to defer structural changes safely.

The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or use World.Commands.

func EachChange

func EachChange[T any](w *World, since uint64, fn func(Entity, ChangeKind, *T) bool)

EachChange visits component changes after since in deterministic journal order. The pointer is nil for removed components.

func Get

func Get[T any](w *World, e Entity) (*T, bool)

Get returns a pointer to entity e's component of type T in w, or (nil, false) if absent or if e is not alive.

func Has

func Has[T any](w *World, e Entity) bool

Has reports whether live entity e carries component T in w.

func LoadWorld

func LoadWorld(store *save.Store, slot string, w *World) error

LoadWorld reads slot from store through game/save and atomically restores it into w.

func MarkChanged

func MarkChanged[T any](w *World, e Entity)

MarkChanged records a write through a component pointer returned by Get.

func Mut

func Mut[T any](w *World, e Entity) (*T, bool)

Mut returns a component pointer and records a changed event for it.

func NearestViewerDistance

func NearestViewerDistance(x, y float32, viewers []Viewer) float32

NearestViewerDistance returns the Euclidean distance from (x, y) to the nearest viewer, or math.MaxFloat32 when viewers is empty.

func OnAdd

func OnAdd[T any](w *World, fn func(Entity, *T)) (remove func())

OnAdd registers fn to run in registration order whenever component T is added to an entity that did not already carry T. Replacing an existing T with Set does not invoke OnAdd. Hooks never run while Store[T] is being queried; if a component is added during a query of the same store, the hook runs as soon as the query exits. It returns an idempotent function that unregisters the hook. Clear, Reset, Restore and Dispose do not run hooks.

func OnRemove

func OnRemove[T any](w *World, fn func(Entity, *T)) (remove func())

OnRemove registers fn to run in registration order whenever component T is removed from an entity via Remove or World.Destroy. During World.Destroy, OnRemove runs for each component before OnDestroy. Hooks never run while Store[T] is being queried; if a component is removed during a query of the same store, the hook runs as soon as the query exits. It returns an idempotent function that unregisters the hook. Clear, Reset, Restore and Dispose do not run hooks.

func ParEach1

func ParEach1[A any](w *World, opt ParOptions, fn func(Entity, *A))

ParEach1 calls fn for every live entity in w carrying component A, split into deterministic chunks of opt.ChunkSize across up to opt.Workers goroutines.

fn may write only *A of the entity it is handed and may perform read-only lookups on other components; it must not spawn, destroy, add or remove components, or record on World.Commands. Structural mutations during the call panic in development builds and are refused under -tags release. On js/wasm or with Workers == 1 it runs inline with no goroutines and no allocations.

func ParEach2

func ParEach2[A, B any](w *World, opt ParOptions, fn func(Entity, *A, *B))

ParEach2 calls fn for every live entity in w carrying both A and B, split into deterministic chunks of opt.ChunkSize across up to opt.Workers goroutines.

Iteration drives from the smaller sparse set (breaking ties toward A), so chunk boundaries depend only on dense order and opt.ChunkSize, never on opt.Workers or runtime.GOMAXPROCS(0). fn may write only *A and *B of the entity it is handed; it must not spawn, destroy, add or remove components, or record on World.Commands. Structural mutations during the call panic in development builds and are refused under -tags release. On js/wasm or with Workers == 1 it runs inline with no goroutines and no allocations.

func ParEach3

func ParEach3[A, B, C any](w *World, opt ParOptions, fn func(Entity, *A, *B, *C))

ParEach3 calls fn for every live entity in w carrying A, B and C, split into deterministic chunks of opt.ChunkSize across up to opt.Workers goroutines.

Iteration drives from the smallest of the three sparse sets (breaking ties in parameter order). fn may write only *A, *B and *C of the entity it is handed; it must not spawn, destroy, add or remove components, or record on World.Commands. Structural mutations during the call panic in development builds and are refused under -tags release. On js/wasm or with Workers == 1 it runs inline with no goroutines and no allocations.

func ParEach4

func ParEach4[A, B, C, D any](w *World, opt ParOptions, fn func(Entity, *A, *B, *C, *D))

ParEach4 calls fn for every live entity in w carrying A, B, C and D, split into deterministic chunks of opt.ChunkSize across up to opt.Workers goroutines.

Iteration drives from the smallest of the four sparse sets (breaking ties in parameter order). fn may write only *A, *B, *C and *D of the entity it is handed; it must not spawn, destroy, add or remove components, or record on World.Commands. Structural mutations during the call panic in development builds and are refused under -tags release. On js/wasm or with Workers == 1 it runs inline with no goroutines and no allocations.

func ParReduce1

func ParReduce1[A, R any](w *World, opt ParOptions, part func(Entity, *A, R) R, combine func(R, R) R) R

ParReduce1 computes one partial result per chunk of opt.ChunkSize entities carrying A and combines non-empty chunk results in ascending chunk order.

Chunk boundaries depend only on dense order and opt.ChunkSize, and combine runs in ascending chunk order on every worker count (including Workers == 1 and js/wasm), so the returned value is identical regardless of worker count. part may write only *A of the entity it is handed; structural mutations during the call panic in development builds and are refused under -tags release.

func ParReduce2

func ParReduce2[A, B, R any](w *World, opt ParOptions, part func(Entity, *A, *B, R) R, combine func(R, R) R) R

ParReduce2 computes one partial result per chunk of opt.ChunkSize entities carrying A and B and combines non-empty chunk results in ascending chunk order.

Iteration drives from the smaller sparse set (breaking ties toward A), chunk boundaries depend only on dense order and opt.ChunkSize, and combine runs in ascending chunk order on every worker count (including Workers == 1 and js/wasm), so the returned value is identical regardless of worker count. part may write only *A and *B of the entity it is handed; structural mutations during the call panic in development builds and are refused under -tags release.

Example

ParEach2 updates each entity's own components across deterministic chunks, and ParReduce2 combines chunk partials in chunk order so the result is identical for every worker count.

package main

import (
	"fmt"

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

type Pos struct{ X, Y float32 }

type Vel struct{ X, Y float32 }

func main() {
	w := entities.NewWorld()
	defer w.Dispose()

	for i := 1; i <= 4; i++ {
		e := w.Spawn()
		entities.Set(w, e, Pos{X: float32(i)})
		entities.Set(w, e, Vel{X: 0.5})
	}

	opt := entities.ParOptions{Workers: 2, ChunkSize: 2}
	entities.ParEach2(w, opt, func(_ entities.Entity, p *Pos, v *Vel) {
		p.X += v.X
	})
	totalX := entities.ParReduce2(w, opt,
		func(_ entities.Entity, p *Pos, _ *Vel, acc float32) float32 { return acc + p.X },
		func(a, b float32) float32 { return a + b },
	)
	fmt.Printf("%.1f\n", totalX)
}
Output:
12.0

func ParReduce3

func ParReduce3[A, B, C, R any](w *World, opt ParOptions, part func(Entity, *A, *B, *C, R) R, combine func(R, R) R) R

ParReduce3 computes one partial result per chunk of opt.ChunkSize entities carrying A, B and C and combines non-empty chunk results in ascending chunk order.

Iteration drives from the smallest of the three sparse sets (breaking ties in parameter order), chunk boundaries depend only on dense order and opt.ChunkSize, and combine runs in ascending chunk order on every worker count (including Workers == 1 and js/wasm), so the returned value is identical regardless of worker count. part may write only *A, *B and *C of the entity it is handed; structural mutations during the call panic in development builds and are refused under -tags release.

func ParReduce4

func ParReduce4[A, B, C, D, R any](w *World, opt ParOptions, part func(Entity, *A, *B, *C, *D, R) R, combine func(R, R) R) R

ParReduce4 computes one partial result per chunk of opt.ChunkSize entities carrying A, B, C and D and combines non-empty chunk results in ascending chunk order.

Iteration drives from the smallest of the four sparse sets (breaking ties in parameter order), chunk boundaries depend only on dense order and opt.ChunkSize, and combine runs in ascending chunk order on every worker count (including Workers == 1 and js/wasm), so the returned value is identical regardless of worker count. part may write only *A, *B, *C and *D of the entity it is handed; structural mutations during the call panic in development builds and are refused under -tags release.

func RegisterCodec

func RegisterCodec[T any](w *World, typeName string) error

RegisterCodec registers a JSON codec for component type T under typeName on w.

Only component types with a registered codec are included in WorldSnapshot output. Registering the same typeName or the same Go type T twice returns ErrDuplicateCodec.

func RegisterResourceCodec

func RegisterResourceCodec[T any](w *World, name string) error

RegisterResourceCodec registers a JSON codec for world resource type T under name on w.

Only resource types with a registered codec are written to WorldSnapshot.Resources. Registering an empty or whitespace-only name returns ErrEmptyCodecName; registering the same name or the same Go type T twice returns ErrDuplicateCodec.

func Remove

func Remove[T any](w *World, e Entity)

Remove detaches component T from entity e in w if present.

func RemoveLater

func RemoveLater[T any](c *Commands, e Entity)

RemoveLater records a deferred Remove[T] for entity e.

func RemoveResource

func RemoveResource[T any](w *World)

RemoveResource deletes the world-level resource of type T from w if present. It is a no-op if w is nil, disposed, or does not hold a resource of type T.

func RemovedSince

func RemovedSince[T any](w *World, since uint64, fn func(Entity) bool)

RemovedSince visits entities whose component was removed after since.

func ResolveLOD

func ResolveLOD(current int, distance float32, bands []LODBand, hysteresis float32) int

ResolveLOD returns the level for an entity at distance from its nearest viewer, given its current level.

The target level is that of the band with the smallest MaxDistance not below distance; beyond every band it is the level of the band with the largest MaxDistance. Bands may be given in any order, and bands with equal MaxDistance resolve to the first one in the slice. hysteresis is a fraction of a boundary's distance that distance must cross beyond the boundary before the level changes, where a level's boundary is the largest MaxDistance among its bands: moving to a farther level requires leaving the current level's boundary*(1+hysteresis), and moving to a nearer level requires coming within the target level's boundary*(1-hysteresis). With no bands, a NaN distance, or a non-positive hysteresis the corresponding rule is skipped and current or the plain target is returned. ResolveLOD does not allocate.

func Resource

func Resource[T any](w *World) (*T, bool)

Resource returns a pointer to the world-level resource of type T on w and true, or (nil, false) if no resource of type T is set or w is nil or disposed.

Mutations through the returned pointer update the stored resource in place. The pointer remains valid until the resource is removed or the world is reset, restored or disposed.

func SaveWorld

func SaveWorld(store *save.Store, slot string, w *World) error

SaveWorld snapshots w and writes it to slot in store through game/save.

func Set

func Set[T any](w *World, e Entity, v T)

Set attaches or replaces component v on entity e in w. It is a no-op if e is not alive in w. Setting a Transform2D while the World has a Hierarchy2D marks e and its descendants dirty, exactly like Hierarchy2D.SetLocal, so WorldTransform2D never goes stale (#546). Writing through a pointer from Get or a Store still needs Hierarchy2D.MarkDirty.

func SetLater

func SetLater[T any](c *Commands, e Entity, v T)

SetLater records a deferred Set[T] for entity e. It accepts both live entities and reserved handles returned by Commands.Spawn.

func SetResource

func SetResource[T any](w *World, v T)

SetResource stores or replaces the world-level resource of type T on w.

Each Go type T has at most one value per World. Resources survive World.Clear and are cleared by World.Reset and World.Dispose. Calling SetResource on a nil or disposed World is a no-op.

func SliceOf

func SliceOf(e Entity, count int) int

SliceOf returns the stable time slice of e for count slices, in [0, count).

It hashes the generational handle with a fixed 64-bit mixing function, so the same live entity always maps to the same slice, destroying an entity never moves another entity between slices, two runs with identical spawns produce identical slices, and new spawns spread over the slices. count <= 1 always returns 0. SliceOf does not allocate.

Types

type ChangeKind

type ChangeKind uint8

ChangeKind identifies a component-store change.

const (
	// ChangeAdded records a component set on an entity that did not carry one.
	ChangeAdded ChangeKind = iota + 1
	// ChangeChanged records a replaced component or a write marked by Mut or MarkChanged.
	ChangeChanged
	// ChangeRemoved records a removed component.
	ChangeRemoved
)

type Commands

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

Commands records deferred structural changes against a World so systems and query callbacks can spawn, destroy, and add or remove components without mutating stores during iteration.

Commands are applied in exact record order by World.ApplyCommands (and automatically at the end of Scheduler.Step, or immediately after a system configured with FlushAfter). Backing buffers are reused across flushes so steady-state recording and applying perform zero heap allocations.

Example

Commands buffers spawns, destroys and component edits recorded during a query and applies them in order.

package main

import (
	"fmt"

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

type Hitpoints struct{ HP int }

func main() {
	w := entities.NewWorld()
	defer w.Dispose()

	a := w.Spawn()
	b := w.Spawn()
	entities.Set(w, a, Hitpoints{HP: 0})
	entities.Set(w, b, Hitpoints{HP: 4})

	c := w.Commands()
	entities.Each1(w, func(e entities.Entity, h *Hitpoints) bool {
		if h.HP <= 0 {
			c.Destroy(e)
		}
		return true
	})
	fresh := c.Spawn(nil)
	entities.SetLater(c, fresh, Hitpoints{HP: 9})
	fmt.Println(w.Alive(a), w.Alive(fresh))
	fmt.Println(w.ApplyCommands(), w.Alive(a), w.Alive(fresh))
}
Output:
true false
3 false true

func (*Commands) Defer

func (c *Commands) Defer(fn func(w *World))

Defer records fn to run against the World in record order when ApplyCommands runs.

func (*Commands) Destroy

func (c *Commands) Destroy(e Entity)

Destroy records a deferred World.Destroy for e. Destroying an already-dead entity or destroying the same entity more than once is a safe no-op when applied.

func (*Commands) Spawn

func (c *Commands) Spawn(p *Prefab) Entity

Spawn reserves an entity handle immediately and records a deferred spawn.

The returned Entity is not alive until ApplyCommands runs (World.Alive returns false and World.Count, World.Each and World.Snapshot exclude it), but it may be passed to SetLater, RemoveLater and Destroy or stored in components right away. If p is non-nil, p's component builders apply when the spawn runs. It returns Zero if c is nil or its World is disposed.

type ComponentSnapshot

type ComponentSnapshot struct {
	Type string          `json:"type"`
	Data json.RawMessage `json:"data"`
}

ComponentSnapshot holds a single JSON-encoded component tagged by its registered codec name.

type Entity

type Entity uint64

Entity is a 64-bit generational handle identifying an entity in a World.

The low 32 bits store the slot index and the high 32 bits store the slot's generation. When an entity is destroyed, its slot is recycled with an incremented generation, so stale handles never alias newly spawned entities.

const Zero Entity = 0

Zero is the invalid entity handle. Live entities always have a non-zero generation, so Zero is never alive.

func MakeEntity

func MakeEntity(index, generation uint32) Entity

MakeEntity constructs a generational Entity handle from its 32-bit slot index and generation. It returns Zero when generation is 0.

func (Entity) Generation

func (e Entity) Generation() uint32

Generation returns the entity's 32-bit generation counter (0 for Zero).

func (Entity) Index

func (e Entity) Index() uint32

Index returns the entity's 32-bit slot index.

func (Entity) IsZero

func (e Entity) IsZero() bool

IsZero reports whether e is the invalid Zero handle.

func (Entity) String

func (e Entity) String() string

String formats e as "Entity(index:generation)" or "Entity(0)" for Zero.

type EntitySnapshot

type EntitySnapshot struct {
	Index uint32 `json:"index"`
	// Parent is the slot index of this entity's hierarchy parent, when the
	// snapshot recorded one; it is nil for a root entity.
	Parent     *uint32             `json:"parent,omitempty"`
	Generation uint32              `json:"generation"`
	Components []ComponentSnapshot `json:"components,omitempty"`
}

EntitySnapshot captures one live entity's generational handle and its serialized components in sorted type-name order.

type Groups

type Groups struct {
	Names []string `json:"names,omitempty"`
}

Groups is the component carrying an entity's group memberships in sorted order.

Manage membership through World.AddToGroup and World.RemoveFromGroup, or by attaching, replacing, or removing Groups through Set, Store.Set, and Remove; the World keeps its per-group spawn-order index in sync automatically.

func (Groups) Has

func (g Groups) Has(group string) bool

Has reports whether g contains group.

type Hierarchy2D

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

Hierarchy2D manages parent-child 2D transform relationships, visibility inheritance, and dirty-subtree propagation for a World.

Local transforms are stored in the World's Store[Transform2D] and composed world transforms are cached in Store[WorldTransform2D], allowing ECS queries (Each1/Each2/Each3) to iterate world transforms directly with zero allocations. Parent-child links are maintained in an intrusive, pointer-free slice indexed by Entity.Index(), so steady-state updates, dirty propagation, reparenting, and Sync perform zero heap allocations.

When World.Destroy removes a parent entity directly, Hierarchy2D automatically cleans up its links according to its configured RemovePolicy (default RemoveDetach) so dangling parent/child references never occur.

Example

Hierarchy2D parents entities so a child's world transform follows its parent's.

package main

import (
	"fmt"

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

func main() {
	w := entities.NewWorld()
	defer w.Dispose()
	h := w.Hierarchy2D()

	ship := w.Spawn()
	h.SetLocal(ship, entities.NewTransform2D(100, 50))
	turret := w.Spawn()
	h.SetLocal(turret, entities.NewTransform2D(10, 0))
	if err := h.SetParent(turret, ship, false); err != nil {
		fmt.Println(err)
		return
	}
	h.SetScale(ship, 2, 2)
	h.Sync()
	wt, _ := h.WorldTransform(turret)
	fmt.Println(wt.X, wt.Y, h.ChildCount(ship))

	h.SetVisible(ship, false)
	h.Sync()
	wt, _ = h.WorldTransform(turret)
	fmt.Println(wt.WorldVisible)
}
Output:
120 50 1
false

func NewHierarchy2D

func NewHierarchy2D(w *World) *Hierarchy2D

NewHierarchy2D returns the 2D transform hierarchy bound to w, creating and attaching it on first call. It returns nil if w is nil.

func (*Hierarchy2D) AppendChildren

func (h *Hierarchy2D) AppendChildren(dst []Entity, e Entity) []Entity

AppendChildren appends e's direct children in deterministic insertion order to dst and returns the extended slice.

func (*Hierarchy2D) ChildCount

func (h *Hierarchy2D) ChildCount(e Entity) int

ChildCount returns the number of direct children of e (0 if e is dead or has no children).

func (*Hierarchy2D) Children

func (h *Hierarchy2D) Children(e Entity) []Entity

Children returns a newly allocated slice of e's direct children in deterministic insertion order, or nil if e has none. For zero-allocation iteration, use EachChild or AppendChildren.

func (*Hierarchy2D) DestroyWithPolicy

func (h *Hierarchy2D) DestroyWithPolicy(e Entity, policy RemovePolicy)

DestroyWithPolicy destroys e in the World after applying policy to its children:

  • RemoveDetach: detaches direct children to root, keeping each child's local Transform2D.
  • RemoveDetachKeepWorld: detaches direct children to root while preserving their world transforms.
  • RemoveCascade: recursively destroys e and all of its descendants, children before parents.

In all cases, parent/child links are cleaned up so no dangling handles remain.

func (*Hierarchy2D) Detach

func (h *Hierarchy2D) Detach(child Entity, keepWorld bool)

Detach removes child from its parent so it becomes a root entity. When keepWorld is true, child's local Transform2D is updated to its composed world transform before detaching. Detaching Zero, a dead entity, or an entity that is already a root is a no-op.

func (*Hierarchy2D) EachChild

func (h *Hierarchy2D) EachChild(e Entity, fn func(Entity) bool)

EachChild calls fn for each direct child of e in deterministic insertion order until fn returns false.

func (*Hierarchy2D) EachDescendant

func (h *Hierarchy2D) EachDescendant(e Entity, fn func(Entity) bool)

EachDescendant calls fn for every strict descendant of e in deterministic pre-order (parent before its children, siblings in child order) until fn returns false.

It allocates nothing in steady state and is safe under re-entrant calls and mutations to the hierarchy or world inside fn.

func (*Hierarchy2D) Index

func (h *Hierarchy2D) Index(e Entity) int

Index returns e's 0-based position among its parent's direct children, or -1 if e is dead, not in the hierarchy, or is a root.

func (*Hierarchy2D) IsAncestor

func (h *Hierarchy2D) IsAncestor(a, e Entity) bool

IsAncestor reports whether a is a strict ancestor of e in h (parent, grandparent, etc.). It returns false when a == e, either entity is dead or Zero, or h is nil or disposed.

func (*Hierarchy2D) IsDirty

func (h *Hierarchy2D) IsDirty(e Entity) bool

IsDirty reports whether e currently needs world-transform recomputation.

func (*Hierarchy2D) Local

func (h *Hierarchy2D) Local(e Entity) (Transform2D, bool)

Local returns e's local Transform2D and true, or (zero, false) if e is dead or has no Transform2D.

func (*Hierarchy2D) MarkDirty

func (h *Hierarchy2D) MarkDirty(e Entity)

MarkDirty marks e and all of its descendants as needing world-transform recomputation. Call MarkDirty after mutating a *Transform2D pointer obtained directly from Store[Transform2D].

func (*Hierarchy2D) MoveChild

func (h *Hierarchy2D) MoveChild(child Entity, index int) error

MoveChild moves child to 0-based position index among its parent's direct children.

It returns ErrWorldDisposed if the World is disposed, ErrDeadEntity if child is not alive, ErrNoParent if child has no parent, and ErrIndexOutOfRange if index is outside [0, childCount).

func (*Hierarchy2D) Parent

func (h *Hierarchy2D) Parent(e Entity) (Entity, bool)

Parent returns e's parent entity and true, or (Zero, false) if e is dead, not in the hierarchy, or is a root.

func (*Hierarchy2D) RemovePolicy

func (h *Hierarchy2D) RemovePolicy() RemovePolicy

RemovePolicy returns the default RemovePolicy used when World.Destroy is called directly on a parent entity.

func (*Hierarchy2D) SetLocal

func (h *Hierarchy2D) SetLocal(e Entity, t Transform2D)

SetLocal sets e's local Transform2D and marks e and its descendants dirty. It is a no-op if e is not alive.

func (*Hierarchy2D) SetParent

func (h *Hierarchy2D) SetParent(child, parent Entity, keepWorld bool) error

SetParent attaches child as the last direct child of parent in deterministic insertion order.

If parent is Zero, child is detached to root (equivalent to Detach(child, keepWorld)). SetParent returns ErrWorldDisposed if the World is disposed, ErrDeadEntity if child (or non-Zero parent) is not alive, and ErrCycle if parenting would introduce a cycle (including child == parent). When keepWorld is true, child's local Transform2D is recomputed relative to parent's world transform so child stays at the same world position, rotation, and scale.

func (*Hierarchy2D) SetPosition

func (h *Hierarchy2D) SetPosition(e Entity, x, y float32)

SetPosition updates e's local (X, Y) position and marks e and its descendants dirty. If e does not yet have a Transform2D, NewTransform2D(x, y) is attached.

func (*Hierarchy2D) SetRemovePolicy

func (h *Hierarchy2D) SetRemovePolicy(policy RemovePolicy)

SetRemovePolicy sets the default RemovePolicy used when World.Destroy is called directly on a parent entity.

func (*Hierarchy2D) SetRotation

func (h *Hierarchy2D) SetRotation(e Entity, rotation float32)

SetRotation updates e's local rotation in radians and marks e and its descendants dirty. If e does not yet have a Transform2D, IdentityTransform2D with the given rotation is attached.

func (*Hierarchy2D) SetScale

func (h *Hierarchy2D) SetScale(e Entity, sx, sy float32)

SetScale updates e's local (ScaleX, ScaleY) and marks e and its descendants dirty. If e does not yet have a Transform2D, IdentityTransform2D with the given scale is attached.

func (*Hierarchy2D) SetVisible

func (h *Hierarchy2D) SetVisible(e Entity, visible bool)

SetVisible updates e's local visibility and marks e and its descendants dirty. If e does not yet have a Transform2D, IdentityTransform2D with the given visibility is attached.

func (*Hierarchy2D) Sync

func (h *Hierarchy2D) Sync() int

Sync updates WorldTransform2D for all dirty subtrees in topological parent-before-child order, skipping clean nodes completely. It returns the number of entities whose WorldTransform2D was recomputed and performs zero heap allocations in steady state.

func (*Hierarchy2D) WorldTransform

func (h *Hierarchy2D) WorldTransform(e Entity) (WorldTransform2D, bool)

WorldTransform returns e's up-to-date WorldTransform2D and true, resolving e's dirty ancestor chain lazily on demand if needed. It returns (zero, false) if e is dead or has no Transform2D and is not part of the hierarchy.

type LOD

type LOD struct {
	// Level is the current simulation level; 0 is full rate and higher levels are cheaper.
	Level int
	// Previous is the level the entity held before its last change.
	Previous int
	// Steps counts the fixed steps since the entity's last update at its level.
	Steps int
	// LastDistance is the nearest-viewer distance used for the last level resolution.
	LastDistance float32
	// Pending is the dt accumulated since the entity's last LODSystem.Simulate update. It carries over unchanged when the level changes, so the first update at a new level receives the whole elapsed time exactly once.
	Pending time.Duration
}

LOD is the per-entity simulation level-of-detail state a game stores as a component and updates with ResolveLOD or LODSystem.

type LODBand

type LODBand struct {
	MaxDistance float32
	Level       int
}

LODBand maps every distance up to and including MaxDistance to Level.

type LODSystem

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

LODSystem resolves the simulation level of every entity carrying an LOD component from its distance to the nearest viewer, applies optional per-level caps, and runs per-entity updates on the cadence their level selects.

Callers step LODSystem.Update before the systems that call LODSystem.Simulate in the same step, so a level change decided this step is due this step.

func NewLODSystem

func NewLODSystem(opts LODSystemOptions) *LODSystem

NewLODSystem returns an LODSystem configured with opts. The option slices are copied, so later changes to them do not affect the system.

func (*LODSystem) Simulate

func (s *LODSystem) Simulate(w *World, dt time.Duration, fn LODUpdate) int

Simulate advances every entity carrying LOD to the cadence of its current level and calls fn once for each entity that is due, with the dt accumulated since that entity's last update, including the current step. It returns how many entities were updated.

Step counting and the accumulated dt live in the LOD component, so a level change never loses or doubles time: the next update at the new level receives everything accumulated so far, and an entity entering a faster cadence is due immediately. The state survives a WorldSnapshot when LOD is registered with RegisterCodec, so a reloaded world continues on the same schedule. fn must not add LOD components structurally; use World.Commands for structural changes.

func (*LODSystem) Update

func (s *LODSystem) Update(w *World, viewers []Viewer)

Update recomputes every entity's LOD level from the nearest viewer, its ResolveLOD hysteresis rules and then the configured caps.

It visits only entities carrying an LOD component, so games opt entities in at spawn. The viewer list is read once per call. It performs no heap allocations once its candidate buffer has grown to the largest number of capped entities, and never mutates component storage structurally.

type LODSystemOptions

type LODSystemOptions struct {
	// Bands maps distance to a level with the same semantics as ResolveLOD. Bands may be given in any order.
	Bands []LODBand
	// Hysteresis is the boundary margin as a fraction of a level's outer boundary, as ResolveLOD defines it.
	Hysteresis float32
	// Caps limits how many entities may hold a level: Caps[level] > 0 allows at most that many entities at that level, and zero, negative and levels past the slice are uncapped. Caps apply after distance: the farthest entities beyond a cap drop one level, and equal distances demote the larger Entity handle first, so the result never depends on store order.
	Caps []int
	// Cadence maps a level to the number of fixed steps between LODSystem.Simulate updates of an entity at that level: a value <= 1, a negative level and a level past the slice update every step.
	Cadence []int
	// Position returns the 2D world position of e; it must not structurally change the World. When nil, the entity's Transform2D position is used and entities without one are skipped.
	Position func(w *World, e Entity) (x, y float32, ok bool)
}

LODSystemOptions configures an LODSystem.

type LODUpdate

type LODUpdate func(w *World, e Entity, lod *LOD, dt time.Duration)

LODUpdate receives one due entity's LOD state and the dt accumulated since its previous update.

type ParOptions

type ParOptions struct {
	// Workers is the maximum number of goroutines that participate in the query (including the caller).
	// Values <= 0 use runtime.GOMAXPROCS(0). Values == 1 (or any value on js/wasm) run inline with no goroutines and no allocations.
	// Values above max(64, runtime.GOMAXPROCS(0)*2) are clamped.
	Workers int
	// ChunkSize is the number of driver-store dense entries per chunk.
	// Chunk boundaries depend only on dense order and ChunkSize, never on Workers or runtime.GOMAXPROCS(0), so chunk-ordered reductions produce identical results for every worker count.
	// Values <= 0 use DefaultParChunkSize.
	ChunkSize int
}

ParOptions configures parallel query iteration (ParEach1..ParEach4) and chunk-ordered reductions (ParReduce1..ParReduce4).

The zero value uses a fixed worker pool sized from runtime.GOMAXPROCS(0) on desktop and mobile targets, and runs inline with no goroutines and no allocations on js/wasm.

type Prefab

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

Prefab is a named entity template that attaches a preset list of components to each entity it spawns.

Value components added with With are copied per entity, while reference-containing components (slices, maps, pointers) added with WithFunc invoke their constructor per spawn so entities never share mutable state.

Example

A Prefab spawns entities with a preset set of components.

package main

import (
	"fmt"

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

type Vel struct{ X, Y float32 }

type Hitpoints struct{ HP int }

func main() {
	w := entities.NewWorld()
	defer w.Dispose()

	slime := entities.With(entities.NewPrefab("slime"), Hitpoints{HP: 3})
	entities.With(slime, Vel{X: -1})
	for _, e := range slime.SpawnN(w, 3) {
		h, _ := entities.Get[Hitpoints](w, e)
		fmt.Println(e, h.HP)
	}
	fmt.Println(entities.Component[Hitpoints](w).Len())
}
Output:
Entity(0:1) 3
Entity(1:1) 3
Entity(2:1) 3
3

func NewPrefab

func NewPrefab(name string) *Prefab

NewPrefab returns an empty Prefab with the given name.

func With

func With[T any](p *Prefab, v T) *Prefab

With attaches a value component template v of type T to p and returns p. If T is already present on p, its builder is replaced. For components containing slices, maps or pointers, prefer WithFunc so each spawned entity receives an independent copy.

func WithFunc

func WithFunc[T any](p *Prefab, make func() T) *Prefab

WithFunc attaches a constructor-backed component template of type T to p and returns p. make is invoked once per spawned entity so slices, maps and pointers are never shared across entities. If make is nil, the zero value of T is used.

func (*Prefab) Clone

func (p *Prefab) Clone(name string) *Prefab

Clone returns a new Prefab named name with a shallow copy of p's component builders, allowing derived prefabs to override or add components without mutating p.

func (*Prefab) Name

func (p *Prefab) Name() string

Name returns the prefab's name.

func (*Prefab) Spawn

func (p *Prefab) Spawn(w *World) Entity

Spawn creates a new entity in w and applies all of p's component builders to it.

func (*Prefab) SpawnN

func (p *Prefab) SpawnN(w *World, n int) []Entity

SpawnN spawns n independent entities from p in w and returns their handles. It returns nil when n <= 0 or w is nil.

type ProcessMode

type ProcessMode uint8

ProcessMode controls whether a system runs during Scheduler.Step, Scheduler.StepPaused, or both.

const (
	// ProcessPausable runs the system during Scheduler.Step only (the default).
	ProcessPausable ProcessMode = iota
	// ProcessWhenPaused runs the system during Scheduler.StepPaused only.
	ProcessWhenPaused
	// ProcessAlways runs the system during both Scheduler.Step and Scheduler.StepPaused.
	ProcessAlways
)

func (ProcessMode) String

func (m ProcessMode) String() string

String returns the human-readable name of m.

type RemovePolicy

type RemovePolicy uint8

RemovePolicy controls what happens to direct children when a parent entity is destroyed.

const (
	// RemoveDetach detaches direct children to root before destroying the parent, keeping each child's local Transform2D.
	// This is the default policy applied when World.Destroy removes a parent directly.
	RemoveDetach RemovePolicy = iota
	// RemoveDetachKeepWorld detaches direct children to root before destroying the parent, updating each child's local Transform2D to preserve its composed world transform.
	RemoveDetachKeepWorld
	// RemoveCascade recursively destroys the entity and all of its descendants.
	RemoveCascade
)

type ResourceSnapshot

type ResourceSnapshot struct {
	Name string          `json:"name"`
	Data json.RawMessage `json:"data"`
}

ResourceSnapshot holds a single JSON-encoded world resource tagged by its registered resource codec name.

type Scheduler

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

Scheduler runs named systems over a World in a deterministic topological order derived from Before and After constraints.

Ties between unconstrained systems are broken by registration order. The zero value of Scheduler is ready to use.

Example

A Scheduler runs systems in an order derived from their Before and After constraints.

package main

import (
	"fmt"
	"time"

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

func main() {
	w := entities.NewWorld()
	defer w.Dispose()

	s := entities.NewScheduler()
	s.AddSystem("render", func(*entities.World, time.Duration) {})
	s.AddSystem("move", func(*entities.World, time.Duration) {}, entities.Before("collide"))
	s.AddSystem("collide", func(*entities.World, time.Duration) {}, entities.Before("render"))
	if err := s.Step(w, time.Second/60); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(s)
}
Output:
move -> collide -> render

func NewScheduler

func NewScheduler() *Scheduler

NewScheduler returns an empty Scheduler.

func (*Scheduler) AddSystem

func (s *Scheduler) AddSystem(name string, fn func(w *World, dt time.Duration), opts ...SystemOption) error

AddSystem registers a named system with optional Before/After constraints.

Constraint targets may be registered later; missing targets and dependency cycles are reported by Build and Step. Immediate errors (empty name, duplicate name, nil function, empty target, or self-dependency) are returned right away without modifying s.

func (*Scheduler) Build

func (s *Scheduler) Build() error

Build validates all Before/After constraints and resolves the deterministic execution order using Kahn's algorithm with registration-order tie-breaking.

func (*Scheduler) Enabled

func (s *Scheduler) Enabled(name string) bool

Enabled reports whether a system named name is registered on s and currently enabled.

func (*Scheduler) HasSystem

func (s *Scheduler) HasSystem(name string) bool

HasSystem reports whether a system named name has been registered on s.

func (*Scheduler) Order

func (s *Scheduler) Order() []string

Order returns the resolved system names in execution order. It resolves the schedule lazily if needed and returns nil if the schedule is empty or invalid.

func (*Scheduler) SetEnabled

func (s *Scheduler) SetEnabled(name string, enabled bool) error

SetEnabled switches the named system on or off without altering its place in the resolved execution order. Calling SetEnabled during Step or StepPaused takes effect immediately for systems that have not yet run in the current step.

func (*Scheduler) Step

func (s *Scheduler) Step(w *World, dt time.Duration) error

Step resolves the schedule if needed and runs every enabled ProcessPausable and ProcessAlways system on w with dt in exact resolved order. Systems configured with FlushAfter apply w's deferred commands immediately after running; Step also calls w.ApplyCommands at the end of the step. Once built, Step performs zero heap allocations of its own.

func (*Scheduler) StepPaused

func (s *Scheduler) StepPaused(w *World, dt time.Duration) error

StepPaused resolves the schedule if needed and runs every enabled ProcessWhenPaused and ProcessAlways system on w with dt in exact resolved order. Systems configured with FlushAfter apply w's deferred commands immediately after running; StepPaused also calls w.ApplyCommands at the end of the step. Once built, StepPaused performs zero heap allocations of its own.

Example

Process modes split systems across Step (ProcessPausable and ProcessAlways) and StepPaused (ProcessWhenPaused and ProcessAlways), while SetEnabled switches a system off without changing its order.

package main

import (
	"fmt"
	"time"

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

func main() {
	w := entities.NewWorld()
	defer w.Dispose()

	var ran []string
	rec := func(name string) func(*entities.World, time.Duration) {
		return func(*entities.World, time.Duration) { ran = append(ran, name) }
	}
	s := entities.NewScheduler()
	_ = s.AddSystem("move", rec("move"))
	_ = s.AddSystem("shake", rec("shake"), entities.Mode(entities.ProcessAlways), entities.After("move"))
	_ = s.AddSystem("pause_ui", rec("pause_ui"), entities.Mode(entities.ProcessWhenPaused), entities.After("shake"))

	_ = s.Step(w, time.Second/60)
	fmt.Println("step:", ran)
	ran = ran[:0]
	_ = s.StepPaused(w, time.Second/60)
	fmt.Println("paused:", ran)
	_ = s.SetEnabled("move", false)
	ran = ran[:0]
	_ = s.Step(w, time.Second/60)
	fmt.Println("disabled move:", ran, "order:", s)
}
Output:
step: [move shake]
paused: [shake pause_ui]
disabled move: [shake] order: move -> shake -> pause_ui

func (*Scheduler) String

func (s *Scheduler) String() string

String formats the resolved system order as "a -> b -> c" for debug overlays and logs.

type Slice

type Slice struct {
	// Index is the slice due in the current step, in [0, Count).
	Index int
	// Count is the slice count k; 1 means the system is not sliced and every entity is due.
	Count int
	// Delta is the dt summed over the steps since this slice last ran, including the current step. Consecutive Delta values of one slice together cover every step that slice waited through.
	Delta time.Duration
}

Slice identifies the deterministic time slice a system registered with Scheduler.Slices runs in, and the dt accumulated since that slice last ran.

type Store

type Store[T any] struct {
	// contains filtered or unexported fields
}

Store holds all instances of component type T in a World using a typed sparse set.

Dense arrays (dense and values) keep components tightly packed for cache-friendly, zero-allocation iteration, while sparse maps entity slot indices to dense indices in O(1) time.

func Component

func Component[T any](w *World) *Store[T]

Component returns the typed component Store for T in w, creating it if it does not yet exist.

func (*Store[T]) Each

func (s *Store[T]) Each(fn func(Entity, *T) bool)

Each calls fn for every entity carrying T in deterministic dense order until fn returns false.

A callback may destroy the entity it was handed, but not add or remove other entities/components of this store: a removal elsewhere swaps the last entry into the removed slot, which can skip or revisit an entity. When the callback needs to touch other entities of the same store, use World.Commands or collect them during Each and act after it returns. The *T is valid only until the callback adds a component to this store, which can grow it and move its values (#546).

func (*Store[T]) Get

func (s *Store[T]) Get(e Entity) (*T, bool)

Get returns a pointer to e's component value and true, or (nil, false) if e is not alive or lacks T. The returned pointer remains valid until components are added or removed from this store.

func (*Store[T]) Has

func (s *Store[T]) Has(e Entity) bool

Has reports whether live entity e currently carries component T.

func (*Store[T]) Len

func (s *Store[T]) Len() int

Len returns the number of entities that currently carry component T.

func (*Store[T]) Remove

func (s *Store[T]) Remove(e Entity)

Remove detaches component T from e if present. It is a no-op if e is stale or lacks T.

func (*Store[T]) Set

func (s *Store[T]) Set(e Entity, v T)

Set attaches or replaces component v on e. It is a no-op if e is not alive in the store's World.

type SystemOption

type SystemOption func(*systemEntry)

SystemOption configures ordering constraints, conditions, flushing, or process mode on a system added to a Scheduler.

func After

func After(other string) SystemOption

After constrains the system to run after the system named other.

func Before

func Before(other string) SystemOption

Before constrains the system to run before the system named other.

func FlushAfter

func FlushAfter() SystemOption

FlushAfter applies World.ApplyCommands immediately after this system runs in Scheduler.Step or Scheduler.StepPaused, so later systems in the same step see its deferred spawns, destroys and component changes. Without FlushAfter, Scheduler.Step and Scheduler.StepPaused apply pending commands once after the last system finishes.

func Mode

func Mode(m ProcessMode) SystemOption

Mode sets the ProcessMode that decides whether the system runs in Scheduler.Step, Scheduler.StepPaused, or both.

func RunIf

func RunIf(cond WorldCondition) SystemOption

RunIf runs the system only when cond is true for the current world. The condition is evaluated in Step immediately before the system, in resolved order; a nil condition always holds.

func Slices

func Slices(k int) SystemOption

Slices runs a system every step but scopes its entity iteration to a deterministic 1/k of the entities that match it: on each Step or StepPaused call the scheduler advances one slice, and World.Slice reports that slice and the dt summed over its k steps. Each1Slice, Each2Slice and Each3Slice visit only the entities whose stable SliceOf handle belongs to the current slice, passing that summed dt to the callback, so an entity is visited once per k steps and its accumulated dt is neither lost nor doubled. The slice of an entity is a stable hash of its generational handle, never iteration order or a random draw, so despawns do not reshuffle the other entities, replays match, and a wave spawned on one step spreads across k steps instead of spiking every k-th step. k <= 1 runs every step without slicing. Slices does not gate the system as a whole; use RunIf for that.

type Transform2D

type Transform2D struct {
	X        float32 `json:"x"`
	Y        float32 `json:"y"`
	Rotation float32 `json:"rotation,omitempty"`
	ScaleX   float32 `json:"scaleX"`
	ScaleY   float32 `json:"scaleY"`
	Hidden   bool    `json:"hidden,omitempty"`
}

Transform2D is an entity's local 2D transform relative to its parent (or to world space when the entity is a root).

The zero value of Transform2D is visible (Hidden == false) with ScaleX == 0 and ScaleY == 0 (collapsed scale), matching game/sprite.Sprite. Use IdentityTransform2D or NewTransform2D to construct a visible transform with unit scale (1, 1).

func IdentityTransform2D

func IdentityTransform2D() Transform2D

IdentityTransform2D returns a visible Transform2D at (0, 0) with zero rotation and unit scale (1, 1).

func NewTransform2D

func NewTransform2D(x, y float32) Transform2D

NewTransform2D returns a visible Transform2D at (x, y) with zero rotation and unit scale (1, 1).

func (Transform2D) Matrix

func (t Transform2D) Matrix() [6]float32

Matrix returns the local 2D affine matrix [a, b, c, d, tx, ty] mapping local points to parent space:

px = a*lx + c*ly + tx
py = b*lx + d*ly + ty

The layout matches nsgo/core.Drawing.Transform and game/sprite.

func (*Transform2D) SetVisible

func (t *Transform2D) SetVisible(visible bool)

SetVisible sets whether this local transform is visible.

func (Transform2D) Visible

func (t Transform2D) Visible() bool

Visible reports whether this local transform is visible (!t.Hidden).

type Viewer

type Viewer struct{ X, Y float32 }

Viewer is a 2D position, such as a camera or player, that entities measure their LOD distance from.

type World

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

World owns entities, their typed component stores, typed world resources, and registered serialization codecs.

The zero value of World is ready to use; NewWorld returns a freshly allocated one.

Example

A World holds entities and their components; Each2 visits every entity that has both component types, in a fixed order.

package main

import (
	"fmt"

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

type Pos struct{ X, Y float32 }

type Vel struct{ X, Y float32 }

func main() {
	w := entities.NewWorld()
	defer w.Dispose()

	player := w.Spawn()
	entities.Set(w, player, Pos{X: 0, Y: 0})
	entities.Set(w, player, Vel{X: 2, Y: 1})
	rock := w.Spawn()
	entities.Set(w, rock, Pos{X: 5, Y: 5})

	entities.Each2(w, func(e entities.Entity, p *Pos, v *Vel) bool {
		p.X += v.X
		p.Y += v.Y
		return true
	})
	p, _ := entities.Get[Pos](w, player)
	fmt.Println(player, *p)
	fmt.Println(entities.Has[Vel](w, rock), w.Count())

	w.Destroy(rock)
	again := w.Spawn()
	fmt.Println(w.Alive(rock), again.Index() == rock.Index(), again.Generation())
}
Output:
Entity(0:1) {2 1}
false 2
false true 2

func NewWorld

func NewWorld() *World

NewWorld returns an empty World ready for spawning entities and attaching components.

func (*World) AddToGroup

func (w *World) AddToGroup(e Entity, group string)

AddToGroup adds live entity e to group and updates w's group index. It is a no-op if w is nil or disposed, e is not alive, group is empty, or e is already in group.

func (*World) Alive

func (w *World) Alive(e Entity) bool

Alive reports whether e refers to a currently live entity in w. Reserved handles returned by Commands.Spawn are not alive until ApplyCommands runs.

func (*World) ApplyCommands

func (w *World) ApplyCommands() int

ApplyCommands executes all recorded commands on w in record order and returns how many ran.

Commands recorded while ApplyCommands is running (from Defer callbacks or lifecycle hooks) are appended to the queue and executed in FIFO order before ApplyCommands returns. Calling ApplyCommands re-entrantly while it is already running returns 0; the outer call drains the remaining queue.

func (*World) Attach

func (w *World) Attach(cx *core.Scope)

Attach binds w's lifetime to cx so w.Dispose runs automatically when cx is disposed.

func (*World) ChangeTick

func (w *World) ChangeTick() uint64

ChangeTick returns an observation point on the world's change clock and turns change recording on. It advances the clock, so every change recorded after the call carries a later tick: passing the returned value to EachChange, AddedSince, ChangedSince or RemovedSince visits exactly the changes made since the call. Scheduler.Step also advances the clock before each system. The clock never goes back, not even on Clear or Reset.

func (*World) ChildrenOf

func (w *World) ChildrenOf(e Entity) []Entity

ChildrenOf returns e's direct children in w's Hierarchy2D without creating a hierarchy when none is attached.

func (*World) Clear

func (w *World) Clear()

Clear removes all live entities and their components while preserving slot generations, allocated capacities, typed world resources, registered codecs and registered hooks for zero-allocation reuse. All entity handles (including reserved command handles) issued before Clear become stale, pending commands are discarded, and Clear does not run hooks.

func (*World) CodecNames

func (w *World) CodecNames() []string

CodecNames returns the component codec names registered on w in ascending order.

func (*World) Commands

func (w *World) Commands() *Commands

Commands returns the deferred command buffer belonging to w. It returns nil if w is nil.

func (*World) Count

func (w *World) Count() int

Count returns the number of live entities in w.

func (*World) DecodeComponent

func (w *World) DecodeComponent(e Entity, typeName string, raw json.RawMessage) error

DecodeComponent strictly decodes raw JSON into the codec-registered component named typeName and attaches or replaces it on live entity e. Unknown JSON fields, trailing data, invalid nulls for non-nullable component types and values the codec cannot encode back, such as a NaN, are rejected without mutating e.

func (*World) Destroy

func (w *World) Destroy(e Entity)

Destroy removes e and all of its components from w and returns its slot to the free list with an incremented generation. Destroying Zero or an entity that is not alive in w is a no-op. Registered OnRemove hooks run for each component on e before OnDestroy; under Hierarchy2D's RemoveCascade policy, children run their hooks before parents.

func (*World) Dispose

func (w *World) Dispose()

Dispose releases all entities and component storage in w and marks w as disposed. Calling Dispose more than once is a no-op. Dispose does not run lifecycle hooks.

func (*World) Disposed

func (w *World) Disposed() bool

Disposed reports whether w has been disposed.

func (*World) Each

func (w *World) Each(fn func(Entity) bool)

Each calls fn for every live entity in w in ascending slot-index order until fn returns false. Entities spawned during iteration are not visited.

func (*World) EncodeComponent

func (w *World) EncodeComponent(e Entity, typeName string) (json.RawMessage, bool, error)

EncodeComponent encodes the codec-registered component named typeName on live entity e as JSON. It returns (nil, false, nil) when e is not alive, typeName is not registered, or e does not carry the component.

func (*World) EntityComponents

func (w *World) EntityComponents(e Entity) ([]ComponentSnapshot, error)

EntityComponents encodes all codec-registered components carried by live entity e in ascending codec-name order.

func (*World) FirstInGroup

func (w *World) FirstInGroup(group string) (Entity, bool)

FirstInGroup returns the first live entity in group in deterministic spawn order and true, or (Zero, false) if group has no members.

func (*World) HasCodec

func (w *World) HasCodec(e Entity, typeName string) bool

HasCodec reports whether live entity e currently carries the codec-registered component named typeName.

func (*World) Hierarchy2D

func (w *World) Hierarchy2D() *Hierarchy2D

Hierarchy2D returns the World's 2D transform hierarchy, creating and attaching it on first call.

func (*World) InGroup

func (w *World) InGroup(group string, fn func(Entity) bool)

InGroup calls fn for every live entity currently in group in deterministic spawn order until fn returns false.

Group membership is indexed so InGroup visits only members of group without scanning all entities, and steady-state iteration allocates nothing. Destroying or removing entities from group during fn is safe; entities added to group during fn are not visited by the in-progress call.

func (*World) OnDestroy

func (w *World) OnDestroy(fn func(Entity)) (remove func())

OnDestroy registers fn to run in registration order whenever a live entity is destroyed, after OnRemove hooks for each of its components have run. Under Hierarchy2D's RemoveCascade policy, children run their OnRemove and OnDestroy hooks before their parents. It returns an idempotent function that unregisters the hook. Clear, Reset, Restore and Dispose do not run hooks.

Example

Lifecycle hooks run OnRemove for each component before OnDestroy when an entity is destroyed.

package main

import (
	"fmt"

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

type Hitpoints struct{ HP int }

func main() {
	w := entities.NewWorld()
	defer w.Dispose()

	removeHP := entities.OnRemove[Hitpoints](w, func(e entities.Entity, h *Hitpoints) {
		fmt.Println("remove", e, h.HP)
	})
	defer removeHP()
	removeDestroy := w.OnDestroy(func(e entities.Entity) {
		fmt.Println("destroy", e)
	})
	defer removeDestroy()

	e := w.Spawn()
	entities.Set(w, e, Hitpoints{HP: 5})
	w.Destroy(e)
}
Output:
remove Entity(0:1) 5
destroy Entity(0:1)

func (*World) OnSpawn

func (w *World) OnSpawn(fn func(Entity)) (remove func())

OnSpawn registers fn to run in registration order whenever an entity becomes alive via World.Spawn, Prefab.Spawn, or a deferred Commands.Spawn applied by ApplyCommands. It returns an idempotent function that unregisters the hook. Clear, Reset, Restore and Dispose do not run hooks.

func (*World) ParentOf

func (w *World) ParentOf(e Entity) (Entity, bool)

ParentOf returns e's parent entity in w's Hierarchy2D without creating a hierarchy when none is attached.

func (*World) PatchComponent

func (w *World) PatchComponent(e Entity, typeName string, raw json.RawMessage) error

PatchComponent strictly decodes raw JSON onto live entity e's existing codec-registered component (or its zero value when absent) and writes the result back atomically. Fields the patch does not change keep their current values, including unexported fields, fields tagged `json:"-"` and the identity of pointers, maps and slices. Unknown JSON fields, trailing data and values the codec cannot encode back, such as a NaN, are rejected without mutating e.

func (*World) RemoveComponent

func (w *World) RemoveComponent(e Entity, typeName string) (bool, error)

RemoveComponent detaches the codec-registered component named typeName from live entity e and reports whether it was present.

func (*World) RemoveFromGroup

func (w *World) RemoveFromGroup(e Entity, group string)

RemoveFromGroup removes live entity e from group and updates w's group index. It is a no-op if w is nil or disposed, e is not alive, group is empty, or e is not in group.

func (*World) Reset

func (w *World) Reset()

Reset removes all entities and typed world resources and releases component and active entity backing storage while keeping bumped slot generations (so stale handles never alias newly spawned entities), registered codecs and registered hooks intact. Pending commands are discarded and Reset does not run hooks.

func (*World) Resolve

func (w *World) Resolve(index, generation uint32) (Entity, bool)

Resolve reconstructs the entity handle for (index, generation) and reports whether it is currently live in w.

func (*World) Restore

func (w *World) Restore(snap WorldSnapshot) error

Restore atomically replaces w's entities, components and typed world resources with snap using w's registered codecs.

Entity indices and generations are preserved verbatim so cross-entity references stored inside components remain valid, while slots omitted from snap keep bumped generations so stale handles from before Restore never alias newly spawned entities. If decoding fails (for example due to an unknown codec or invalid JSON), w is left completely unchanged.

An error about the snapshot's contents is a *loaderr.Error that names the field at fault, such as "entities[2].parent", and how to fix it, and matches ErrInvalidSnapshot or ErrUnknownCodec with errors.Is.

func (*World) SavePart

func (w *World) SavePart() save.Part

SavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores w through save.Game. Loading decodes and validates every entity, component codec, resource codec and hierarchy link into staging state before committing to w, and clears w when loading an older save slot that omits this part.

func (*World) Slice

func (w *World) Slice() Slice

Slice returns the time slice of the system currently running in Scheduler.Step or Scheduler.StepPaused, or a Slice with Count 1 outside a system run.

func (*World) Snapshot

func (w *World) Snapshot() (WorldSnapshot, error)

Snapshot encodes all live entities, their codec-registered components and all codec-registered world resources into a deterministic WorldSnapshot. Entities are emitted in ascending slot-index order, each entity's components in ascending codec-name order, and resources in ascending resource-codec-name order.

Example

Snapshot captures the components that have a registered codec, and Restore rebuilds a World from it, as SaveWorld and LoadWorld do through a save.Store.

package main

import (
	"fmt"

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

type Hitpoints struct{ HP int }

func main() {
	w := entities.NewWorld()
	defer w.Dispose()
	entities.RegisterCodec[Hitpoints](w, "health")
	e := w.Spawn()
	entities.Set(w, e, Hitpoints{HP: 7})

	snap, err := w.Snapshot()
	if err != nil {
		fmt.Println(err)
		return
	}
	loaded := entities.NewWorld()
	defer loaded.Dispose()
	entities.RegisterCodec[Hitpoints](loaded, "health")
	if err := loaded.Restore(snap); err != nil {
		fmt.Println(err)
		return
	}
	entities.Each1(loaded, func(e entities.Entity, h *Hitpoints) bool {
		fmt.Println(e, h.HP)
		return true
	})
}
Output:
Entity(0:1) 7

func (*World) Spawn

func (w *World) Spawn() Entity

Spawn creates a new live entity, recycling a previously destroyed slot when available. It returns Zero if w has been disposed.

type WorldCondition

type WorldCondition func(*World) bool

WorldCondition decides whether a system runs for the current world.

func And

func And(conds ...WorldCondition) WorldCondition

And returns a condition that holds when every non-nil condition holds, evaluated in order and stopping at the first that does not. With no non-nil conditions it always holds.

func Not

Not negates a world condition. A nil condition always holds, as it does for RunIf, so Not(nil) never holds.

func Or

func Or(conds ...WorldCondition) WorldCondition

Or returns a condition that holds when any non-nil condition holds, evaluated in order and stopping at the first that does. With no non-nil conditions it never holds.

type WorldSnapshot

type WorldSnapshot struct {
	Entities  []EntitySnapshot   `json:"entities"`
	Resources []ResourceSnapshot `json:"resources,omitempty"`
}

WorldSnapshot is a deterministic, JSON-serializable snapshot of a World's live entities, registered components and registered world resources.

type WorldTransform2D

type WorldTransform2D struct {
	X            float32
	Y            float32
	Rotation     float32
	ScaleX       float32
	ScaleY       float32
	Matrix       [6]float32
	WorldVisible bool
}

WorldTransform2D is the cached world-space 2D transform composed from an entity's ancestor chain.

Matrix holds the exact 2D affine transform [a, b, c, d, tx, ty] mapping local coordinates to world space. X, Y, Rotation, ScaleX and ScaleY hold the decomposed world position, orientation (radians), and axis scales. WorldVisible is true only when this entity and every ancestor are visible.

func (WorldTransform2D) InverseTransformPoint

func (wt WorldTransform2D) InverseTransformPoint(wx, wy float32) (lx, ly float32)

InverseTransformPoint maps a point (wx, wy) in world space back into this entity's local space. If Matrix is singular (zero determinant), it returns (0, 0).

func (WorldTransform2D) TransformPoint

func (wt WorldTransform2D) TransformPoint(lx, ly float32) (wx, wy float32)

TransformPoint maps a point (lx, ly) in this entity's local space into world space.

Jump to

Keyboard shortcuts

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