ECS evaluation (issue #31)
Status: measured, decided and prototyped (2026-11-16: the user took every recommendation of section 5; the
in-engine prototype of section 6 is section 7). The rest of the implementation is the follow-up ticket. The benchmarks are in Prototypes/EcsBench/ (opt-in, CMake only).
Goal (#31): data-oriented, multithreaded game code by default, not something each system adds later. Before #3,
because the renderer will build its frame packet from component data (Docs/RendererThreading.md).
1. What was measured
Four candidates, the same components, kernels and data (fixed random seeds), all on Primal's job system
(primal.jobs), Release (clang 23, -O3 -mavx2):
- arrays (today): option D, one dense array per component indexed by entity, plus a byte per entity for
optional components (how
Engine/Componentsstores transforms and scripts today). No queries, no user components. - own (archetype): option A in our own code,
Prototypes/EcsBench/OwnEcs.h(about 600 lines): Unity DOTS/Unreal Mass-style 16 KB chunks with one array per component, archetype graph edges, cached queries, per-chunk change versions, per-thread command buffers applied at the sync point, a pool of free chunks, Primal's 32-bit ids (24-bit index, 8-bit generation). - EnTT 4.0.0 (option C, sparse sets): plain views, and full-owning groups (its fast path; a component can be
owned by one group only). Its parallel loops slice the pool and look each entity up, as its docs suggest: it has
no ranged
each(). - flecs 4.2.0 (option A as a library): cached queries; parallel loops in multithreaded read-only mode with one
stage and one worker iterator per job (what its own worker threads do, here on our jobs). Structural changes go
through a stage (4.2 removed
defer_begin()/defer_end(): the world has no deferred mode any more).
Machine: Ryzen 9 5900X (12 cores, 24 threads, 2 × 32 MB L3), 3 runs of 30 rounds each, median per run; ranges are min-max over the runs. All four agree on a check value per benchmark (sums, counts), so none skips work. A Debug build with EnTT's and flecs' asserts runs clean. Parallel loops use one job per thread for every candidate (more, smaller jobs were slower; see section 4).
x64/Release/EcsBench [arrays] [own] [entt] [flecs] # PRIMAL_JOBS=0: one thread; PRIMAL_ECS_BATCH=<n>: job size
2. Results
| Benchmark | arrays (today) | own (archetype) | EnTT | flecs |
|---|---|---|---|---|
| Iterate 1M position+velocity, 1 thread | 0.20-0.21 ms | 0.32-0.45 ms (16 KB chunks), 0.23 (256 KB) | view 1.75-1.84, group 0.87-0.90 | 0.18-0.22 |
| Same, job system | 0.10-0.20 | 0.14-0.17 | view 0.44-0.50, group 0.34-0.42 | 0.10-0.21 |
| Query 3 of 6 components, 100k entities, 12.5k match | 0.08-0.14 ms (scans all) | 0.003 | view 0.27-0.34 | 0.001 |
| Churn: add/remove a component on 10% of 100k, per frame, via a command queue | 0.01-0.05 ms | 0.44-0.50 | 0.19-0.20 | 0.90-0.96 |
| Random access by entity id | 0.6-0.8 ns | 6.3-6.6 | 9.8-9.9 | 11.3-12.4 |
| Transform matrices, 100k, 1 thread | 1.49-1.54 ms | 1.46-1.59 | view 1.81-1.83, group 1.49-1.50 | 1.44-1.46 |
| Same, job system | 0.23-0.29 | 0.25-0.29 | view 0.31-0.33, group 0.22-0.30 | 0.23-0.30 |
| Create 100k entities with 3 components | (n/a) | 3.2-3.3 ms | 3.6 | 16.4-17.3 staged, ~12 direct |
| Destroy 100k entities | (n/a) | 0.96-0.98 ms | 4.1-4.2 | 1.4 |
| Memory, 1M position+velocity | 24 B/entity | 42 | 49 | 59 |
| Memory growth after 50 churn frames | 2 B/entity | 6 | 11 | 70 (stage memory kept) |
Compile time of one file using it (-O2; a plain file: 0.14 s) |
0.62 s (std headers) | 1.15 s | 0.17 s | |
| Size | ~600 lines (prototype) | 1.2 MB of headers | 125k lines of C + 38k header |
3. What the numbers say
- For the engine's real per-frame work, storage doesn't matter. The transform phase is math-bound: all four are within 5% (EnTT's plain view 20% slower), on one thread and on 24. Today's arrays are already as fast as any ECS for a fixed set of components that every entity has. An ECS is not a speed-up of today's code.
- What an ECS adds is generality at nearly no cost: user-defined components, queries that touch only matching entities (3 of 6: 25-140x faster than scanning arrays with flags), structural changes through a queue, change versions, and a place for scheduling. The archetype candidates keep the arrays' speed on linear loops (flecs and own with large chunks match them).
- EnTT is the weak fit for "data-oriented by default". Iterating several components through a view is 4-8x slower on light kernels; groups fix that only for one fixed set per component. Its strengths (cheap add/remove, 2.5x faster churn than our prototype, 5x faster than flecs) matter for tag-heavy designs, which can be had in an archetype ECS with enableable components (DOTS) instead of structural changes.
- flecs is the fastest at iterating and querying, and the slowest at structural changes (create 3-5x, churn 2x our prototype), with the most memory. Its real argument is features: relationships and hierarchies, observers, reflection (would answer much of #41), prefabs, an explorer, a REST API. Its costs for Primal: a 125,000-line C library with its own conventions (C API, its own OS API/allocators/threads, global-ish world state), API churn (4.2 removed deferred mode, which the 4.1 docs and examples still use; this evaluation hit it), and its pipeline/scheduler, which would be bypassed to stay on our jobs and frame phases.
- Our own archetype ECS is within reach. About 600 lines give speed within 1.5x of the best candidate on
iteration (2x on the lightest loop with 16 KB chunks), queries and transforms, the best create/destroy and random
access of the three ECSs, and the least memory; churn is 2.4x behind EnTT (and 2x ahead of flecs). It follows the
project's rules (C++23,
std::expected, the job system, the existing frame phases and command queue, the C ABI for the editor) by construction. What it would still need is the rest of the work list: scheduling by declared access, hierarchy, observers, reflection and editor tooling. That is the larger part of the cost. - Chunk size is a tuning question, not a design one. 16 KB (DOTS' size) costs per-chunk overhead on very light loops (0.32 vs 0.23 ms per 1M); 256 KB matches the arrays but wastes memory on small archetypes (every archetype has at least one chunk). The transform kernel doesn't notice.
4. Side findings
- Job size matters more than the ECS for light loops. Iterating 1M positions in 245 jobs of 4096 took 0.33-0.48
ms on 24 threads, worse than one thread (0.21 ms); 24 jobs (one per thread) took 0.10-0.20 ms. The cost per job
(queueing, waking a worker) is in the microseconds.
jobs::parallel_for()takes a batch size today; a variant that takes a job count, or a cost hint, would suit systems better. FitsDocs/RendererThreading.mdsection 5 step 7 (worker spinning) and #1's tuning. - Primal's ids have 8 generation bits. A slot whose generation reaches 255 is retired for good
(
id::max_generation). With churn-heavy games (spawn/despawn every frame) that retires slots steadily. EnTT uses 12 bits (20-bit index), flecs 64-bit ids. Worth deciding with the ECS (16 bits of each in au32limits the world to 65,536 entities, so it would mean a 64-bit id). - The parallel loops of every candidate ran clean in the Debug build; ThreadSanitizer hasn't been run on the
benchmark (it's a prototype; the follow-up prototype gets
ci.sh tsan).
5. Recommendation and decisions
Recommended: option A in our own code, hybrid with scripts (the Unreal Mass model). Archetype chunks, queries,
systems that declare their access and are scheduled on primal.jobs within the primal.frame phases; scripts stay
objects (EntityScript, GameScript) that read and write components through the entity API, as they do with
transforms today. Reasons: archetypes give the speed (point 2), our own code fits the job system and frame phases
we already built (point 5), and the features flecs would bring (hierarchy, observers, reflection) are each a
bounded piece of work that we'd shape for the editor's C ABI and #41 anyway. flecs is the alternative if features
now matter more than owning the code; EnTT and "stay with arrays" are not recommended.
Decided (user, 2026-11-16): every recommendation below (in brackets where there was a choice).
- The option: A own, A flecs, C EnTT, or D stay with arrays. [A own]
- Scripts (#31 question 8): stay objects next to the ECS (Mass and Unity's hybrid do this), or become components + systems. [objects] Several scripts per entity and script data as components can come later either way.
- When structural changes apply (question 4): at the sync point only (today's rule, recommended to start), or also between phases (Mass), which lets a later phase see entities a former one created. [sync point]
- Change detection (question 6): per-chunk versions (DOTS; in the prototype, recommended) replacing
changes_from_previous_frame/read_write_flag, or per-component dirty flags. [per chunk] - Hierarchy (question 7): a parent component and a depth-ordered transform update (DOTS, recommended with the transform port), or relationships as a general feature (flecs). Either way it lands with the transform port. [parent component]
- Header or module (question 14): the typed API (
create<T...>, queries,get<T>) as a header, since game scripts and other headers include it and GCC needs everyimportafter every#include; the type-erased core (archetypes, chunks, command buffers) behind it in a.cppor a module. Recommended: header API +.cppcore, like logging. [header +.cpp] - Entity ids: keep 32 bits (24/8) for now, or 64-bit ids with a larger generation (see section 4). [32 bits]
- Chunk size: 16 KB (DOTS) to start, revisited with real archetypes, or larger. [16 KB]
Tied to #41 (script reflection): user-defined components need registration (name, size, alignment) for the
editor, game.bin and the C ABI, and reflected fields for an inspector. With option A own, components get a
registration macro like PRIMAL_SCRIPT (an inline variable, no generator), and #41 decides fields/reflection for
scripts and components together. With flecs, its reflection addon covers much of it.
6. After the decisions (the rest of #31's "done when")
- A prototype in the engine, in a branch: the chosen storage; queries; two systems scheduled by their declared
read/write access on the job system inside a frame phase; the entity command queue extended to add/remove
components; the transform phase ported to it (renderer reads stay as they are:
get_transform_matrices()and the light culler's change flags get an ECS-backed implementation). Checked with unit tests andci.sh tsan. - The follow-up implementation ticket with the steps, including the editor's C ABI (
EntityAPI.cpp),game.bin(load_game()), and what #3's frame packet reads. - #41's decision, with the component registration from point 1.
7. The in-engine prototype (2026-11-16)
Engine/ECS/ is a new layer below Components (Tools/check_layers.py: ECS may use Common and Core):
Ecs.h, the typed API:ecs::Worldwithcreate(T...),destroy(),add()/remove(),get<T>()(read) andwrite<T>()(marks the chunk),locate()(anEntityReffor several accesses with one lookup), queries (each(),each_chunk(),parallel_each_chunk()), queued changes from any thread (queue_add(),queue_remove(),queue_destroy(), applied byapply_commands()), and systems (add_system<T...>(name, group, function),run_systems(group)). Access is declared byconst;ChunkView::read()/write()assert it in Debug.World.cpp, the type-erased core: archetypes in 16 KB chunks (the entity ids, then one array per component, 16-byte aligned), archetype graph edges for add/remove, a pool of free chunks, cached queries, one command queue per job system thread (plus one, locked, for other threads), and the scheduler.- Scheduling: a system's step is one more than the latest step of an earlier system of its group whose access conflicts with its own (one writes what the other reads or writes). Each step is one parallel loop over the chunks of all its systems, one job per thread (section 4).
- Versions: every write tags the chunk's array of that component with the world's version. Each step of systems
runs in a version of its own (newer than every write before it, older than every write after), so a system's
ChunkView::changed<T>()means "written since my last run", and data a system derived is current when its version is greater than its inputs'.end_frame()starts a new version;frame_version()is the first one of the frame. - Component ids: one per type, in the order of first use, in a constant-initialized
std::atomic<u32>per type (no guard on the fast path, so the accessors inline). At most 64 types (the masks areu64). Each binary has its own registry: a game DLL in the editor would number its own types (stable names are #41).
The engine uses it for transforms (Engine/Components/Entity.cpp, Transform.cpp):
game_entity::world()is the game world. Its ids are the entity ids (same 24/8-bit format and reuse rule), soTransformIdis still the entity's id and the script and geometry arrays are still indexed by entity.- Every entity has
transform::Position,Rotation,Scale,LocalFrame,LocalToWorldandWorldToLocal.transform::update()(the scripts' caches, the editor'sSetPosition...) writes the first three; three systems inSystemGroup::transform_updatecompute the rest, each skipping chunks whose inputs didn't change: local frames and world matrices in step 0 (no shared written component), inverses in step 1 (they read the world matrices). - Readers between a write and the next
update_matrices()(get_transform_matrices(),right(), ...) compute the value instead of reading a stale one, without writing, so render preparation may still read from several threads. - The light culler's
get_updated_components_flags()reports a component as changed when its chunk was written in this frame (per chunk, so neighbours may be reported too). Before: changed since the last read. - Component changes from scripts and jobs:
game_entity::queue_add_component<T>()/queue_remove_component<T>(), applied at the sync point after the entity commands.SystemGroup::game_updateruns after the scripts'update()(empty for now: the hook for game systems).
Measured (the "transform phase of 100000 entities" benchmark, every entity changes position and rotation every
frame, Release, the 5900X; before = the arrays of Transform.cpp):
| apply the changes | local frames + matrices | sum | |
|---|---|---|---|
| Before, 1 thread | 1.61-1.64 ms (local frames included) | 1.57-1.59 ms | 3.2 ms |
| ECS, 1 thread | 0.90-0.92 ms | 2.72-2.75 ms | 3.6 ms |
| Before, 24 threads | 1.77-1.85 ms (local frames included) | 0.35-0.38 ms | 2.2 ms |
| ECS, 24 threads | 1.04-1.16 ms (one run 1.38) | 0.67-0.85 ms | 1.8-2.0 ms |
The local frames (1.4 ms of the 100,000 rotations) moved from the single-threaded apply into a system that runs in parallel; world matrices + inverses alone are faster than before (1.28 vs 1.58 ms on one thread). Writing a component of one entity costs about 4 ns against 1 ns for a plain array: the lookup through record, archetype and chunk. In real frames far fewer entities change; when many do, a system (not per-entity writes) is the fast path.
What the prototype taught:
component_id<const T>was a second instantiation with its own id at first, so every query with aconstcomponent matched nothing, and the transform systems never ran (the readers' fallback hid it). The unit tests caught it;const Tnow forwards toT.- A function-local
staticid (a thread-safe guard and a registration call) kept the accessors from inlining: 13 ns per write. The atomic id brought it to 4 ns. - The chunk size doesn't matter for per-entity writes (16, 64 and 256 KB measured the same); it stays 16 KB.
- A derived value written in the same version as its inputs can't tell whether it's current: hence the version per step of systems, and "current" meaning strictly newer.
Checked: UnitTests 159 (11 new in UnitTests/EcsTests.cpp: moves across archetypes and chunks, id reuse,
queries with exclusions, versions, commands from jobs, the scheduler's steps, systems on the job system skipping
unchanged chunks, parallel_each_chunk(), component commands through frame::run(), the transform systems
computing only changed chunks), GraphicsTests 21 with validation and sync validation, clang + GCC (Debug, Release),
ASan/UBSan, ThreadSanitizer, clang-tidy, the source checks; in the Windows VM all 4 configurations and 8 EngineTest
variants, UnitTests Debug (15 runs) and Release, the renderer test on D3D12 and Vulkan. Desktop: plan doc A34.
8. Hierarchy: design proposal (#52 step 1, 2026-11-18)
Status: decided (user, 2026-11-18: every recommendation of 8.7) and implemented (8.8). Decided with #31 (section 5, point 5): a parent component and a transform update ordered by depth, as in Unity DOTS.
8.1 What there is today
- Every entity has
Position,Rotation,Scale(written by scripts through their per-thread caches, by the editor'sSetPosition/..., bytransform::create()), and three derived components:LocalFrame(right, up, front),LocalToWorld,WorldToLocal. Three systems compute the derived ones for chunks whose inputs changed (Transform.cpp,register_systems()), intransform::update_matrices(). - All of it is world space: there are no parents. The renderer reads
get_transform_matrices()(render items), and cameras and lights readentity.position()andentity.front(); the light culler asks which entities changed this frame (get_updated_components_flags()). - The editor's scene is a flat list of entities, and so is
game.bin(load_game()). TransformComponent.halready has an unusedenum class Space { absolute, local, world }and a TODO asking for local/world getters.
8.2 The data
Position,Rotation,Scalebecome relative to the parent (for an entity without a parent, relative to the world, so nothing changes for roots).transform::Parent { game_entity::Entity entity; }, only on entities that have a parent: a reflected component (#41), sogame.binand the editor save it as an entity reference.transform::HierarchyDepth { u16 depth; }next toParent(1 for a child of a root): internal, not reflected (it's derived), maintained when parents change.- Children are a side table, not a component. The ECS has no per-entity variable-size data (components are
plain data in chunks). A table indexed by the entity's index (a small vector of child ids per entity) in the
hierarchy code gives: removing a subtree, updating the depths of a subtree when it moves, and
children(). It changes only at the sync point or between frames, like the structure of the world. LocalToWorld/WorldToLocalstay world space.LocalFrame(right/up/front) becomes the world axes, taken from the rows ofLocalToWorld(normalized: scale is removed), since that's what cameras, lights and scripts mean by "front".
8.3 The update
- Roots (no
Parent): the existing systems, withParentexcluded:LocalToWorldfrom position, rotation and scale, chunk by chunk, skipping unchanged chunks. Unchanged cost for scenes without a hierarchy. - Children, level by level, after the roots:
LocalToWorld = local matrix × parent's LocalToWorld(row vectors, so the parent's matrix is on the right). A level only reads the level above, which is finished, so a level runs in parallel. Two ways to walk the levels (8.7, decision 4):- (a) a depth-sorted list of children, rebuilt at the sync point when the hierarchy changed: each level is a
contiguous range, run with
jobs::parallel_for. Per child: the parent'sLocalToWorld, the child's locals and its ownLocalToWorld, each through an entity lookup (about 4 ns each; one matrix multiply, about 5 ns). - (b) level passes over the chunks with
Parent, skipping rows of other depths: array access for the child's own data, only the parent through a lookup, but every level scans every child chunk. - Not chosen: DOTS's walk per root (recursing into each root's children in one job), since one big hierarchy (a whole level under one root) would then run on one thread.
- (a) a depth-sorted list of children, rebuilt at the sync point when the hierarchy changed: each level is a
contiguous range, run with
- Changes: a child is computed again when its own position, rotation, scale or parent changed (its chunk's
versions), or when its parent's
LocalToWorldis newer than its own (a per-entity check, through the parent's chunk version). A moving parent thus moves its whole subtree, and nothing else is touched. - Then, in parallel:
WorldToLocalandLocalFramefromLocalToWorld(asWorldToLocalis today). - Readers between a write and the next
update_matrices()compute, as today; for a child that means walking up to the root (a fallback, not the hot path).
Scale and parents: the world matrix is the full product, so a non-uniformly scaled parent shears a rotated child
(as in Unity and Unreal). A world scale read back from such a matrix is approximate (Unity's lossyScale).
8.4 Changing the hierarchy
game_entity::set_parent(child, parent, KeepWorld)between frames or at the sync point, andqueue_set_parent()inside a frame (a structural change: adds or removesParent, moves the child to another archetype).parentinvalid detaches. WithKeepWorld::yes(the default; Unity'sworldPositionStays), the child's locals are recomputed so that it doesn't move on screen; withKeepWorld::noits locals stay and it jumps to the new parent's space.- A parent that is the child itself or one of its descendants is refused (logged as an error, the hierarchy stays as it was): checked by walking up from the new parent.
- Removing an entity removes its subtree (decision 3). The children's
end_play()runs before the parent's. EntityInfogets aparentfield, socreate()/queue_create()can make a child directly.- Depth limit:
u16(65,535 levels). Real scenes are far below; a deep chain only costs one level pass per level.
8.5 The API: local and world (decision 1)
Unity and Unreal both make the short name mean world space: Unity position / localPosition, Unreal
GetActorLocation() / GetRelativeLocation(). Proposed, the same:
| world | relative to the parent | |
|---|---|---|
| read | position(), rotation(), scale() (approximate under shear) |
local_position(), local_rotation(), local_scale() |
| write (scripts) | set_position(), set_rotation(), set_scale() |
set_local_position(), set_local_rotation(), set_local_scale() |
| axes | right(), up(), front() (world, as today) |
— |
- Existing script code keeps meaning what it meant (world space), and for an entity without a parent both are the same values.
- A world-space write is turned into a local one when the scripts' caches are applied (
transform::update()), with the parent's current world matrix. When a parent and its child both move in the same frame, the caches are applied parents first (sorted by depth), so the child lands where the script asked. - Cameras and lights keep reading
position()/front(), which now mean world space: right for a camera on a moving player. SpaceinTransformComponent.hgets its meaning, or goes: decided when the API is written (#52 step 4).
8.6 The editor and files (later steps)
- The editor shows and edits local values, as Unity's and Unreal's inspectors do; its scene list becomes a tree,
and dragging an entity onto another parents it (#52 step 5, with #13 for the new editor). Until then EngineDLL gets
SetParent/GetParentexports, so it can be done by hand and tested. game.binstores the parent as an entity reference (theParentcomponent, reflected), with #33 / #52 step 5.
8.7 Decisions for the user
- Names: the short names are world space and
local_*is relative to the parent (recommended; Unity and Unreal), or the short names are local andworld_*is world space. - Reparenting keeps the world transform by default (recommended; the child doesn't jump), or keeps the local values.
- Removing a parent removes its children (recommended; Unity, DOTS), or detaches them to the root, keeping their world transform (Unreal's actors).
- The child update: (a) a depth-sorted list (recommended: no scan per level, simple change checks), or (b) level passes over the chunks. Both get the benchmark of section 7 with hierarchies (wide: 10,000 roots × 9 children; deep: chains of 16); if (a) is slower than expected, (b) is the fallback.
- Scope of step 1: the data, the update,
set_parent/queue_set_parent, the world/local API, removal of subtrees,EntityInfo::parent, the EngineDLL exports, tests and the benchmark (recommended). The editor's tree view andgame.binstay with step 5.
Decided (user, 2026-11-18): 1. world space for the short names, local_* relative to the parent; 2. reparenting keeps
the world transform by default; 3. removing a parent removes its children; 4. the depth-sorted list; 5. the scope
above.
8.8 Implemented (2026-11-18)
- Components (
Engine/Components/Transform.h):transform::Parent(reflected, an entity reference) andtransform::HierarchyDepth(internal);Position/Rotation/Scaleare relative to the parent.ComponentFlags::local_rotation/local_position/local_scalemark a script's or the editor's write as relative to the parent; without them a write is world space. - Update (
transform::update_matrices()): the roots' world matrices (a system that excludesParent), then the children level by level from the depth-sorted list (jobs::parallel_forper level; they write without marking the chunk,ecs::World::write_unmarked(), and the frame thread marks after the level,mark_written(), since threads would race on a chunk's version), then local frames (now from the world matrix) and inverses (SystemGroup::transform_derived). A child is computed when its own values or parent changed since the last update (chunk versions againstWorld::advance_version()'s strict line), or when its parent's matrix was computed in this update (a per-entity flag: a parent and its child often share a chunk, so chunk versions can't tell them apart). - Readers (
get_transform_matrices(),position(),front(), ...) use the stored values when nothing the entity depends on (it and its ancestors) was written since the last update, else compute, walking up. - Changes:
game_entity::set_parent(child, parent, KeepWorld)/queue_set_parent(),EntityInfo::parent,transform::parent_of()/children_of(),Entity::parent();game_entity::remove()removes the subtree, deepest first. Cycles are refused. World-space writes of children are converted with the parent's world transform at the time, parents first (transform::update()sorts by depth). - API:
position()/rotation()/scale()world,local_position()/... relative to the parent (Entityandtransform::Component);EntityScript::set_local_position()/... next to the world-space setters. New math forwardersdecompose()andquat_inverse(). - Editor: EngineDLL
SetParent/GetParentexports; the inspector still shows and sets world values (no tree yet: local values come with the tree view, step 5).RemoveGameEntitynow removes the subtree. - The light culler (
get_updated_components_flags()) reports a child whose world matrix changed this frame (moved with its parent).
Measured (UnitTests "benchmark: hierarchy update of 100000 entities", every root moves every frame, Release,
24 threads, ms per frame for update_matrices()):
| ms | |
|---|---|
| flat, 100,000 roots | 0.61-0.96 |
| wide, 10,000 roots × 9 children | 2.02-2.05 |
| deep, 6,250 chains of 16 | 2.42-2.46 |
The children's pass computes a child in about 28 ns on one thread (90,000 children: 2.5 ms; 1.15 ms on 24 threads, plus 0.36 ms marking the chunks on the frame thread). It scales like the rest of the transform update (the roots: 1.9 ms on one thread, 0.6-0.96 on 24): lookups and memory, not the hierarchy. Option (b) wasn't needed. In real frames only moving parents' subtrees are computed.
Checked: UnitTests 206 (11 new in UnitTests/HierarchyTests.cpp, 1 in MathTests.cpp), clang + GCC,
ThreadSanitizer (the job-system case), ASan/UBSan, clang-tidy, the checks, GraphicsTests 21; MSVC in the VM (4
configurations, UnitTests Debug + Release, the renderer test on D3D12 and Vulkan). Desktop: plan doc A39.
9. Scripts and components (#52 step 2, 2026-11-18)
Status: decided (user, 2026-11-18: every recommendation of 9.8) and implemented (9.10). The question of 9.9 is its own issue, #58 (entity trees from code and prefabs).
9.1 What there is today
- Scripts (
EntityScript,GameScript) run one after another on the frame thread (script::update_scripts()), in the game update phase. - A script reaches only its entity's transform:
set_position()/... go into a per-thread cache (ComponentCache), applied in the transform phase (apply_transform_changes()→transform::update()). Finding an entity's entry searches the cache linearly: O(n) per write, O(n²) per frame (#57; 16-21 ms with 10,000 moving scripts). A script that sets its position and reads it back in the same frame gets the old value. - One script per entity (
game_entitykeeps ascript::Componentper entity index). - No
late_update()orfixed_update(). - The game API (
Engine/EngineAPI/) doesn't include the ECS: game projects can't name a component yet.
9.2 Components from scripts
On game_entity::Entity (so on every EntityScript, and on any entity a script holds):
const Health *health{get<Health>()}; // read; nullptr when the entity has none
if (Health *h{write<Health>()}) { h->value -= 10; } // write: marks the chunk (change detection)
has<Health>();
queue_add_component(Burning{.seconds = 3.f}); // structural: applied at the next sync point
queue_remove_component<Burning>();
- Reads and writes are immediate. That is safe because scripts run one at a time on the frame thread; parallel scripts (later, #1) need another rule (9.6).
- Structural changes (add, remove) are queued, as
game_entity::queue_add_component()already is; the name says so. - A pointer is valid until the next structural change, so for the rest of the frame (changes wait for the sync point).
9.3 Transforms without the cache (#57)
set_position()/set_rotation()/set_scale()and thelocal_*versions write thePosition/Rotation/Scalecomponents directly. A world-space value is converted with the parent's world transform at the time of the write (what Unity does). The per-thread caches, their search andapply_transform_changes()'s apply step go; the transform phase only runsupdate_matrices().- A script now reads back what it just wrote. A child moved in world space by one script, whose parent is moved later in the frame by another, moves with its parent (its local value stays), instead of being kept at the world point: that matches Unity and Unreal, where a world-space write is immediate too.
transform::update(ComponentCache *)stays for EngineDLL (the editor writes batches), now a loop of direct writes.- Expected cost: a lookup per write (about 4 ns) instead of the cache. The existing benchmark ("transform phase of 100000 entities") measures it before and after; #57's 10,000 moving scripts should go from 16-21 ms to well under 1 ms.
9.4 Several scripts per entity
Unity's MonoBehaviours, Unreal's ActorComponents: an entity holds any number of scripts.
- Per entity index, a short list of script ids (a side table, as the children are: scripts are objects, not components).
game_entity::add_script(entity, creator)between frames and at the sync point,queue_add_script()/queue_remove_script()inside a frame;EntityInfo::scripts(several creators) replacesEntityInfo::script.entity.script<FanScript>()finds one by type: through the reflection index every script already has (reflect::detail::type_index<T>), no RTTI (the engine has none on MSVC).scripts()lists them.- Order: an entity's scripts update in the order they were added; entities in the order they were created (as now).
- Lifetime per script as today: constructor,
begin_play()at the next sync point,update(),end_play()when it or its entity goes. An entity's scripts end in reverse order. Entity::script()(onescript::Component) goes; the editor's script list andgame.binlearn several scripts in step 5.
9.5 late_update() and fixed_update()
late_update(dt): after every script'supdate()and the game systems, before the transform phase. For cameras and anything that follows what others moved this frame. It reads current values (writes are immediate now; world values compute until the matrices update).fixed_update(fixed_dt): a fixed time step (say 60 Hz) run 0 or more times per frame, for physics. There is no physics yet; recommended to add it with physics, where the step and its interpolation are designed together.
9.6 Later: scripts in parallel
Not in this step. When scripts run in jobs (#1), immediate writes from several threads race on a chunk's version (the
problem the hierarchy solved with write_unmarked() + mark_written()). Then: writes go to per-thread command
lists applied at a phase boundary, or scripts declare what they write and are scheduled like systems. The API of 9.2
stays; what it does underneath changes.
9.7 The game API
get<T>() and the rest are templates over component types, so the game API needs the ECS's typed header. #31 decided
the typed API is a header that game scripts include (section 5, decision 6), so Engine/ECS/Ecs.h joins the public
set in Tools/check_layers.py, with an EngineAPI declaration of game_entity::world(). Queries and systems for
game code stay step 4 (with the DirectXMath question, #6 decision 3). Game components must be PRIMAL_COMPONENT()
(reflected) for the editor and game.bin; the ECS accepts unreflected ones (step 3's rule).
9.8 Decisions for the user
- Direct transform writes (recommended; fixes #57, values readable at once), or keep the caches and only make their search O(1).
- Component access on
Entityas in 9.2: immediate reads and writes, structural changes namedqueue_*(recommended). - Several scripts per entity, found by type through reflection (recommended).
late_update()now;fixed_update()with physics (recommended), or both now.Ecs.hin the game API now for component access (recommended; #31 decided it's a header for game code), or component access only for engine-side code until step 4.
9.9 The question: building an entity's parts in code (Unreal's CreateDefaultSubobject)
The user asked (2026-11-18) whether a script's constructor can build parts, as Unreal's actors do:
RootScene = CreateDefaultSubobject<USceneComponent>(TEXT("RootScene"));
ParentMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ParentMesh"));
ParentMesh->SetupAttachment(RootScene);
The direction: in Unreal an actor holds a tree of scene components, each with its own transform. Primal's components are data, and an entity has one transform; the tree of transformed parts is child entities (step 1). So Unreal's subobject tree becomes an entity with children, each with its own components (a mesh is a child entity with a geometry component):
// In a script: what Unreal does in the constructor.
const Entity body{create_child({.geometry = &body_mesh})};
const Entity wheel{body.create_child({.position = {1.f, 0.f, 0.f}, .geometry = &wheel_mesh})};
- Where: the constructor runs when the entity is created (between frames or at the sync point), where creating
entities is allowed, so it works there.
begin_play()(also at the sync point) works too. Insideupdate()it would bequeue_create_child()(the child exists from the next frame). - What's missing: a
create_child()helper (today:create()withEntityInfo::parent), named children to find them again (child("Wheel")), and prefabs: Unreal's other half is that those subobjects are defaults of the class, editable in the Blueprint editor and saved. Primal's equivalent is a prefab asset (an entity tree with its components and scripts, made in the editor, instantiated from code or a scene), which needs the editor's tree view andgame.binwith components (step 5, #33). - Proposed: a separate issue, "entity trees from code and prefabs", after step 5:
create_child()and names first (small), prefabs with the editor work.
9.10 Implemented (2026-11-18)
- Direct transform writes:
EntityScript::set_position()/... andset_local_*()calltransform::apply()(one entity's values; a child's world-space values converted with its parent's world transform now). The per-thread caches and their search are gone;apply_transform_changes()only runsupdate_matrices().transform::update(cache, count)stays for EngineDLL's batches (parents first). #57: 10,000 scripts moving their entity, 17.2 ms → 0.32 ms per frame (UnitTests "benchmark: 10000 scripts moving their entity", Release). - Components on
Entity(EngineAPI/GameEntity.h):get<T>(),write<T>()(nullptr without it),has<T>(),queue_add_component(value),queue_remove_component<T>().Engine/ECS/Ecs.his in the game API's public set;game_entity::world()is declared inGameEntity.h.check_layers.pyallows EngineAPI → ECS (the ECS already usedEngineAPI/Reflection.h: a header-level loop, listed for #3). - Several scripts per entity:
game_entity::add_script()/remove_script()andqueue_*versions;EntityInfo::scripts(more scripts afterscript, which stays for the common case: a deviation from 9.4, to keep the 20 single-script call sites and the editor's one-script ABI);Entity::scripts(),Entity::script<T>()(by the reflection index,script::detail::script_type_of()), andscript()is the first one. An entity's scripts end in reverse order. Removing a script moves the game's last script into its place, so the update order holds as added only until scripts are removed (documented; Unity promises no order either). late_update(dt)onEntityScriptandGameScript, in the new frame phaseframe::Phase::late_update(after the game systems, before the transform phase);script::update()(for tests) runs it too.- Checked: UnitTests 211 (5 new in
UnitTests/ScriptComponentTests.cpp), clang + GCC, ASan/UBSan, TSan, clang-tidy, the checks, GraphicsTests; MSVC in the VM (4 configurations, UnitTests Debug + Release, the renderer test on D3D12 and Vulkan). Desktop: plan doc A40.
10. The game API, the editor and game.bin: design proposal (#52 steps 4 and 5, 2026-11-18)
Status: decided (user, 2026-11-18: every recommendation of 10.6); step 4 and the engine side of step 5 are implemented, and the editor side is written and builds but isn't checked yet (10.7). Steps 4 and 5 together, before #3 (user, 2026-11-18).
10.1 The model in one paragraph
An entity has one transform, any number of components (plain data) and any number of scripts (objects); its children are entities of their own (step 1). Several scripts are separate behaviors of one thing; a child is a part that sits or moves somewhere else (a turret on a tank). Unity's model: a GameObject with several MonoBehaviours and child GameObjects. In Unreal's words: our scripts are its ActorComponents, our child entities its SceneComponents (#58 has the Unreal-style construction).
10.2 What there is today
- Game code (
Engine/EngineAPI/, the only folder on a game project's include path,GameEntity.hforce-included): entities (Entity: transform values,parent(), components since step 2,script<T>()), scripts, reflection, input, logging. Missing for game code: creating and removing entities,set_parent, adding scripts (declared in the engine-internalComponents/Entity.h), the entity's children, the init structs (transform::InitInfoand the others are internal), the system groups, removing a system. - Compile cost:
GameEntity.hpreprocesses to about 148,000 lines, 1.0 s of-fsyntax-onlyper game script file (clang); DirectXMath and the SIMD headers are about 48,000 of them (Docs/Math.md). It comes throughTransformComponent.h→Utilities/Math.h→MathSimd.h, for thecalculate_*()functions that returnmath::vec. - game.bin (
load_game()): a count, then per entity a fixed record per component (transform: position, Euler angles, scale; script: a name; geometry: not written yet, #33). No version, no parents, no component values, no script fields. - The editor (WPF,
PrimalEditor/): a flat list of entities per scene, each with aTransform, at most oneScript(by name) and aGeometry; the inspector shows world values. EngineDLL creates entities from a fixedGameEntityDescriptor. - Two engine copies in the editor: EngineDLL and the game DLL each link the engine library. Entities live in
EngineDLL's world; the game's script classes and component types register in the game DLL's own registry
(EngineDLL gets script creators through
primal_get_script_creator()). The game's reflection tables are invisible to EngineDLL today.
10.3 Step 4: the game API
- Entities from game code:
game_entity::queue_create()/queue_remove()/queue_set_parent()/queue_add_script()/queue_remove_script()move into the game API, with the init structs (transform::InitInfo,script::InitInfo,geometry::InitInfo) andEntityInfo. The immediate versions stay engine-internal (game code runs inside frames, where only queued changes are allowed; a script's constructor andbegin_play()run at the sync point, wherecreate()is fine: they get it too, asserted by phase). - The hierarchy for game code:
Entity::children(),Entity::find_script_in_children<T>()(Unity'sGetComponentInChildren). Names (child("Turret")) are #58. - Systems from game code:
game_entity::SystemGroupin the game API; a game system is added in aGameScript'sbegin_play()and removed in itsend_play()(newecs::World::remove_system()), so it lives as long as the game (a reload in the editor removes it with the game code). Queries (world().each<...>()) work already (Ecs.his public since step 2). - DirectXMath out of what every game file sees (#6 decision 3):
calculate_*()return storage types (v3,v4), soTransformComponent.hneeds onlyMathTypes.h.MathSimd.hstays public: game code that computes with SIMD includes it where it needs it. Measured before and after (lines and compile time per file).
10.4 Step 5: the editor and game.bin
- game.bin version 2, written by the editor, read by
load_game():- a header (magic, version), then the entities in parent-before-child order;
- per entity: its parent's index (or none), then its components by name hash with their fields by name hash (type, value), then its scripts by name hash with their reflected fields;
- the transform as its reflected components (
transform::Position,Rotation,Scale; the derived ones are not written); geometry stays out until #33; - read through reflection: an unknown component, script or field is skipped (with a warning), a missing field keeps
its default. A component needs a default value to start from:
TypeInfogets aconstructfunction. - Version 1 files are not read (no backwards compatibility: game projects are rebuilt).
- The editor's C ABI (EngineDLL), UTF-8, values as reflection text (
reflect::value_to_text(), already tested): list the types (name, kind, fields: name, type, min/max, tooltip, enum entries), add/remove a component or script by name, get/set a field of an entity's component or script, set/get the parent. - The game DLL's types in EngineDLL: the game DLL exports its reflection tables (
primal_get_types()); EngineDLL registers them when it loads the game code and unregisters them before it unloads it (a newreflect::unregister_type()). Component fields cross by offset (plain data); script fields by the game DLL's address functions, valid while it's loaded (it creates those scripts anyway). - The editor (WPF) (decision 4 sets how much):
- the scene becomes a tree (drag an entity onto another to parent it, keeping its world transform);
- the inspector shows local values (relative to the parent) and edits them;
- several scripts per entity, added by name and listed;
- a generic field editor driven by the reflection tables: number (with min/max), bool, vectors, enum (a list), entity reference (a picker), string, arrays and lists; it shows and edits script fields and component values;
- the game's components added and removed per entity;
- the project saves all of it (the editor's own
.primalscene files) and writes game.bin version 2.
10.5 Order of work
- Step 4 (engine, Linux): the game API moves,
children(), systems withremove_system(), DirectXMath out of the force-included headers. - Step 5 engine side (Linux):
TypeInfo::construct,unregister_type(), game.bin v2 (a writer in C++ for tests and the reader), the EngineDLL ABI, the game DLL export. - Step 5 editor side (C#, in the Windows VM with
Tools/EditorAutomation): as decision 4 says.
10.6 Decisions for the user
- Game code creates entities and changes the hierarchy only through queued calls inside frames, plus
create()in constructors andbegin_play()(recommended), or queued calls everywhere. - Game systems live from a GameScript's
begin_play()to itsend_play()(recommended), or a registration macro like scripts' (PRIMAL_SYSTEM, registered beforemain(), always on). - DirectXMath out of the force-included headers (recommended:
calculate_*()returnv3/v4,MathSimd.hon request), or leave it in. - How much editor UI now (the WPF editor is to be replaced by the AvaloniaUI one, #13; view models carry over, XAML doesn't):
- game.bin keys components, scripts and fields by name hash (recommended: the same keys as the registry, robust to reordering), or by index into a type table at the start of the file (smaller, but the table holds the names anyway).
10.7 Where it stands (2026-11-19)
Done and checked (2026-11-19: Linux clang + GCC, ASan/UBSan, TSan, clang-tidy, ci.sh checks, header_check,
UnitTests 218, GraphicsTests 21; the VM: all four configurations, UnitTests Debug + Release):
- Step 4 (game API,
children(), game systems from game scripts, DirectXMath out of the force-included headers) and game.bin v2 (content::save_game()/load_game(), keyed by name hash) as in 10.3/10.4. EngineDLL/EditorSupport.h/.cpp(a static libraryEditorSupportin CMake, linked by UnitTests; compiled into EngineDLL and UnitTests in MSBuild):import_types()copies the game DLL's types into EngineDLL's registry (names, fields, enums, a component's default value; component fields by offset; the engine's own types skipped; a reload refreshes the copies in place and refuses a component whose size changed),release_imported_types()before the DLL is freed,types_json(), components and scripts by name, fields as reflection text. Tests:UnitTests/EditorSupportTests.cpp.- EngineDLL exports (
EntityAPI.cpp):GetTypes,GetEntityComponentNames,GetEntityScriptNames,AddComponent/RemoveComponent,AddScript/RemoveScript,Get/SetComponentField,Get/SetScriptField,SaveGame; strings UTF-8, text returned into a caller's buffer (length returned,u32_invalid_idfor none).LoadGameCodeDllimports the types (primal_get_types), unload releases them. Checked in the VM: a game DLL's component and script (with an enum field) come throughGetTypes. The transform exports (Get/SetPosition, ...) now read and write values relative to the parent.
The editor (C#, decision 4a), driven in the VM on 2026-11-19:
Components/ReflectedTypes.cs(the types JSON),Components/ReflectedComponent.cs(ReflectedFieldsComponent: the user's values as reflection text, written to the engine when the entity is created; entity fields kept as the target'sGameEntity.Guid;ReflectedComponent;FieldViewModel;MSReflectedFields<T>),Script.cs(several per entity,EngineIndex),GameEntity.cs(Guid,Parent, tree properties,SyncEngineComponents(), children detached before the engine removes their parent),Scene.cs(depth-first order,SetParent()with undo, removing an entity removes its subtree),Project.cs(SaveGamewrites game.bin; scripts leave the engine before the DLL unloads and come back after, keeping their values;AvailableComponents), the inspector (ReflectedComponentViewreplacesScriptComponentView: text, check box, enum and entity editors, Remove; Add Component > Component), the scene list as a tree (indent, collapse arrow, drag onto an entity to parent, below the list to unparent).- Multi-selection matches components by
Component.Key(scripts by name and order).
What the VM run checked (DebugEditor, the VM's ScriptTest project, Tools/EditorAutomation plus mouse input for
the drags; details in the plan doc, A41): entities with two scripts and the game's Armor component; every field
editor with undo/redo and .max clamping; the tree (parent by drag, unparent, cycle refused, collapse, undo/redo,
removing a subtree and undoing it); a game code rebuild with a new field keeping the values; save + reopen; Run, where
the game's scripts log the values game.bin v2 gave them. Found and fixed: a value the engine refused stayed in the field
(and in the project file) with an undo step; now it's refused (ReflectedFieldsComponent.SetFieldText() returns
false, IsInEngine). Found and fixed on Linux: ContentLoader.cpp (game.bin) uses Log and the ECS, which the layer
table didn't allow yet (Tools/check_layers.py: Content → Core, ECS), and two clang-tidy findings.
Lessons for driving the editor (also at the top of Tools/EditorAutomation/EditorUi.psm1): the window must be maximized (it opens partly
off-screen in the VM, and clicks there miss); selecting an entity is an undo step and clears the redo stack; WPF
re-evaluates Undo/Redo only after real input (move the mouse before invoking them); the ScriptTest headers needed
u32, not primal::u32 (the primitive aliases are global).
Known limits: entity references inside arrays and lists are kept as raw engine ids in the editor (not by Guid), so
they don't survive a reload; numbers, vectors, arrays, lists and strings use a text box with the reflection text format
(1 2 3, [a, b], "text").
Left: the desktop checks (plan doc A41), then #3. The actor model (10.8) was chosen on 2026-11-19 (user): issue #59, Docs/Actors.md.
10.8 Aside: Unreal's actor model (question, 2026-11-18)
Could Primal move to Unreal's split, an actor whose ActorComponents (logic, no transform) are our scripts and whose
SceneComponents (transform, attached in a tree) are our child entities? Moderate, and mostly above the engine core.
The runtime already has the parts: several scripts per entity, a transform hierarchy, children(),
find_script_in_children(). What it would add:
- An owner: a component (
ActorRoot, orOwnedBy{actor}on its parts) so that a subtree is one unit: spawned, removed, saved and copied together, and its parts are not separate things in the outliner. That is #58 (entity trees from code and prefabs) under another name, so most of the cost is shared with it. - Typed scene components: mesh, light, camera, collider as child entities with known components, and a C++ type
per kind with transform accessors (
MeshComponent), created in the actor's constructor (#58'sCreateDefaultSubobject-like construction). - The editor: the outliner lists actors, and the details panel shows the actor's component tree (the tree view made here would be split in two).
What doesn't change: the ECS, game.bin (parts are entities with an owner), reflection, the scripts. The difference from Unreal is that its components are objects with virtual calls; ours stay ECS data, so the data layout and the job system's batching are kept. The current path doesn't close that door: an owner component can be added later.
Decided (user, 2026-11-19): Primal moves to the actor model, before #3 (roadmap #25). Design note:
Docs/Actors.md (editor-first: prefabs, actors with typed parts and behaviors on the ECS; the decisions for the user);
issue #59. #58 moves into it.