Table of Contents

ECS Architecture

This page describes how Ghost.Entities is organized internally and how the main pieces interact.

Core Objects

  • World
    • Root owner for ECS runtime state.
    • Holds EntityManager, ComponentManager, SystemManager, and command buffers.
    • Carries a monotonic Version used by change tracking.
  • Entity
    • Lightweight handle (ID, Generation) used to validate stale references.
  • EntityManager
    • Responsible for create/destroy and structural changes (add/remove component).
    • Tracks entity location (archetype, chunk, row) in a slot map.
  • ComponentManager
    • Owns archetypes and query cache.
    • Maps signature hashes to archetype IDs.
    • Maps query-mask hashes to query IDs.
  • EntityQuery
    • Stores a compiled query mask.
    • Maintains a list of matching archetypes.
    • Exposes iterators (chunk, component, entity+component) and scheduling APIs.

Archetype and Chunk Model

Entities are grouped by exact component signature into archetypes.

  • Each archetype owns N chunks.
  • Each chunk stores:
    • packed entity IDs,
    • packed component arrays,
    • optional enable bitmasks for enableable components,
    • per-component change versions,
    • chunk structural version.

Effects:

  • Data for the same component is contiguous per chunk.
  • Iteration can be cache-friendly and branch-light.
  • Structural operations move entities between archetypes.

Structural Changes

Adding/removing components changes an entity signature, so the entity moves:

  1. Resolve current EntityLocation.
  2. Resolve or create destination archetype.
  3. Allocate destination row.
  4. Copy shared component bytes from old to new archetype layout.
  5. Write the new/removed component result.
  6. Remove old row with swap-back compaction.
  7. Update EntityLocation for moved entities.

Archetypes cache transition edges (Add / Remove) to avoid recomputing destination lookups repeatedly.

Query Compilation and Matching

QueryBuilder compiles high-level filter methods into bitset masks.

Main mask dimensions:

  • structural requirements (All, Any, Absent),
  • enabled/disabled semantic filters,
  • write access intent.

A query first filters at archetype level (signature match), then performs per-entity checks for enablement semantics when needed.

Systems and Update Flow

  • SystemManager owns system instances.
  • SystemGroup can sort systems using [UpdateAfter] / [UpdateBefore].
  • SystemBase supports RequireQueryForUpdate gating and lifecycle hooks:
    • OnInitialize,
    • OnStartRunning / OnStopRunning,
    • OnUpdate,
    • OnCleanup.

Deferred Structural Writes

EntityCommandBuffer records structural commands into a compact byte buffer.

  • Record in gameplay/jobs.
  • Playback at controlled sync points.
  • Avoid invalidating iterators while iterating live chunks.

Use per-thread command buffers (World.GetThreadLocalEntityCommandBuffer) in multithreaded pipelines.