EnTT and flecs
You have built a sparse-set ECS and an archetype ECS. For a real project, use a library. The two mature open-source choices in C++ are EnTT (sparse sets, header-only, used in Minecraft's Bedrock Edition) and flecs (archetypes, C core with a C++ API, plus relationships, prefabs, a pipeline and a web-based explorer). Both are MIT licensed.
| EnTT | flecs | |
|---|---|---|
| Storage | sparse sets, optional groups | archetype tables |
| Language | header-only C++ (C++20 for current releases) | C99 core + C++17 API |
| Systems | you write them as functions over views | built in: world.system<...>() with phases |
| Hierarchies | your own components | built-in ChildOf relationship |
| Prefabs | your own | built-in prefabs instantiated with the IsA relationship |
| Extras | signals, dispatcher, resource cache, meta reflection | queries with operators, observers, REST API + Flecs Explorer, modules |
| Install | vcpkg entt, Conan entt, or copy single_include/entt/entt.hpp |
vcpkg flecs, or add distr/flecs.c + flecs.h |
Note: The code below targets current releases (EnTT 3.x/4.x basics, flecs 4.x). Neither library can run on this site, so the snippets are shown as code. Check each project's README when you upgrade: both evolve quickly.
EnTT
The registry creates entities and owns the storage for every component type. A view iterates entities that have all the listed components; mark read-only components const.
#include <entt/entt.hpp>
struct Position { float x, y; };
struct Velocity { float dx, dy; };
struct Health { int hp; };
void movement(entt::registry& registry, float dt) {
auto view = registry.view<Position, const Velocity>();
for (auto [entity, pos, vel] : view.each()) {
pos.x += vel.dx * dt;
pos.y += vel.dy * dt;
}
}
int main() {
entt::registry registry;
const auto player = registry.create();
registry.emplace<Position>(player, 0.0f, 0.0f);
registry.emplace<Velocity>(player, 1.0f, 0.5f);
registry.emplace<Health>(player, 100);
movement(registry, 1.0f / 60.0f);
if (registry.all_of<Health>(player)) {
registry.patch<Health>(player, [](Health& h) { h.hp -= 10; }); // modify + notify listeners
}
if (auto* hp = registry.try_get<Health>(player)) { /* use hp->hp */ }
registry.remove<Velocity>(player); // no-op if missing; erase<T> asserts it exists
registry.destroy(player);
}EnTT's signals let you react to component changes without polling: registry.on_construct<Health>().connect<&onHealthAdded>() calls a free function void onHealthAdded(entt::registry&, entt::entity) every time a Health is emplaced. Its dispatcher is a ready-made version of the event bus:
struct EnemyKilled { entt::entity who; };
void onKilled(const EnemyKilled& e) { /* add score */ }
entt::dispatcher dispatcher{};
dispatcher.sink<EnemyKilled>().connect<&onKilled>();
dispatcher.trigger(EnemyKilled{enemy}); // immediate
dispatcher.enqueue(EnemyKilled{enemy}); // queued...
dispatcher.update(); // ...delivered hereHere is a runnable model of what on_construct/on_destroy do under the hood: each storage owns a list of callbacks, fired inside emplace and destroy.
#include <functional>
#include <iostream>
#include <unordered_map>
#include <vector>
using Entity = unsigned;
template <typename T>
class Storage {
public:
using Listener = std::function<void(Entity)>;
std::vector<Listener> onConstruct, onDestroy;
void emplace(Entity e, T value) {
data_[e] = value;
for (auto& l : onConstruct) l(e);
}
void erase(Entity e) {
if (!data_.count(e)) return;
for (auto& l : onDestroy) l(e); // fired while the component still exists
data_.erase(e);
}
T& get(Entity e) { return data_.at(e); }
private:
std::unordered_map<Entity, T> data_;
};
struct RigidBody { float mass; };
int main() {
Storage<RigidBody> bodies;
int physicsBodies = 0;
// A physics module mirrors every RigidBody into its own world.
bodies.onConstruct.push_back([&](Entity e) { physicsBodies++; std::cout << "physics: create body for " << e << " (mass " << bodies.get(e).mass << ")\n"; });
bodies.onDestroy.push_back([&](Entity e) { physicsBodies--; std::cout << "physics: destroy body for " << e << "\n"; });
bodies.emplace(1, {80});
bodies.emplace(2, {5});
bodies.erase(1);
std::cout << "physics bodies alive: " << physicsBodies << "\n";
}physics: create body for 1 (mass 80)
physics: create body for 2 (mass 5)
physics: destroy body for 1
physics bodies alive: 1
This is how engines keep a third-party system (physics, audio, navigation) in sync with ECS components without every gameplay system remembering to call it.
flecs
In flecs, systems are part of the world. world.progress() runs every system once, in pipeline phase order, and passes the frame's delta time.
#include <flecs.h>
struct Position { float x, y; };
struct Velocity { float x, y; };
int main() {
flecs::world world;
world.system<Position, const Velocity>("Move")
.kind(flecs::OnUpdate)
.each([](flecs::iter& it, size_t, Position& p, const Velocity& v) {
p.x += v.x * it.delta_time();
p.y += v.y * it.delta_time();
});
// Prefabs: in flecs v4 an instance gets its own copy of the prefab's components by default;
// to share one value instead, give the component the (OnInstantiate, Inherit) trait.
flecs::entity Goblin = world.prefab("Goblin").set<Velocity>({1, 0});
flecs::entity g1 = world.entity("g1").is_a(Goblin).set<Position>({0, 0});
// Hierarchies are a built-in relationship.
flecs::entity sword = world.entity("sword").child_of(g1);
// Ad-hoc queries
auto q = world.query<const Position>();
q.each([](flecs::entity e, const Position& p) { /* e.name(), p.x */ });
// Observers react to events such as a component being set.
world.observer<Position>().event(flecs::OnSet).each([](Position& p) { /* ... */ });
while (world.progress(1.0f / 60.0f)) { /* until world.quit() */ }
}Tip: In flecs 4.1,
e.get<T>()returns aconst T&and asserts that the component exists; usee.try_get<T>()for a pointer that may be null. Older tutorials showgetreturning a pointer: check which version a snippet was written for.
The default pipeline phases run in this order: OnLoad, PostLoad, PreUpdate, OnUpdate, OnValidate, PostUpdate, PreStore, OnStore. Inside a phase, systems run in declaration order. A runnable model of that scheduling rule:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
enum Phase { OnLoad, PostLoad, PreUpdate, OnUpdate, OnValidate, PostUpdate, PreStore, OnStore };
const char* phaseName[] = {"OnLoad", "PostLoad", "PreUpdate", "OnUpdate", "OnValidate", "PostUpdate", "PreStore", "OnStore"};
struct System { std::string name; Phase phase; int declared; };
int main() {
std::vector<System> systems;
auto declare = [&](std::string n, Phase p) { systems.push_back({n, p, int(systems.size())}); };
declare("Render", OnStore);
declare("Move", OnUpdate);
declare("ReadInput", OnLoad);
declare("Collide", OnValidate);
declare("Animate", OnUpdate);
declare("UpdateTransforms", PostUpdate);
std::stable_sort(systems.begin(), systems.end(), [](const System& a, const System& b) { return a.phase < b.phase; });
for (const System& s : systems)
std::cout << phaseName[s.phase] << ": " << s.name << " (declared #" << s.declared << ")\n";
}OnLoad: ReadInput (declared #2)
OnUpdate: Move (declared #1)
OnUpdate: Animate (declared #4)
OnValidate: Collide (declared #3)
PostUpdate: UpdateTransforms (declared #5)
OnStore: Render (declared #0)
Picking one
- Choose EnTT if you want a small, unopinionated library and plan to write your own scheduler, hierarchy and editor integration.
- Choose flecs if you want hierarchies, prefabs, a pipeline, reflection and a live inspector (the Flecs Explorer connects to
world.set<flecs::Rest>({})) out of the box. - Either way, wrap the library behind a thin layer only where it buys you something (serialization, editor hooks). Hiding every call "in case we switch" mostly costs time.
Test yourself
Which EnTT call iterates entities that have both Position and Velocity, with Velocity read-only?
registry.query<Position, Velocity>()registry.view<Position, const Velocity>()registry.system<Position, Velocity>()registry.each<Position>()
In flecs, what does world.entity().is_a(Goblin) do when Goblin is a prefab?
- Nothing until the next progress() call
- Makes the entity an instance of the prefab through the IsA relationship, so it starts with the prefab's components
- Makes the entity a child of the prefab
- Deletes the prefab
Which flecs phase runs first in the default pipeline?
- OnUpdate
- PreUpdate
- OnLoad
- OnStore