ecs
Entities, the components each has, and the systems that pass over them: a world keeping entities with the same set of components together, a column for each component, so a pass over those having some components is a walk along arrays, as fast as a loop over arrays of one's own. It's Sakura's, built with blossom, and reads only std.
import ecs;
struct position { var x: f32; var y: f32; }
struct velocity { var x: f32; var y: f32; }
struct asleep {} # a tag: a component holding nothing
var w := world::new();
val ball := w.spawn_with(position{}, velocity{ x = 1 });
w.add::<asleep>(w.spawn_with(position{ x = 5 }));
# Each entity having what the function takes, `&T` to read, `&mut T` to write.
w.each(def(p: &mut position, v: &velocity) {
p.x += v.x;
p.y += v.y;
});
# A filter says what the function doesn't take.
w.query(without::<asleep>()).each(def(e: entity, p: &position) { ... });
# Chunks: a table's entities at once, each component a column, for loops of one's own.
for c in w.query(with::<position>().with::<velocity>()).chunks() {
val ps := c.write::<position>();
val vs := c.read::<velocity>();
for i in 0..c.length { ps[i].x += vs[i].x; }
}
# On every processor.
w.par_each(def(p: &mut position, v: &velocity) { p.x += v.x; });
if w.get::<position>(ball) is some(&mut p) { p.y = 10; }
w.set(ball, velocity{ y = -1 }); # replaces the one it has
_ = w.remove::<velocity>(ball);
_ = w.despawn(ball);
tests/ecs.sakura drives all of it, and tools/bench.sakura times it.
A project reads it by requiring this folder, or its remote, and naming ecs among a target's deps:
requires:
- ../ecs
targets:
- name: game
type: program
deps: [ecs]
Layout
| Path | Holds |
|---|---|
ecs/ecs.sakura |
entity, and component_info, what a world knows of a type of component |
ecs/world.sakura |
world: spawning and despawning, giving, replacing, taking, and getting components, deferring, apply, and resources |
ecs/table.sakura |
Tables: the entities having one set of components, a column of each component's values |
ecs/query.sakura |
Filters, queries, the parameters each reads, and chunks |
ecs/each.sakura |
The passes each and par_each make, one for each number of parameters a function takes, up to 8 |
ecs/workers.sakura |
The threads par_each calls functions on |
ecs/commands.sakura |
commands: changes to what entities have, made later |
ecs/schedule.sakura |
schedule: systems run in order, each timed, and taken out by name |
ecs/keys.sakura |
Components and resources reached by their types' keys, as a program does for scripts |
ecs/serial.sakura |
How std::serial writes and reads an entity, and entity_numbering, the numbers a program writes entities as in data of its own |
ecs/idmap.sakura |
The table of numbers by 64-bit keys a world looks things up in |
How it works
- Tables: a world keeps its entities in tables, one for each set of components an entity has had, its archetype, each component a column of values in the entities' order, and a tag, a component of no size, no column at all. Despawning an entity, or moving it to another table, moves the table's last entity into its place, so the rows stay side by side. An entity gaining or losing a component moves to the table having its new set, which each table remembers by the component, so the move is found once, and
spawn_withmoves an entity into the table of all its components at once, which it remembers by their types. - Components are values of any type. What closes, as a
string, is closed as its entity loses it, is despawned, or the world closes, and moved byte for byte between tables otherwise. Each type is known by a hash of itspath_of, its name with the module of each type it names, made while compiling, the same in every program, sogame::positionandai::positionare two components. eachcalls a function for each entity having the components it takes. Its parameters say what it passes over:&Treads a component, and&mut Twrites one, which the entity must have;maybe<&T>andmaybe<&mut T>take one it may lack; andentitytakes the entity; in any order, up to 8. Its lambda is written with its parameters' types.- Queries:
w.query(filter)is a pass over the entities a filter passes, by components they have,with, or lack,without, besides those its function takes. What a pass asks the world works out once and keeps, with the tables it matches, which it brings up to date as tables are made, so a pass walks straight to the columns. - What changed: a filter's
changed::<T>()passes the tables whoseTwas written since its query last passed, as a pass taking&mut T, a chunk'swrite, orset, writes them: a table passes whole where any of its entities was written. A query remembers when it last passed, so a system keeps its query from one run to the next; a new one finds every table changed. - Deferring: while a pass goes over the world, what would move an entity, a component given that it lacks or taken, a spawn, or a despawn, is kept, and made as the outermost pass ends, so the tables a pass walks stay as they are. A component an entity has already is replaced where it is, at once.
commandskeep changes the same way, for a program toapplywhen it's ready; a change to an entity despawned first is dropped, its value closed. par_eachcalls its function from several threads at once: the world's, and workers, one for each processor more, started as it's first called and waiting until the world closes. The rows of the tables it matches are cut into pieces, several for each thread, which each takes in turn, so those finishing first take more; a pass of fewer than 4,096 entities stays on the world's thread. The function writes only what it's given; it may replace components an entity has, and defer what would move one, but not spawn, query, or pass over the world itself, which fault.world::threadssays how many threads it uses.- Resources are values of a type a world holds one of, apart from any entity, as a clock:
set_resource,resource, andremove_resource. - Schedules run systems, functions of the world or types of one's own with an
invoketaking it, in the order they were added, timing each, whichtimingstells;removetakes out those of a name. - Keys:
get_by_key,has_by_key,set_by_info,remove_by_key,resource_by_key, andentities_by_keyreach components by their types' keys,component_key::<T>(), rather than their types, as an engine does for the scripts it runs, which declare types it doesn't: a key, and the bytes of a value, laid out as both sides build the type from one declaration.component_info::plainmakes what a world knows of a type of plain data as the program runs, which must outlast every world meeting it. - Written and read: an
entityisstd::serial's to write and read, as a component naming one is. Its bits name it only in its own world while the program runs, so a program writing a world as data of its own, as a scene file, gives each entity a number there in anentity_numbering, andapplywrites and reads every entity by it until what it gives closes: an entity as its number, or as nothing where it has none, as one despawned, and a number read as the entity it names, which must name one. With none applied, an entity is written as its bits.entity::noneis nothing either way.
Speed
blossom run ecs.bench over a million entities of two components, built with -O2, on a Ryzen 9 9950X3D of 16 cores and 32 threads, its passes each over 36 MB, which its 128 MB of L3 holds:
| What | Time for each entity |
|---|---|
| A loop over plain vectors | 1.63 ns |
| A loop over a query's chunks | 1.20 ns |
each, given a type of one's own with an invoke |
1.20 ns |
each, given a lambda |
1.95 ns |
each, over 67 tables |
1.95 ns |
par_each, on 32 threads |
0.28 ns |
spawn_with of two components |
27 ns |
get, in the order they were spawned |
5.9 ns |
get, in no order |
20 ns |
set of a component the entity has |
16 ns |
| A move to another table, as a tag is added or removed | 50 ns |
despawn |
25 ns |
each adds nothing to the loop it makes: given a type of its own, it's as fast as chunks. A lambda costs a call through its address for each entity, 0.75 ns here, as Sakura calls a lambda given to generic code, where a type's invoke is inlined; a hot pass gives a type, or walks chunks. A pass this light is bound by memory, which par_each's threads share, so heavier work gains more from them.
Testing
blossom test runs tests/ecs.sakura: entities and their generations, components given, replaced, taken, and moved between tables, what closes closed once, passes of every kind of parameter, filters, deferring, chunks, what changed, passes on four threads, resources, commands, schedules, components of one name in two modules, components reached by their types' keys, and entities written and read by a numbering. sakurac run --checks runs them with every read and write checked, and reports nothing left unreleased.
Not yet
Relationships between entities, which a program keeps of its own, as hearth's scenes keep parents and children; hooks run as a component is given or taken; the tables a world no longer uses given back; what changed known of each entity rather than each table; systems run on several threads at once by what they read and write, rather than each pass on several; and saving a world whole, which each type's key was made for, and its entities' numbering is the start of.