Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-28 08:31:02 -05:00
commit cd126dbcae
17 files changed
+3273

No files matched your search

+510
View File
@@ -0,0 +1,510 @@
#! Contains queries: filters saying which entities a pass goes over, passes
#! calling a function for each entity, which says what it takes by its
#! parameters, and chunks, the columns a table's entities have, for loops of
#! one's own.
module ecs;
# What a term of a query asks.
enum term_kind: u8 {
has, # That a table has a component.
lacks, # That it hasn't.
changed, # That it has one, written since the query last passed.
entity_of, # A parameter taking the entity.
reads, # A parameter taking `&T`, which a table must have.
writes, # A parameter taking `&mut T`, which a table must have.
maybe_reads, # A parameter taking `maybe<&T>`.
maybe_writes, # A parameter taking `maybe<&mut T>`.
by_value, # A parameter taking anything else, which `each` refuses.
}
struct filter_term {
var info: *component_info;
var kind: term_kind;
}
#! Which entities a query goes over, by the components they have and lack, as
#! `with::<player>().without::<asleep>()`. What a function given `each` takes
#! is asked too, so a filter says only what's left: the components an entity
#! must have that the function doesn't take, as tags, those it mustn't have,
#! and those it must have changed.
pub struct filter {
var terms: filter_term[12];
var count: u64;
}
#! A filter passing the entities having a component.
pub def with<T>(): filter {
val none := filter{};
return none.with::<T>();
}
#! A filter passing the entities lacking a component.
pub def without<T>(): filter {
val none := filter{};
return none.without::<T>();
}
#! A filter passing the entities of tables whose component was written since
#! the query last passed over them.
pub def changed<T>(): filter {
val none := filter{};
return none.changed::<T>();
}
#! The filter, passing only the entities having a component too.
pub def filter::with<T>(&this): filter {
return this.and(info_of::<T>(), term_kind::has);
}
#! The filter, passing only the entities lacking a component too.
pub def filter::without<T>(&this): filter {
return this.and(info_of::<T>(), term_kind::lacks);
}
#! The filter, passing only the entities having a component written since the
#! query last passed over them, too. What's written is known of each table, as
#! a pass writing a column, or `set` writing one value of it: a table any
#! entity of which had its component written passes whole.
pub def filter::changed<T>(&this): filter {
if size_of::<T>() == 0 {
fault($"`changed` was given `{name_of::<T>()}`, a tag, which is never written.");
}
return this.and(info_of::<T>(), term_kind::changed);
}
def filter::and(&this, info: *component_info, kind: term_kind): filter {
if this.count == 12 {
fault("A filter holds at most 12 terms.");
}
var made: filter = this;
made.terms[made.count] = filter_term{ info = info, kind = kind };
made.count++;
return made;
}
# What a function given `each` takes as a parameter.
struct param {
var name: strview; # The component's path, as `game::position`.
var hash: u64; # Of the path, which is the component's key.
var kind: term_kind;
}
# A parameter, by its type's path: `&mut game::position`,
# `core::maybe<&game::velocity>`, and so on.
const def param_of(spelled: strview): param {
var name := spelled;
var optional := false;
if begins(name, "core::maybe<") && name[name.length - 1] == '>' {
optional = true;
name = name[12:name.length - 13];
}
var kind := term_kind::by_value;
if begins(name, "&mut ") {
kind = optional ? term_kind::maybe_writes : term_kind::writes;
name = name[5:];
} else if begins(name, "&") {
kind = optional ? term_kind::maybe_reads : term_kind::reads;
name = name[1:];
} else {
name = spelled;
}
return param{ name = name, hash = hash_text(name, fnv_basis), kind = kind };
}
const def begins(text: strview, start: strview): bool {
return false if text.length < start.length;
for i in 0..start.length {
return false if text[i] != start[i];
}
return true;
}
# What a parameter of type `P` takes.
def param_for<P>(): param {
if const P is entity {
return param{ name = "entity", kind = term_kind::entity_of };
}
const made: param = param_of(path_of::<P>());
return made;
}
# A term of a query: a filter's, or a parameter's.
struct term {
var info: *component_info; # A filter's, or `null` for a parameter's.
var name: strview;
var hash: u64;
var kind: term_kind;
var id: u32; # Or `absent`, for a parameter whose type the world hasn't met.
}
# What a world keeps of a query, which every pass asking the same uses: the
# tables it passes over, and where in each its terms' columns are.
struct query_state : owning {
var terms: vector<term>;
var first: u64; # The first parameter's term.
var matched: vector<u32>; # The tables it passes over.
var slots: vector<u32>; # Of each table matched, each term's column, `tagged`, or `absent`.
var seen: u64; # How many of the world's tables it has looked at.
var known: u64; # How many types the world had as it last looked for its parameters'.
}
pub def query_state::close(&mut this): void {
this.terms.close();
this.matched.close();
this.slots.close();
}
# The query asking what a filter and parameters do, made where it's new, and
# brought up to date with the world's tables.
def world::query_of(&mut this, by: &filter, params: span<param>): u32 {
if this.parallel {
fault("A function `par_each` calls can't query the world itself.");
}
var key := fnv_basis;
for i in 0..by.count {
key = mixed(key ^ by.terms[i].info[0].key) + by.terms[i].kind as u64;
}
for i in 0..params.length {
key = mixed(key ^ params[i].hash) + params[i].kind as u64 + 16;
}
val found := this.cached.get(key);
if found != absent {
this.refresh(found);
return found;
}
var made := query_state{
terms = vector::<term>::new(),
first = by.count,
matched = vector::<u32>::new(),
slots = vector::<u32>::new(),
known = 0xFFFFFFFFFFFFFFFF,
};
for i in 0..by.count {
val t: filter_term = by.terms[i];
made.terms.append(term{ info = t.info, name = t.info[0].path, kind = t.kind, id = this.id_of(t.info) });
}
for i in 0..params.length {
val p: param = params[i];
if p.kind == term_kind::by_value {
fault($"A function given `each` takes `{p.name}`, which it can't be given: it takes components as `&T` or `&mut T`, or `maybe<&T>` or `maybe<&mut T>` where an entity may lack one, and the `entity`.");
}
made.terms.append(term{ name = p.name, hash = p.hash, kind = p.kind, id = absent });
}
val index := this.queries.length as u32;
this.queries.append(move(made));
this.cached.set(key, index);
this.refresh(index);
return index;
}
# Finds the types of the parameters of a query that the world hadn't met, by
# their paths, whose hashes are their keys.
def world::resolve(&mut this, q: u32): void {
val st := &mut this.queries[q as u64];
return if st.known == this.infos.length;
st.known = this.infos.length;
var found := false;
for i in st.first..st.terms.length {
val t := &mut st.terms[i];
if t.kind == term_kind::entity_of || t.id != absent {
continue;
}
val id := this.by_key.get(t.hash);
if id != absent && this.infos[id as u64][0].path == t.name {
t.id = id;
found = true;
}
}
if found {
st.matched.clear();
st.slots.clear();
st.seen = 0;
}
}
# Brings a query up to date with the tables made since it last looked.
def world::refresh(&mut this, q: u32): void {
this.resolve(q);
val st := &mut this.queries[q as u64];
for index in st.seen..this.tables.length {
val t := &this.tables[index];
if matches(st, t) {
st.matched.append(index as u32);
for i in 0..st.terms.length {
val id := st.terms[i].id;
st.slots.append(id == absent || st.terms[i].kind == term_kind::entity_of ? absent : t.slot_of(id));
}
}
}
st.seen = this.tables.length;
}
# Whether a query passes over a table.
def matches(st: &query_state, t: &table): bool {
for i in 0..st.terms.length {
val each := &st.terms[i];
match each.kind {
term_kind::has, term_kind::changed, term_kind::reads, term_kind::writes => {
return false if each.id == absent || !t.has(each.id);
}
term_kind::lacks => {
return false if each.id != absent && t.has(each.id);
}
else => {}
}
}
return true;
}
# The ticks of a pass: the query's last, and its own.
struct pass {
var since: u64;
var now: u64;
}
# Starts a pass, the tick its query last passed at becoming the pass's: the
# world defers what would move an entity until the outermost pass ends.
def world::begin_pass(&mut this, last: &mut u64): pass {
if this.parallel {
fault("A function `par_each` calls can't pass over the world itself.");
}
this.deferring++;
this.tick++;
val since := last;
last = this.tick;
return pass{ since = since, now = this.tick };
}
def world::end_pass(&mut this): void {
this.deferring--;
if this.deferring == 0 && this.pending.length > 0 {
this.flush();
}
}
# How many rows of a table matched a pass goes over: none where it's empty, or
# a column a `changed` term asks of wasn't written since the query last passed.
# Stamps the columns the pass writes.
def world::rows_of(&mut this, q: u32, m: u64, since: u64, now: u64): u64 {
val st := &this.queries[q as u64];
val t := &mut this.tables[st.matched[m] as u64];
return 0 if t.count == 0;
val stride := st.terms.length;
for i in 0..stride {
if st.terms[i].kind == term_kind::changed {
val slot := st.slots[m * stride + i];
return 0 if slot >= tagged || t.columns[slot as u64].changed <= since;
}
}
for i in 0..stride {
val kind := st.terms[i].kind;
val slot := st.slots[m * stride + i];
if (kind == term_kind::writes || kind == term_kind::maybe_writes) && slot < tagged {
t.columns[slot as u64].changed = now;
}
}
return t.count;
}
# A place in a column a pass reads from, and how far apart its rows are.
struct cursor {
var at: *mut u8;
var stride: u64;
}
# Where a parameter's values begin in a table matched, from a row: the
# column's, the entities', or `null` where an entity may lack it and these do.
def world::cursor_of(&this, q: u32, m: u64, index: u64, from: u64): cursor {
val st := &this.queries[q as u64];
val t := &this.tables[st.matched[m] as u64];
val term_at := st.first + index;
if st.terms[term_at].kind == term_kind::entity_of {
return cursor{ at = (t.entities + from) as *mut u8, stride = 8 };
}
val slot := st.slots[m * st.terms.length + term_at];
return cursor{} if slot == absent;
# A tag holds nothing, so its reference is any address that's there.
return cursor{ at = t.entities as *mut u8 } if slot == tagged;
val c := &t.columns[slot as u64];
return cursor{ at = c.data + from * c.size, stride = c.size };
}
# The value of a parameter's type at a cursor, which then moves to the next:
# the entity, or a reference made of the cursor's address, which `maybe<&T>`
# is too, `nothing` where the address is `null`.
def take<P>(c: &mut cursor): P {
if const P is entity {
val e: entity = through(c.at as *entity);
c.at = c.at + c.stride;
return e;
}
# The cursor's address is its first word, read as the reference it is.
val got := (address(c) as *mut P)[0];
c.at = c.at + c.stride;
return got;
}
#! Which entities a pass goes over, as a filter says, in a world: to call a
#! function for each, or walk their chunks, or count them. It remembers when it
#! last passed, which its filter's `changed` terms read, so a system keeps its
#! query from one pass to the next.
pub struct query {
var owner: *mut world;
var by: filter;
var last: u64; # The world's tick as it last passed, or 0 where it never has.
}
#! The entities a filter passes, to pass over. Where the filter asks what
#! `changed`, every table counts as changed for its first pass.
pub def world::query(&mut this, by: filter): query {
return query{ owner = address(this), by = by };
}
#! Calls a function for each entity having the components it takes, in the
#! order of their tables. It takes components as `&T`, to read, or `&mut T`,
#! to write, or `maybe<&T>` or `maybe<&mut T>` where an entity may lack them,
#! and the `entity` as an `entity`, in any order, as
#! `def(e: entity, p: &mut position, v: &velocity)`.
#!
#! The world defers what would move an entity while it passes, making it as
#! the pass ends.
pub def world::each<F, Ts...>(&mut this, f: F): void where F: invokable<def(Ts...): void> {
val by := filter{};
var last := 0u;
this.walk(&by, &mut last, f);
}
#! Calls a function for each entity having the components it takes, as `each`
#! does, from several threads at once: the world's own, and a worker for each
#! processor more. The function is called for different entities at once, so
#! it writes only what it's given. It may set components an entity has, and
#! defer what would move one, but not spawn or pass over the world itself.
pub def world::par_each<F, Ts...>(&mut this, f: F): void where F: invokable<def(Ts...): void> {
val by := filter{};
var last := 0u;
this.walk_parallel(&by, &mut last, f);
}
#! Calls a function for each entity the filter passes having the components
#! it takes, as `world::each` does.
pub def query::each<F, Ts...>(&mut this, f: F): void where F: invokable<def(Ts...): void> {
through(this.owner).walk(&this.by, &mut this.last, f);
}
#! Calls a function for each entity the filter passes having the components
#! it takes, from several threads, as `world::par_each` does.
pub def query::par_each<F, Ts...>(&mut this, f: F): void where F: invokable<def(Ts...): void> {
through(this.owner).walk_parallel(&this.by, &mut this.last, f);
}
#! How many entities the filter passes.
pub def query::count(&mut this): u64 {
val w := &mut through(this.owner);
val q := w.query_of(&this.by, span::<param>::empty());
val st := &w.queries[q as u64];
var total := 0u;
for m in 0..st.matched.length {
total += w.tables[st.matched[m] as u64].count;
}
return total;
}
#! The chunks of the entities the filter passes: a chunk for each table, its
#! components as columns, for loops of one's own over them. The world defers
#! what would move an entity until the chunks are done with.
pub def query::chunks(&mut this): chunks {
val w := &mut through(this.owner);
val q := w.query_of(&this.by, span::<param>::empty());
val p := w.begin_pass(&mut this.last);
return chunks{ owner = this.owner, query = q, since = p.since, now = p.now, open = true };
}
#! The entities of a table a query passes, side by side, and their components,
#! each a column of one value for each entity, in the same order.
pub struct chunk {
var owner: *mut world;
var table: u32;
pub val length: u64; #! How many entities.
var now: u64;
}
#! Its entities.
pub def chunk::entities(&this): span<entity> {
val t := &through(this.owner).tables[this.table as u64];
return span::<entity>::over(t.entities, this.length);
}
#! Whether its entities have a component.
pub def chunk::has<T>(&this): bool {
val w := &mut through(this.owner);
return w.tables[this.table as u64].has(w.find_id(info_of::<T>()));
}
#! Its entities' values of a component, to read.
pub def chunk::read<T>(&this): span<T> {
return span::<T>::over(this.column_of(info_of::<T>(), false) as *T, this.length);
}
#! Its entities' values of a component, to write, which `changed` filters then
#! pass.
pub def chunk::write<T>(&this): slice<T> {
return slice::<T>::over(this.column_of(info_of::<T>(), true) as *mut T, this.length);
}
def chunk::column_of(&this, info: *component_info, writing: bool): *mut u8 {
val w := &mut through(this.owner);
val id := w.find_id(info);
val t := &mut w.tables[this.table as u64];
val slot := id == absent ? absent : t.slot_of(id);
if slot == absent {
fault($"A chunk's entities haven't `{info[0].path}`: a filter `with` it passes only those that have it.");
}
if slot == tagged {
fault($"`{info[0].path}` is a tag, which has no values: `has` asks of it.");
}
if writing {
t.columns[slot as u64].changed = this.now;
}
return t.columns[slot as u64].data;
}
#! The chunks a query passes, one for each table having entities, which `for`
#! walks. Closing it ends the pass, whether walked to its end or not.
pub struct chunks : owning, iterator<chunk> {
var owner: *mut world;
var query: u32;
var next_match: u64;
var since: u64;
var now: u64;
var open: bool;
}
pub def chunks::next(&mut this): maybe<chunk> {
return nothing{} if !this.open;
val w := &mut through(this.owner);
val count := w.queries[this.query as u64].matched.length;
while this.next_match < count {
val m := this.next_match;
this.next_match++;
val rows := w.rows_of(this.query, m, this.since, this.now);
if rows > 0 {
val table := w.queries[this.query as u64].matched[m];
return chunk{ owner = this.owner, table = table, length = rows, now = this.now };
}
}
this.end();
return nothing{};
}
pub def chunks::close(&mut this): void {
this.end();
}
def chunks::end(&mut this): void {
if this.open {
this.open = false;
through(this.owner).end_pass();
}
}