Files
ecs/ecs/world.sakura
T
2026-10-30 06:25:53 -05:00

728 lines
23 KiB
Plaintext

#! Contains `world`: entities, the components each has, and the resources the
#! world holds apart from any entity.
import system;
module ecs;
# Where an entity is.
struct record {
var table: u32; # Its table; `absent` where its index is free, or `pending` where it was spawned while the world deferred.
var row: u32; # Its row; while its index is free, the next free index, or `absent`.
var generation: u32;
}
# A record's table where its entity was spawned while the world deferred, and
# is in no table until the world stops.
const pending: u32 = 0xFFFFFFFD;
# One value of a type, which the world holds apart from any entity.
struct resource {
var info: *component_info;
var data: *mut u8; # Or `null` where it was removed.
}
#! Entities, and the components each has.
#!
#! Entities with the same set of components are kept together, in a table
#! whose columns are their components, so a pass over the entities having some
#! components walks along the columns of the tables having them. An entity
#! gaining or losing a component moves to the table having its new set, which
#! each table remembers, so the move is found once.
#!
#! While a query passes over it, the world defers what would move an entity:
#! components given or taken, spawns, and despawns are kept, and made as the
#! outermost pass ends, so the tables a pass walks stay as they are. A value an
#! entity has already is replaced where it is, at once.
#!
#! Several threads pass over it at once while it's shared, from `begin_sharing`
#! to `end_sharing`, as an engine runs systems reaching different components.
pub struct world : owning {
var records: vector<record>;
var free: u32; # The first free index, or `absent`.
var living: u64;
var infos: vector<*component_info>; # Of each component, by its id.
var by_key: idmap; # Ids by the types' keys.
var tables: vector<table>; # The first holds the entities with no components.
var by_hash: idmap; # The first table of each hash of components.
var bundles: idmap; # Tables by the types `spawn_with` was given.
var queries: vector<box<query_state>>; # Each where it stays, as a pass keeps its address.
var cached: idmap; # Queries by the hash of what they ask.
var deferring: u32; # How many passes are going on, and whether it's shared.
var pending: commands; # What the passes deferred.
var tick: atomic<u64>; # Counts passes and changes, for `changed`.
var resources: vector<resource>;
var by_resource: idmap;
var crew: workers;
var parallel: bool; # Whether `par_each` is calling functions on several threads.
var sharing: bool; # Whether threads share it, between `begin_sharing` and `end_sharing`.
var guard: atomic<u32>; # Held while a thread defers a change or finds a query, as `parallel` or `sharing` is.
}
#! A world with no entities.
pub def world::new(): world {
var made := world{
records = vector::<record>::new(),
free = absent,
infos = vector::<*component_info>::new(),
by_key = idmap::new(),
tables = vector::<table>::new(),
by_hash = idmap::new(),
bundles = idmap::new(),
queries = vector::<box<query_state>>::new(),
cached = idmap::new(),
pending = commands::new(),
resources = vector::<resource>::new(),
by_resource = idmap::new(),
crew = workers::new(),
};
val none := span::<u32>::empty();
_ = made.make_table(none, hash_ids(none));
return made;
}
#! Closes every component and resource it holds.
pub def world::close(&mut this): void {
this.crew.close();
this.pending.close();
for i in 0..this.resources.length {
val held := &mut this.resources[i];
if held.data != null {
if held.info[0].closes {
held.info[0].dispose(held.data);
}
raw_release(held.data);
held.data = null;
}
}
this.resources.close();
this.by_resource.close();
this.tables.close();
this.by_hash.close();
this.bundles.close();
this.queries.close();
this.cached.close();
this.infos.close();
this.by_key.close();
this.records.close();
}
#! How many entities are alive.
pub val world::count: u64 {
get => this.living;
}
#! How many tables it keeps entities in: one for each set of components an
#! entity has had.
pub val world::archetypes: u64 {
get => this.tables.length;
}
# Entities.
#! Spawns an entity with no components.
pub def world::spawn(&mut this): entity {
val e := this.new_entity();
if this.deferring > 0 {
this.defer(op::place, e, null);
} else {
this.place(e);
}
return e;
}
#! Spawns an entity with components, which it moves into their table at once,
#! rather than through one table for each, as giving them one at a time would.
pub def world::spawn_with<Ts...>(&mut this, components: Ts...): entity {
val e := this.new_entity();
if this.deferring > 0 {
this.defer(op::place, e, null);
for const c in components {
this.defer_put(e, info_of_value(&c), &mut c as *mut u8);
emptied(&mut c);
}
return e;
}
# The table of a set of types is kept by the sum of their keys' hashes, which
# their order doesn't change, so it's found once.
var bundle := 0u;
for const c in components {
bundle += mixed(info_of_value(&c)[0].key);
}
var to := this.bundles.get(bundle);
if to == absent {
var ids: u32[32];
var count := 0u;
for const c in components {
if count == 32 {
fault("`spawn_with` takes at most 32 components.");
}
ids[count] = this.id_of(info_of_value(&c));
count++;
}
to = this.table_of_unsorted(&mut ids, count);
this.bundles.set(bundle, to);
}
val row := this.tables[to as u64].push(e);
val r := &mut this.records[e.index as u64];
r.table = to;
r.row = row as u32;
val now := this.stamp();
val t := &mut this.tables[to as u64];
for const c in components {
val slot := t.slot_of(this.find_id(info_of_value(&c)));
if slot != tagged {
place(t.at(slot, row), &mut c);
t.columns[slot as u64].changed = now;
}
}
return e;
}
# The table of a set of components, put in order first. `spawn_with` gives it
# their ids rather than its pack, which, passed on, would move its values here.
def world::table_of_unsorted(&mut this, ids: &mut u32[32], count: u64): u32 {
for i in 1..count {
var j := i;
while j > 0 && ids[j - 1] > ids[j] {
val swap := ids[j];
ids[j] = ids[j - 1];
ids[j - 1] = swap;
j--;
}
if j > 0 && ids[j - 1] == ids[j] {
fault($"`spawn_with` was given two of `{this.infos[ids[j] as u64][0].path}`.");
}
}
val set: span<u32> = ids[0:count];
return this.table_of(set);
}
#! Despawns an entity, closing its components.
#! @returns Whether it was alive.
pub def world::despawn(&mut this, e: entity): bool {
return false if !this.alive(e);
if this.deferring > 0 {
this.defer(op::despawn, e, null);
} else {
this.despawn_now(e);
}
return true;
}
#! Whether an entity is alive: spawned by this world, and not despawned.
pub def world::alive(&this, e: entity): bool {
val index := e.index as u64;
return index < this.records.length && this.records[index].generation == e.generation
&& this.records[index].table != absent;
}
# An entity's index and generation, in no table yet.
def world::new_entity(&mut this): entity {
if this.parallel {
fault("A function `par_each` calls can't spawn entities: spawn them after.");
}
if this.sharing {
this.refuse_while_shared("spawn entities");
}
this.living++;
if this.free != absent {
val index := this.free;
val r := &mut this.records[index as u64];
this.free = r.row;
r.table = pending;
r.row = 0;
return entity::of(index, r.generation);
}
val index := this.records.length as u32;
this.records.append(record{ table = pending, row = 0, generation = 1 });
return entity::of(index, 1);
}
# Puts an entity in the table of no components.
def world::place(&mut this, e: entity): void {
val row := this.tables[0].push(e);
val r := &mut this.records[e.index as u64];
r.table = 0;
r.row = row as u32;
}
def world::despawn_now(&mut this, e: entity): void {
val r: record = this.records[e.index as u64];
if r.table != pending {
val t := &mut this.tables[r.table as u64];
t.close_row(r.row as u64);
val moved := t.take_out(r.row as u64);
if moved != entity::none {
this.records[moved.index as u64].row = r.row;
}
}
val freed := &mut this.records[e.index as u64];
freed.table = absent;
freed.generation = freed.generation == 0xFFFFFFFF ? 1 : freed.generation + 1;
freed.row = this.free;
this.free = e.index;
this.living--;
}
# Components.
#! Gives an entity a component, or replaces the one it has. Where a query is
#! passing over the world, a component the entity lacks is given as the pass
#! ends.
pub def world::set<T>(&mut this, e: entity, value: T): void {
if !this.alive(e) {
fault($"`set` was given {e.show()}, which isn't alive.");
}
val info := info_of::<T>();
val r: record = this.records[e.index as u64];
val id := this.find_id(info);
if id != absent && r.table != pending {
val t := &mut this.tables[r.table as u64];
val slot := t.slot_of(id);
if slot != absent {
# It has one, which the value replaces where it is, closing it.
if slot != tagged {
through(t.at(slot, r.row as u64) as *mut T) = move(value);
t.columns[slot as u64].changed = this.stamp();
}
return;
}
}
if this.deferring > 0 {
this.defer_put(e, info, &mut value as *mut u8);
emptied(&mut value);
return;
}
if r.table == pending {
this.place(e);
}
val at := this.add_now(e, this.id_of(info));
if at != null {
place(at, &mut value);
}
}
#! Gives an entity a component's zero value where it lacks one, as a tag is
#! given.
pub def world::add<T>(&mut this, e: entity): void where T: zeroable {
return if this.has::<T>(e);
var zero: T;
this.set(e, move(zero));
}
#! Takes a component from an entity, closing it.
#! @returns Whether the entity had it.
pub def world::remove<T>(&mut this, e: entity): bool {
val id := this.find_id(info_of::<T>());
return false if !this.has_id(e, id);
if this.deferring > 0 {
this.defer(op::remove, e, info_of::<T>());
} else {
this.remove_now(e, id);
}
return true;
}
#! Whether an entity has a component.
pub def world::has<T>(&this, e: entity): bool {
return this.has_id(e, this.find_id(info_of::<T>()));
}
#! An entity's component, where it has one. A tag has nothing to lend, which
#! `has` asks of instead.
#! @remarks The reference lasts until the entity next moves, as it gains or
#! loses a component, or another in its table is despawned.
pub def world::get<T>(&mut this, e: entity): maybe<&mut T> {
val at := this.value_of(e, this.find_id(info_of::<T>()));
return nothing{} if at == null;
return maybe::<&mut T>{ some = through(at as *mut T) };
}
#! An entity's component, where it has one, to read.
pub def world::get<T>(&this, e: entity): maybe<&T> {
val at := this.value_of(e, this.find_id(info_of::<T>()));
return nothing{} if at == null;
return maybe::<&T>{ some = through(at as *T) };
}
#! The names of an entity's components, in the order its table holds them, as
#! `game::position, game::velocity`.
pub def world::describe(&this, e: entity): string {
var text := string::from("", nothing{});
return text if !this.alive(e);
val r: record = this.records[e.index as u64];
return text if r.table == pending;
val t := &this.tables[r.table as u64];
for i in 0..t.ids.length {
if i > 0 {
text.append(", ");
}
text.append(this.infos[t.ids[i] as u64][0].path);
}
return text;
}
def world::has_id(&this, e: entity, id: u32): bool {
return false if id == absent || !this.alive(e);
val r: record = this.records[e.index as u64];
return r.table != pending && this.tables[r.table as u64].has(id);
}
# Where an entity's value of a component is, or `null` where it has none, or
# it's a tag.
def world::value_of(&this, e: entity, id: u32): *mut u8 {
return null if id == absent || !this.alive(e);
val r: record = this.records[e.index as u64];
return null if r.table == pending;
val t := &this.tables[r.table as u64];
val slot := t.slot_of(id);
return null if slot >= tagged;
return t.at(slot, r.row as u64);
}
# Gives a living entity a component, or replaces the one it has, moving the
# value's bytes in, which the caller lets go of.
def world::set_bytes(&mut this, e: entity, info: *component_info, from: *mut u8): void {
val id := this.id_of(info);
val r: record = this.records[e.index as u64];
if r.table != pending {
val t := &mut this.tables[r.table as u64];
val slot := t.slot_of(id);
if slot != absent {
if slot != tagged {
val at := t.at(slot, r.row as u64);
if info[0].closes {
info[0].dispose(at);
}
memcpy(at, from, info[0].size);
t.columns[slot as u64].changed = this.stamp();
}
return;
}
} else {
this.place(e);
}
val at := this.add_now(e, id);
if at != null {
memcpy(at, from, info[0].size);
}
}
# Gives a living entity a component it lacks, moving it to the table having
# it too, and gives where the value goes, which the caller writes, or `null`
# for a tag.
def world::add_now(&mut this, e: entity, id: u32): *mut u8 {
val r: record = this.records[e.index as u64];
val to := this.table_with(r.table, id);
val row := this.move_row(e, r.table, r.row as u64, to);
val t := &mut this.tables[to as u64];
val slot := t.slot_of(id);
return null if slot == tagged;
t.columns[slot as u64].changed = this.stamp();
return t.at(slot, row);
}
# Takes a component a living entity has, closing it.
def world::remove_now(&mut this, e: entity, id: u32): void {
val r: record = this.records[e.index as u64];
val t := &mut this.tables[r.table as u64];
val slot := t.slot_of(id);
return if slot == absent;
if slot != tagged {
val c := &t.columns[slot as u64];
if c.info[0].closes {
c.info[0].dispose(c.data + r.row as u64 * c.size);
}
}
val to := this.table_without(r.table, id);
_ = this.move_row(e, r.table, r.row as u64, to);
}
# Moves an entity's row to another table, with the values the two tables share,
# and gives its row there. What only the first has was closed already, and what
# only the second has, the caller writes.
def world::move_row(&mut this, e: entity, from: u32, row: u64, to: u32): u64 {
val made := this.tables[to as u64].push(e);
val source := &mut this.tables[from as u64];
val target := &mut this.tables[to as u64];
for i in 0..source.columns.length {
val c := &source.columns[i];
val slot := target.slot_of(c.id);
if slot != absent && slot != tagged {
memcpy(target.at(slot, made), c.data + row * c.size, c.size);
}
}
val moved := source.take_out(row);
if moved != entity::none {
this.records[moved.index as u64].row = row as u32;
}
val r := &mut this.records[e.index as u64];
r.table = to;
r.row = made as u32;
return made;
}
# The tick a change is stamped with: a new one outside a pass, so a query that
# ran before it sees it; within one, the pass's own, which every query that ran
# before the pass is behind.
def world::stamp(&mut this): u64 {
if this.deferring == 0 {
return this.next_tick();
}
return this.tick.load(order::relaxed);
}
# Moves the tick on, and gives it: by one add of the threads sharing the
# world, where they do, and as a plain count otherwise.
def world::next_tick(&mut this): u64 {
if this.sharing {
return this.tick.fetch_add(1, order::relaxed) + 1;
}
val next := this.tick.load(order::relaxed) + 1;
this.tick.store(next, order::relaxed);
return next;
}
# Types of components.
# A type's id, given it where it's new.
def world::id_of(&mut this, info: *component_info): u32 {
val found := this.by_key.get(info[0].key);
if found != absent {
val known := this.infos[found as u64];
if known != info && (known[0].path != info[0].path || known[0].name != info[0].name) {
fault($"`{known[0].path}` and `{info[0].path}` hash alike, so a world can't tell them apart.");
}
return found;
}
if this.parallel {
fault($"`{info[0].path}` was first used within `par_each`: use it before.");
}
if this.sharing {
fault($"`{info[0].path}` was first used while threads share the world: use it before.");
}
val id := this.infos.length as u32;
this.infos.append(info);
this.by_key.set(info[0].key, id);
return id;
}
# A type's id, or `absent` where the world hasn't met it.
def world::find_id(&this, info: *component_info): u32 {
return this.by_key.get(info[0].key);
}
# Tables.
def hash_ids(ids: span<u32>): u64 {
var h := fnv_basis;
for i in 0..ids.length {
h = mixed(h ^ ids[i] as u64);
}
return h;
}
# The table of a set of components, in order, made where it's new.
def world::table_of(&mut this, ids: span<u32>): u32 {
val h := hash_ids(ids);
var at := this.by_hash.get(h);
while at != absent {
if this.tables[at as u64].ids.view() == ids {
return at;
}
at = this.tables[at as u64].next;
}
return this.make_table(ids, h);
}
def world::make_table(&mut this, ids: span<u32>, h: u64): u32 {
var made := table{
ids = vector::<u32>::new(),
slots = vector::<u32>::new(),
columns = vector::<column>::new(),
hash = h,
next = this.by_hash.get(h),
edges = idmap::new(),
};
for i in 0..ids.length {
val info := this.infos[ids[i] as u64];
made.ids.append(ids[i]);
if info[0].size == 0 {
made.slots.append(tagged);
} else {
made.slots.append(made.columns.length as u32);
made.columns.append(column{ size = info[0].size, id = ids[i], info = info });
}
}
val index := this.tables.length as u32;
this.tables.append(move(made));
this.by_hash.set(h, index);
return index;
}
# The table an entity of one goes to as it gains a component.
def world::table_with(&mut this, from: u32, id: u32): u32 {
val key := (id as u64 << 1) + 1;
val known := this.tables[from as u64].edges.get(key);
return known if known != absent;
var ids := vector::<u32>::new();
val have := &this.tables[from as u64].ids;
var placed := false;
for i in 0..have.length {
if !placed && id < have[i] {
ids.append(id);
placed = true;
}
ids.append(have[i]);
}
if !placed {
ids.append(id);
}
val to := this.table_of(ids.view());
this.tables[from as u64].edges.set(key, to);
this.tables[to as u64].edges.set(key + 1, from);
return to;
}
# The table an entity of one goes to as it loses a component.
def world::table_without(&mut this, from: u32, id: u32): u32 {
val key := (id as u64 << 1) + 2;
val known := this.tables[from as u64].edges.get(key);
return known if known != absent;
var ids := vector::<u32>::new();
val have := &this.tables[from as u64].ids;
for i in 0..have.length {
if have[i] != id {
ids.append(have[i]);
}
}
val to := this.table_of(ids.view());
this.tables[from as u64].edges.set(key, to);
this.tables[to as u64].edges.set(key - 1, from);
return to;
}
# Deferring.
#! Makes the changes commands hold, in order, leaving them empty. Those of an
#! entity no longer alive are dropped, their values closed.
pub def world::apply(&mut this, changes: &mut commands): void {
this.refuse_while_shared("make the changes commands hold");
if this.deferring > 0 {
fault("`apply` can't run while a query passes over the world: run it after.");
}
for i in 0..changes.list.length {
val c: command = changes.list[i];
val index := c.who.index as u64;
val known := index < this.records.length && this.records[index].generation == c.who.generation;
match c.what {
op::place => {
if known && this.records[index].table == pending {
this.place(c.who);
}
}
op::set => {
if this.alive(c.who) {
this.set_bytes(c.who, c.info, changes.data + c.at);
} else if c.info[0].closes {
c.info[0].dispose(changes.data + c.at);
}
}
op::remove => {
val id := this.find_id(c.info);
if this.has_id(c.who, id) {
this.remove_now(c.who, id);
}
}
op::despawn => {
if this.alive(c.who) {
this.despawn_now(c.who);
}
}
}
}
changes.forget();
}
# Keeps a change, under the guard where threads may keep them at once.
def world::defer(&mut this, what: op, e: entity, info: *component_info): void {
this.lock();
this.pending.list.append(command{ what = what, who = e, info = info });
this.unlock();
}
# Keeps a component given, its bytes copied, which the caller lets go of.
def world::defer_put(&mut this, e: entity, info: *component_info, from: *mut u8): void {
this.lock();
this.pending.put(e, info, from);
this.unlock();
}
def world::lock(&mut this): void {
return if !this.parallel && !this.sharing;
while this.guard.exchange(1, order::acquire) != 0 {
system::yield_now();
}
}
def world::unlock(&mut this): void {
if this.parallel || this.sharing {
this.guard.store(0, order::release);
}
}
# Makes what the passes deferred.
def world::flush(&mut this): void {
var queued := move(this.pending);
this.apply(&mut queued);
this.pending = move(queued);
}
# Resources.
#! Gives the world a resource: the one value of its type the world holds, apart
#! from any entity, as a clock or the settings of a game. One the world holds
#! already it replaces.
pub def world::set_resource<T>(&mut this, value: T): void {
this.refuse_while_shared("be given resources");
val info := info_of::<T>();
var found := this.by_resource.get(info[0].key);
if found == absent {
found = this.resources.length as u32;
this.resources.append(resource{ info = info });
this.by_resource.set(info[0].key, found);
}
val held := &mut this.resources[found as u64];
if held.data == null {
held.data = raw_allocate(size_of::<T>() == 0 ? 1 : size_of::<T>());
} else if info[0].closes {
info[0].dispose(held.data);
}
memcpy(held.data, &mut value as *mut u8, size_of::<T>());
emptied(&mut value);
}
#! The world's resource of a type, where it holds one.
pub def world::resource<T>(&mut this): maybe<&mut T> {
val found := this.by_resource.get(info_of::<T>()[0].key);
return nothing{} if found == absent || this.resources[found as u64].data == null;
return maybe::<&mut T>{ some = through(this.resources[found as u64].data as *mut T) };
}
#! Takes the world's resource of a type, closing it.
#! @returns Whether it held one.
pub def world::remove_resource<T>(&mut this): bool {
this.refuse_while_shared("have resources taken");
val found := this.by_resource.get(info_of::<T>()[0].key);
return false if found == absent || this.resources[found as u64].data == null;
val held := &mut this.resources[found as u64];
if held.info[0].closes {
held.info[0].dispose(held.data);
}
raw_release(held.data);
held.data = null;
return true;
}