An Archetype ECS
A sparse set stores each component type on its own. An archetype ECS stores entities grouped by their exact set of components. Every entity that has exactly Position + Velocity lives in one table; every entity with Position + Velocity + Health lives in another. Each table (the archetype) has one column per component, and row i of every column belongs to the same entity.
Archetype {Position, Velocity} Archetype {Position, Velocity, Health}
row | entity | Position | Velocity row | entity | Position | Velocity | Health
0 | 3 | (0, 0) | (1, 0) 0 | 1 | (2, 2) | (0, 1) | 100
1 | 8 | (4, 1) | (0, -1) 1 | 6 | (7, 0) | (1, 1) | 60Unity's Entities package (DOTS), flecs, Bevy and Unreal's Mass all work this way. The payoff: a query for Position + Velocity finds the matching tables once and then walks their columns in lockstep, with no per-entity contains check and no random lookups. The cost: adding or removing a component moves the entity to a different table.
Signatures and matching
Give each component type a small integer ID and an archetype's signature becomes a bitmask. A query matches an archetype when (archetype.mask & query.mask) == query.mask.
#include <bitset>
#include <iostream>
#include <string>
#include <vector>
constexpr int kMaxComponents = 8;
using Mask = std::bitset<kMaxComponents>;
enum Component { Position, Velocity, Health, Player, Sprite };
const char* names[] = {"Position", "Velocity", "Health", "Player", "Sprite"};
Mask maskOf(std::initializer_list<Component> list) {
Mask m;
for (Component c : list) m.set(c);
return m;
}
std::string describe(Mask m) {
std::string s = "{";
for (int i = 0; i < 5; i++) if (m.test(i)) s += (s.size() > 1 ? ", " : "") + std::string(names[i]);
return s + "}";
}
int main() {
std::vector<Mask> archetypes = {
maskOf({Position, Sprite}),
maskOf({Position, Velocity, Sprite}),
maskOf({Position, Velocity, Health, Sprite}),
maskOf({Position, Velocity, Health, Player, Sprite}),
};
Mask moving = maskOf({Position, Velocity});
Mask damageable = maskOf({Health});
for (Mask a : archetypes) {
std::cout << describe(a) << " bits=" << a
<< " moving:" << ((a & moving) == moving)
<< " damageable:" << ((a & damageable) == damageable) << "\n";
}
}{Position, Sprite} bits=00010001 moving:0 damageable:0
{Position, Velocity, Sprite} bits=00010011 moving:1 damageable:0
{Position, Velocity, Health, Sprite} bits=00010111 moving:1 damageable:1
{Position, Velocity, Health, Player, Sprite} bits=00011111 moving:1 damageable:1
In a real game there are usually tens to a few hundred archetypes, but many thousands of entities. Engines cache the list of matching archetypes per query and update it only when a new archetype appears.
A working archetype ECS
The version below stores columns as raw byte vectors, so one Archetype type can hold any components. Components must be trivially copyable here (moves use memcpy); real libraries call constructors and destructors through per-type function tables.
#include <bitset>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <type_traits>
#include <vector>
constexpr int kMax = 32;
using Mask = std::bitset<kMax>;
using Entity = std::uint32_t;
inline int nextComponentId = 0;
inline std::size_t componentSizes[kMax];
template <typename T> int componentId() {
static_assert(std::is_trivially_copyable_v<T>);
static const int id = [] { componentSizes[nextComponentId] = sizeof(T); return nextComponentId++; }();
return id;
}
struct Column {
std::size_t elemSize = 0;
std::vector<std::byte> bytes;
void* at(std::size_t row) { return bytes.data() + row * elemSize; }
void push(const void* src) { bytes.resize(bytes.size() + elemSize); std::memcpy(at(bytes.size() / elemSize - 1), src, elemSize); }
void swapRemove(std::size_t row) {
std::size_t last = bytes.size() / elemSize - 1;
if (row != last) std::memcpy(at(row), at(last), elemSize);
bytes.resize(bytes.size() - elemSize);
}
};
struct Archetype {
Mask mask;
int columnOf[kMax]; // component id -> column index, -1 if absent
std::vector<Column> columns;
std::vector<Entity> entities;
explicit Archetype(Mask m) : mask(m) {
for (int id = 0; id < kMax; id++) {
columnOf[id] = -1;
if (m.test(id)) { columnOf[id] = int(columns.size()); columns.push_back(Column{componentSizes[id], {}}); }
}
}
};
struct Record { std::size_t archetype, row; };
class World {
public:
World() { archetypes_.emplace_back(Mask{}); } // archetype 0: no components
Entity create() {
Entity e = Entity(records_.size());
records_.push_back({0, archetypes_[0].entities.size()});
archetypes_[0].entities.push_back(e);
return e;
}
template <typename T> void add(Entity e, const T& value) {
int id = componentId<T>();
Record rec = records_[e];
Mask target = archetypes_[rec.archetype].mask; target.set(id);
std::size_t dst = findOrCreate(target);
Archetype& from = archetypes_[rec.archetype];
Archetype& to = archetypes_[dst];
for (int c = 0; c < kMax; c++) // copy the components it already had
if (from.columnOf[c] >= 0) to.columns[to.columnOf[c]].push(from.columns[from.columnOf[c]].at(rec.row));
to.columns[to.columnOf[id]].push(&value);
to.entities.push_back(e);
removeRow(rec.archetype, rec.row);
records_[e] = {dst, to.entities.size() - 1};
moves_++;
}
template <typename T> T& get(Entity e) {
Record r = records_[e];
Archetype& a = archetypes_[r.archetype];
return *static_cast<T*>(a.columns[a.columnOf[componentId<T>()]].at(r.row));
}
// Query: fn(A*, B*, count) is called once per matching archetype with its raw columns.
template <typename A, typename B, typename Fn> int query(Fn fn) {
Mask want; want.set(componentId<A>()); want.set(componentId<B>());
int matched = 0;
for (Archetype& a : archetypes_) {
if ((a.mask & want) != want || a.entities.empty()) continue;
matched++;
fn(static_cast<A*>(a.columns[a.columnOf[componentId<A>()]].at(0)),
static_cast<B*>(a.columns[a.columnOf[componentId<B>()]].at(0)), a.entities.size());
}
return matched;
}
std::size_t archetypeCount() const { return archetypes_.size(); }
int moves() const { return moves_; }
private:
std::size_t findOrCreate(Mask m) {
for (std::size_t i = 0; i < archetypes_.size(); i++) if (archetypes_[i].mask == m) return i;
archetypes_.emplace_back(m);
return archetypes_.size() - 1;
}
void removeRow(std::size_t arch, std::size_t row) {
Archetype& a = archetypes_[arch];
for (Column& c : a.columns) c.swapRemove(row);
Entity moved = a.entities.back();
a.entities[row] = moved;
a.entities.pop_back();
if (row < a.entities.size()) records_[moved].row = row;
}
std::vector<Archetype> archetypes_;
std::vector<Record> records_;
int moves_ = 0;
};
struct Position { float x, y; };
struct Velocity { float x, y; };
struct Health { int hp; };
int main() {
World world;
for (int i = 0; i < 6; i++) {
Entity e = world.create();
world.add(e, Position{float(i), 0});
if (i % 2 == 0) world.add(e, Velocity{1, 0.5f});
if (i >= 3) world.add(e, Health{100});
}
std::cout << "archetypes: " << world.archetypeCount() << ", entity moves: " << world.moves() << "\n";
// System: movement over every archetype that has Position and Velocity.
int matched = world.query<Position, Velocity>([](Position* p, Velocity* v, std::size_t n) {
for (std::size_t i = 0; i < n; i++) { p[i].x += v[i].x * 2; p[i].y += v[i].y * 2; }
});
// System: poison everything with Position and Health.
world.query<Position, Health>([](Position*, Health* h, std::size_t n) { for (std::size_t i = 0; i < n; i++) h[i].hp -= 15; });
std::cout << "movement matched " << matched << " archetypes\n" << std::fixed << std::setprecision(1);
for (Entity e = 0; e < 6; e++) {
Position& p = world.get<Position>(e);
std::cout << "entity " << e << ": (" << p.x << ", " << p.y << ")";
if (e >= 3) std::cout << " hp " << world.get<Health>(e).hp;
std::cout << "\n";
}
}archetypes: 5, entity moves: 12
movement matched 2 archetypes
entity 0: (2.0, 1.0)
entity 1: (1.0, 0.0)
entity 2: (4.0, 1.0)
entity 3: (3.0, 0.0) hp 85
entity 4: (6.0, 1.0) hp 85
entity 5: (5.0, 0.0) hp 85
Building six entities one component at a time caused a lot of entity moves: every add copies the entity into a new table. That is the main cost of archetypes, and it is why libraries offer ways to create an entity with all its components at once (flecs insert, Unity EntityManager.CreateEntity(archetype)) and why toggling a component every frame is a bad idea. Use an enabled flag inside the component, or the library's enable/disable feature, instead.
Systems and schedules
A system is a query plus a function, and the engine runs systems in a fixed order every frame. A minimal scheduler is a list:
struct System { const char* name; void (*run)(World&, float dt); };
std::vector<System> schedule = {
{"input", inputSystem},
{"movement", movementSystem},
{"damage", damageSystem},
{"render", renderExtractSystem},
};
for (auto& s : schedule) s.run(world, dt);Because each system declares which components it reads and writes, a smarter scheduler can run movement and an unrelated animation system in parallel. That is the idea behind the task graph.
Sparse sets vs archetypes
| Sparse set (EnTT) | Archetype (flecs, Unity DOTS, Bevy) | |
|---|---|---|
| Add/remove component | O(1), nothing moves | moves the entity's whole row to another table |
| Multi-component query | walk smallest pool, check the rest | walk matching tables, columns in lockstep |
| Memory layout of one entity | spread over pools | contiguous row across columns of one table |
| Good fit | many structural changes, tag components | big, stable populations iterated every frame |
Both are fast enough for nearly every game. Choose the library you like to use, and keep structural changes (add/remove) out of the hottest loops in either case.
Test yourself
In an archetype ECS, what happens when you add a component to an existing entity?
- Only a bit flag is set
- The entity's data moves to the table for its new component set
- The component is appended to a global pool
- Nothing until the next frame
Query mask {Position, Velocity} against archetype mask {Position, Velocity, Health}: does it match?
- Yes, because the archetype contains every queried component
- No, because the masks are not equal
- Only if Health is read-only
- Only for the first row
Why should you avoid adding and removing a component every frame in an archetype ECS?
- It leaks memory
- Each change copies the entity between tables, which is expensive at scale
- Queries stop matching
- Components lose their values