-
Notifications
You must be signed in to change notification settings - Fork 10
Add ECS #760
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
FakeByte
wants to merge
1
commit into
master
Choose a base branch
from
ecs-proposal
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add ECS #760
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| # OpenVic ECS — user documentation | ||
|
|
||
| This directory documents the archetype-based ECS in `src/openvic-simulation/ecs/`. Only the core infrastructure exists on this branch — no game code has been migrated yet. These docs are usage-focused: they tell you how to write game code *against* the ECS, what each API guarantees, and which rules are load-bearing for performance and lockstep determinism. The terse upstream summary lives at [`ECS.md`](../../ECS.md) in the repo root — read it first; this directory expands it. | ||
|
|
||
| ## The mental model | ||
|
|
||
| - One **`World`** per session owns everything: entity slots, archetypes, chunks, singletons, registered systems, and the scheduler. Game code creates it, populates it, registers systems once, then calls `tick_systems(today)` once per simulation day. | ||
| - An **entity** is a stable handle — `EntityID { index, generation }` — plus the set of plain-struct **components** attached at `create_entity` time. Pre-attach everything the entity will ever need: changing the component set later is an archetype migration per call. | ||
| - Every unique component set is an **archetype**; an archetype stores its entities column-wise in fixed 16 KB **chunks**. That layout is why iteration is fast — and why raw component pointers are short-lived. | ||
| - Per-tick logic lives in **systems**: CRTP structs whose `tick` signature *is* their access declaration (`C const&` = Read, `C&` = Write). Singleton and cross-archetype access must be declared via `extra_reads()` / `extra_writes()` — undeclared access silently breaks determinism. | ||
| - The **scheduler** builds one DAG per World from declared access plus explicit edges/phases, and runs it as a sequence of stages; systems proven conflict-free run in parallel within a stage. | ||
| - Inside a tick, structural mutation through the World is refused — it goes through **`ctx.cmd`** (a `CommandBuffer`) and applies at the stage barrier in a deterministic, worker-count-independent order. | ||
| - Everything serves the **determinism contract**: fixed-point math only, declared access, deterministic reductions, bit-identical results at every worker count, save-stable `EntityID`s, and full-state checksums to prove it. | ||
|
|
||
| ``` | ||
| World ──────────── tick_systems(today), once per simulation day | ||
| │ | ||
| ├─ entities EntityID { index, generation } — stable, save-stable handles | ||
| ├─ archetypes one per unique component set | ||
| │ └─ chunks fixed 16 KB blocks; one contiguous column (slab) per component | ||
| ├─ singletons one value per type, owned by the World, outside all archetypes | ||
| │ | ||
| └─ scheduler one DAG from declared access + edges/phases | ||
| stage 0: SysA ─┐ | ||
| SysB ─┼── run in parallel (proven conflict-free) | ||
| SysC ─┘ | ||
| ═══ stage barrier: each system's CommandBuffer applies ═══ | ||
| stage 1: SysD (observes everything stage 0 created/destroyed) | ||
| ═══ barrier ═══ | ||
| ... | ||
| ``` | ||
|
|
||
| ## Quick start | ||
|
|
||
| A component, a singleton, a system, a session (assembled from [world.md](world.md) and [systems.md](systems.md)): | ||
|
|
||
| ```cpp | ||
| #include "openvic-simulation/ecs/SystemImpl.hpp" // required in the TU that registers systems | ||
| #include "openvic-simulation/ecs/World.hpp" | ||
|
|
||
| using namespace OpenVic::ecs; | ||
| using OpenVic::Date; | ||
|
|
||
| struct Position { | ||
| int32_t x = 0; | ||
| int32_t y = 0; | ||
| }; | ||
|
|
||
| struct Velocity { | ||
| int32_t dx = 0; | ||
| int32_t dy = 0; | ||
| }; | ||
|
|
||
| struct GameClock { | ||
| bool paused = false; | ||
| }; | ||
|
|
||
| // Register at global namespace scope; the string literal is the type's durable identity. | ||
| ECS_COMPONENT(Position, "game::Position") | ||
| ECS_COMPONENT(Velocity, "game::Velocity") | ||
| ECS_COMPONENT(GameClock, "game::GameClock") | ||
|
|
||
| struct MovementSystem : System<MovementSystem> { | ||
| // The tick body reads the GameClock singleton. That access is invisible in the | ||
| // tick signature, so it MUST be declared (see systems.md). | ||
| static constexpr std::array<component_type_id_t, 1> extra_reads() { | ||
| return { component_type_id_of<GameClock>() }; | ||
| } | ||
|
|
||
| void tick(TickContext const& ctx, Position& p, Velocity const& v) { | ||
| GameClock const* clock = ctx.world.get_singleton<GameClock>(); | ||
| if (clock->paused) { | ||
| return; | ||
| } | ||
| p.x += v.dx; | ||
| p.y += v.dy; | ||
| } | ||
| }; | ||
| ECS_SYSTEM(MovementSystem) | ||
|
|
||
| void run_session() { | ||
| World world; | ||
|
|
||
| // Singletons first — never create one mid-tick. | ||
| world.set_singleton<GameClock>(); | ||
|
|
||
| // Pre-attach every component at creation; add_component later means a migration. | ||
| EntityID const mover = world.create_entity(Position { 0, 0 }, Velocity { 1, 2 }); | ||
|
|
||
| world.register_system<MovementSystem>(); | ||
|
|
||
| Date const today { 1836, 1, 1 }; | ||
| for (int day = 0; day < 5; ++day) { | ||
| world.tick_systems(today); | ||
| } | ||
|
|
||
| Position const* p = world.get_component<Position>(mover); | ||
| // p->x == 5, p->y == 10 | ||
| (void) p; | ||
| } | ||
| ``` | ||
|
|
||
| ## Reading order | ||
|
|
||
| | # | Doc | What it covers | | ||
| |---|---|---| | ||
| | 1 | [storage-model.md](storage-model.md) | Archetypes, chunks, columns — the mental model behind every performance rule | | ||
| | 2 | [entities.md](entities.md) | `EntityID`, create/destroy, immutable entities, bulk creation, save-stable ids, `CachedRef` | | ||
| | 3 | [components.md](components.md) | Defining and registering components, tags, singletons, checksum rules, `DenseSlotAllocator` | | ||
| | 4 | [world.md](world.md) | `World` API reference: lifecycle, iteration, singletons, identity snapshots / save-load | | ||
| | 5 | [queries.md](queries.md) | Building a `Query`, the `for_each` family, system `Filters`, the query cache | | ||
| | 6 | [systems.md](systems.md) | Writing `System` / `SystemThreaded` / `ChunkSystem`, access declarations, `should_run`, `TickContext` | | ||
| | 7 | [scheduling.md](scheduling.md) | Stages, conflict resolution, explicit edges, phases, `schedule_hash` | | ||
| | 8 | [command-buffer.md](command-buffer.md) | Deferred structural mutation from inside system ticks | | ||
| | 9 | [threading-and-reductions.md](threading-and-reductions.md) | What is safe in parallel, `EcsThreadPool`, deterministic `reductions::*` folds | | ||
| | 10 | [determinism.md](determinism.md) | The lockstep contract: rules, checksums, worker-count invariance | | ||
| | 11 | [pitfalls.md](pitfalls.md) | The consolidated rules and footguns list — read last, re-read often | | ||
|
|
||
| ## Build and test | ||
|
|
||
| ```powershell | ||
| scons # build sim library + headless | ||
| scons run_ovsim_tests=yes # build & run unit tests (snitch) | ||
| ``` | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.