Initial Commit
This commit is contained in:
22 files changed
+5161
No files matched your search
@@ -0,0 +1,9 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
@@ -0,0 +1 @@
|
||||
.blossom
|
||||
@@ -0,0 +1,126 @@
|
||||
# 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](https://git.malunal.studio/sakura/blossom), and reads only std.
|
||||
|
||||
```sakura
|
||||
import malunal::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);
|
||||
|
||||
# What changed of each entity since the query last passed.
|
||||
var moved := w.query(changed::<position>());
|
||||
moved.each(def(e: entity, p: &position) { ... });
|
||||
|
||||
# Run as an entity is given a component, or loses one.
|
||||
_ = w.observe::<asleep>(change::added, def(at, e) { ... });
|
||||
|
||||
# Children, despawned with their parents.
|
||||
val shadow := w.spawn_with(position{});
|
||||
w.set_parent(shadow, ball);
|
||||
_ = w.despawn(ball); # and `shadow`
|
||||
```
|
||||
`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 `malunal.ecs`, whose module is `malunal::ecs`, among a target's `deps`:
|
||||
|
||||
```yaml
|
||||
requires:
|
||||
- ../ecs
|
||||
targets:
|
||||
- name: game
|
||||
type: program
|
||||
deps: [malunal.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/ticks.sakura` | When each entity was given a component, and its value last written, kept of the components queries ask of, and what a pass asks of each entity |
|
||||
| `ecs/query.sakura` | Filters, by type and by path, 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/observers.sakura` | `observe`: functions run as an entity is given a component, or loses one |
|
||||
| `ecs/relations.sakura` | Parents and children: `child_of`, `children`, `set_parent`, and the rest |
|
||||
| `ecs/workers.sakura` | The threads `par_each` calls functions on |
|
||||
| `ecs/sharing.sakura` | A world shared by threads, each passing over it at once |
|
||||
| `ecs/commands.sakura` | `commands`: changes to what entities have, and entities spawned, 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, and the key of a type's path |
|
||||
| `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_with` moves 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 its `path_of`, its name with the module of each type it names, made while compiling, the same in every program, so `game::position` and `ai::position` are two components.
|
||||
- **`each`** calls a function for each entity having the components it takes. Its parameters say what it passes over: `&T` reads a component, and `&mut T` writes one, which the entity must have; `maybe<&T>` and `maybe<&mut T>` take one it may lack; and `entity` takes 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. A program knowing a type only by its path names it so, as `with_path("game::player")`, `without_path`, and `changed_path`, as an engine reading what a system takes from its type's spelling does; no entity has a type the world hasn't met, and every one lacks it, until it's met. 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 entities whose `T` was written since its query last passed, as a pass taking `&mut T`, a chunk's `write`, or `set`, writes them, or as they were given it; `added::<T>()` passes those given `T` since, spawned with it or given it as they lacked it, a tag as well as a value. A value written through `get` isn't known as 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 entity changed and given. The world keeps when each entity was given a component, and its value last written, only once some query asks of it, so passes over the rest cost nothing more. Of those asked of, a pass writing them stamps each entity it passes, and a pass asking walks the tables written since, and of those, the entities. A chunk's `passes` says which of its entities do; `count` counts those that do, without moving the query on.
|
||||
- **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. `commands` keep changes the same way, for a program to `apply` when it's ready; a change to an entity despawned first is dropped, its value closed. Those a world makes, by `world::commands`, spawn entities too, by `spawn` and `spawn_with`, whose numbers are known at once, which the commands and the world give components, despawn, and make children till they're applied; applied, an entity is put in the table of the components the commands gave it at once, as `spawn_with` puts it.
|
||||
- **Observers**: `observe::<T>(change::added, f)` runs `f`, given the world and the entity, each time an entity is given a `T` it lacked, once the value is there, and `change::removed` each time one loses it, as it's taken or the entity despawned, while the value still is, so `f` reads it. A component replaced, or written, runs none. What an observer changes that would move an entity is made once the change it observed is done, which runs observers in turn. Observers run on the world's thread: those of changes made while a pass or threads went over the world run as they're made. `unobserve` takes one out.
|
||||
- **Parents and children**: `set_parent(child, parent)` makes an entity a child of another, giving it `child_of` and the parent's `children` it, in order, refusing to make an entity within itself; `remove_parent` takes it from its parent, and `parent_of` and `children_of` read them. Despawning an entity despawns each entity within it, the deepest first, and takes it from its parent's `children`; taking an entity's `children` leaves its children of the world itself. Where a pass goes over the world, a parent given or taken is made as it ends, and commands give and take them too.
|
||||
- **`par_each`** calls 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, spawn, and defer what would move one, but not query or pass over the world itself, which fault. `world::threads` says how many threads it uses.
|
||||
- **Sharing**: from `begin_sharing` to `end_sharing`, several threads pass over the world at once, as an engine runs systems reaching different components on threads of its own. Each passes by `each`, queries, and chunks, gets and replaces the components entities have, reads resources, and spawns, and what would move an entity is deferred, as within a pass, until the sharing ends. An entity spawned is alive once the sharing ends, and given components, despawned, and made a child till then. Threads may read a component at once, but one writing it must be the only thread reaching it, which the world leaves to its caller. While shared, the world can't meet types it hasn't, be given resources or observers or have them taken, or `apply` commands, which fault, and `par_each` calls its function on its own thread, as the sharing threads are the workers. A thread finding a query, or spawning, takes a lock, which no world not shared takes; a query first asking what changed of a component the world doesn't track yet asks of its tables alone till the sharing ends.
|
||||
- **Resources** are values of a type a world holds one of, apart from any entity, as a clock: `set_resource`, `resource`, and `remove_resource`. A world closes them the last given first, so one made of another, as a renderer of the window it draws into, closes before it.
|
||||
- **Schedules** run systems, functions of the world or types of one's own with an `invoke` taking it, in the order they were added, timing each, which `timings` tells; `remove` takes out those of a name.
|
||||
- **Keys**: `get_by_key`, `has_by_key`, `set_by_info`, `remove_by_key`, `resource_by_key`, `set_resource_by_info`, and `entities_by_key` reach components and resources by their types' keys, `component_key::<T>()`, or `key_of_path` of a type's path, 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::plain` makes 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 `entity` is `std::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 an `entity_numbering`, and `apply` writes 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::none` is nothing either way.
|
||||
|
||||
## Speed
|
||||
`blossom run malunal.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 | 0.78 ns |
|
||||
| A loop over a query's chunks | 0.85 ns |
|
||||
| `each`, given a type of one's own with an `invoke` | 0.90 ns |
|
||||
| `each`, given a lambda | 2.0 ns |
|
||||
| `each`, over 67 tables | 1.95 ns |
|
||||
| `par_each`, on 32 threads | 0.29–0.37 ns |
|
||||
| `spawn_with` of two components | 30–32 ns |
|
||||
| `spawn_with` of two components by commands, recorded and applied | 84 ns |
|
||||
| `get`, in the order they were spawned | 8 ns |
|
||||
| `get`, in no order | 28–33 ns |
|
||||
| `set` of a component the entity has | 16.5 ns |
|
||||
| A move to another table, as a tag is added or removed | 52–54 ns |
|
||||
| `despawn`, from 67 tables | 31–35 ns |
|
||||
| `each` asking what changed, of a million, 10,000 written since | 0.5 ns |
|
||||
|
||||
`each` adds next to nothing to the loop it makes: given a type of its own, it's within a tenth of a nanosecond of chunks. A lambda costs a call through its address for each entity, about a nanosecond 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.
|
||||
|
||||
Knowing what changed of each entity costs nothing where no query asks: passes are as fast as they were without it, and spawning, moving, and despawning cost a few nanoseconds more than before observers and parents were the world's, for asking whether an entity has either, about 2 ns a spawn, 5 a move, and 6 a despawn. Of a component a query asks of, a pass writing it stamps each entity it passes, and moving an entity copies its ticks; a pass asking walks only the tables written since it last passed. Commands record each component's bytes and apply them as `spawn_with` would, the rest of their cost.
|
||||
|
||||
## 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, by type and by path, deferring, chunks, what changed, passes on four threads, a world four threads share, each passing over it, finding queries it hadn't, and deferring changes, resources, closed the last given first, commands, schedules, components of one name in two modules, components reached by their types' keys, entities written and read by a numbering, what was written and given of each entity, by passes, `set`, moves, and chunks, observers, parents and children, given and taken, despawned together, by the world and by commands, entities spawned by two threads sharing a world, and by their commands, and what a query first asks while threads share a world. `sakurac run --checks` runs them with every read and write checked, and reports nothing left unreleased.
|
||||
|
||||
## Not yet
|
||||
The tables a world no longer uses given back; observers of a component replaced; relationships besides parents and children; and saving a world whole, which each type's `key` was made for, and its entities' numbering is the start of.
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
name: ecs
|
||||
gpid: malunal
|
||||
semv: 1.0.0
|
||||
|
||||
options:
|
||||
level: 2
|
||||
|
||||
requires:
|
||||
- https://git.malunal.studio/sakura/std@v1.0.0
|
||||
|
||||
targets:
|
||||
- name: malunal.ecs
|
||||
type: library
|
||||
root: ./ecs
|
||||
deps:
|
||||
- std.serial
|
||||
- std.thread
|
||||
- std.time
|
||||
|
||||
# Times `malunal::ecs` over a million entities; see its header.
|
||||
- name: malunal.ecs.bench
|
||||
type: program
|
||||
level: ${level}
|
||||
deps:
|
||||
- malunal.ecs
|
||||
- std.io
|
||||
- std.time
|
||||
srcs:
|
||||
- tools/bench.sakura
|
||||
|
||||
tests:
|
||||
- name: malunal.ecs.tests
|
||||
type: program
|
||||
deps: [malunal.ecs, std.json, std.serial, std.testing, std.thread]
|
||||
srcs: [tests/main.sakura, tests/ecs.sakura]
|
||||
|
||||
exports:
|
||||
- malunal.ecs
|
||||
|
||||
package:
|
||||
desc: Entities, their components, and the systems passing over them, kept in tables by archetype.
|
||||
auth: John Christman <sorakatadzuma@gmail.com>
|
||||
@@ -0,0 +1,158 @@
|
||||
#! Contains `commands`: changes to what entities have, kept to be made later,
|
||||
#! as a world keeps those made while a query passes over it.
|
||||
|
||||
module malunal::ecs;
|
||||
|
||||
# What a command does.
|
||||
enum op: u8 {
|
||||
place, # Puts an entity spawned while the world deferred into its first table.
|
||||
set, # Gives an entity a component, or replaces the one it has.
|
||||
remove, # Takes a component from an entity.
|
||||
despawn, # Despawns an entity.
|
||||
parent, # Makes an entity a child of another.
|
||||
unparent, # Takes an entity from its parent.
|
||||
}
|
||||
|
||||
struct command {
|
||||
var what: op;
|
||||
var who: entity;
|
||||
var info: *component_info; # The component's, for `set` and `remove`.
|
||||
var at: u64; # Where `set`'s value is, in `data`, or the bits of `parent`'s parent.
|
||||
}
|
||||
|
||||
#! Changes to what entities have, made later, in order, by `world::apply`. The
|
||||
#! values it's given it holds until then, and closes where they're never made,
|
||||
#! as where their entity was despawned first. Those a world makes, by
|
||||
#! `world::commands`, spawn entities too.
|
||||
pub struct commands : owning {
|
||||
var list: vector<command>;
|
||||
var data: *mut u8;
|
||||
var used: u64;
|
||||
var capacity: u64;
|
||||
var owner: *mut world; # The world it spawns entities of, or `null`.
|
||||
}
|
||||
|
||||
#! Commands of no world, which spawn none.
|
||||
pub def commands::new(): commands {
|
||||
return commands{ list = vector::<command>::new() };
|
||||
}
|
||||
|
||||
#! Commands of the world, which spawn its entities: whatever thread spawns,
|
||||
#! as a system running while threads share the world does.
|
||||
pub def world::commands(&mut this): commands {
|
||||
return commands{ list = vector::<command>::new(), owner = address(this) };
|
||||
}
|
||||
|
||||
#! Spawns an entity with no components, its number known at once, and put in
|
||||
#! the world as the commands are applied: till then, it's given components,
|
||||
#! despawned, and made a child as one alive, by the commands or the world.
|
||||
pub def commands::spawn(&mut this): entity {
|
||||
if this.owner == null {
|
||||
fault("Commands made by `commands::new` spawn no entities: a world makes those that do, by `world::commands`.");
|
||||
}
|
||||
val e := through(this.owner).new_entity();
|
||||
this.place(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
#! Spawns an entity with components, as `spawn` does.
|
||||
pub def commands::spawn_with<Ts...>(&mut this, components: Ts...): entity {
|
||||
val e := this.spawn();
|
||||
for const c in components {
|
||||
this.put(e, info_of_value(&c), &mut c as *mut u8);
|
||||
emptied(&mut c);
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
#! Makes an entity a child of another, as `world::set_parent` does.
|
||||
pub def commands::set_parent(&mut this, child: entity, parent: entity): void {
|
||||
this.list.append(command{ what = op::parent, who = child, at = parent.bits });
|
||||
}
|
||||
|
||||
#! Takes an entity from its parent, as `world::remove_parent` does.
|
||||
pub def commands::remove_parent(&mut this, child: entity): void {
|
||||
this.list.append(command{ what = op::unparent, who = child });
|
||||
}
|
||||
|
||||
#! How many changes it holds.
|
||||
pub val commands::length: u64 {
|
||||
get => this.list.length;
|
||||
}
|
||||
|
||||
#! Gives an entity a component, or replaces the one it has.
|
||||
pub def commands::set<T>(&mut this, e: entity, value: T): void {
|
||||
this.put(e, info_of::<T>(), &mut value as *mut u8);
|
||||
emptied(&mut value);
|
||||
}
|
||||
|
||||
#! Gives an entity a component's zero value, as a tag is given, where it lacks
|
||||
#! one.
|
||||
pub def commands::add<T>(&mut this, e: entity): void where T: zeroable {
|
||||
var zero: T;
|
||||
this.set(e, move(zero));
|
||||
}
|
||||
|
||||
#! Takes a component from an entity.
|
||||
pub def commands::remove<T>(&mut this, e: entity): void {
|
||||
this.list.append(command{ what = op::remove, who = e, info = info_of::<T>() });
|
||||
}
|
||||
|
||||
#! Despawns an entity.
|
||||
pub def commands::despawn(&mut this, e: entity): void {
|
||||
this.list.append(command{ what = op::despawn, who = e });
|
||||
}
|
||||
|
||||
def commands::place(&mut this, e: entity): void {
|
||||
this.list.append(command{ what = op::place, who = e });
|
||||
}
|
||||
|
||||
# Keeps a copy of a value's bytes, which the caller then lets go of.
|
||||
def commands::put(&mut this, e: entity, info: *component_info, from: *mut u8): void {
|
||||
val size := info[0].size;
|
||||
val align := info[0].align == 0 ? 1u : info[0].align;
|
||||
val at := (this.used + align - 1) & ~(align - 1);
|
||||
if at + size > this.capacity {
|
||||
var room := this.capacity == 0 ? 256u : this.capacity * 2;
|
||||
while room < at + size {
|
||||
room *= 2;
|
||||
}
|
||||
this.data = resized(this.data, room);
|
||||
this.capacity = room;
|
||||
}
|
||||
memcpy(this.data + at, from, size);
|
||||
this.used = at + size;
|
||||
this.list.append(command{ what = op::set, who = e, info = info, at = at });
|
||||
}
|
||||
|
||||
#! Forgets every change it holds, closing their values.
|
||||
pub def commands::clear(&mut this): void {
|
||||
for i in 0..this.list.length {
|
||||
val c: command = this.list[i];
|
||||
if c.what == op::set && c.info[0].closes {
|
||||
c.info[0].dispose(this.data + c.at);
|
||||
}
|
||||
}
|
||||
this.forget();
|
||||
}
|
||||
|
||||
# Forgets every change it holds, whose values were made or closed already.
|
||||
def commands::forget(&mut this): void {
|
||||
this.list.clear();
|
||||
this.used = 0;
|
||||
}
|
||||
|
||||
pub def commands::close(&mut this): void {
|
||||
this.clear();
|
||||
raw_release(this.data);
|
||||
this.data = null;
|
||||
this.capacity = 0;
|
||||
this.list.close();
|
||||
}
|
||||
|
||||
# Leaves a value whose bytes went elsewhere empty, so closing it closes nothing.
|
||||
def emptied<T>(value: &mut T): void {
|
||||
if const T is closeable {
|
||||
memset(value as *mut u8, 0, size_of::<T>());
|
||||
}
|
||||
}
|
||||
+560
@@ -0,0 +1,560 @@
|
||||
#! Contains the passes `each` and `par_each` make, one for each number of
|
||||
#! parameters a function takes, up to 8, each the same but for that number:
|
||||
#! the query its parameters ask, then a loop over each table it matches,
|
||||
#! calling the function for each row, or, where the query asks what was
|
||||
#! written or given of each entity, for each row passing.
|
||||
|
||||
module malunal::ecs;
|
||||
|
||||
# What `par_each` gives the threads it calls a function on.
|
||||
struct task<F> {
|
||||
var owner: *mut world;
|
||||
var query: *mut query_state;
|
||||
var call: *mut F;
|
||||
var since: u64;
|
||||
var now: u64;
|
||||
}
|
||||
|
||||
def world::walk<F, T1>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>()]);
|
||||
val p := this.begin_pass(last);
|
||||
for m in 0..q[0].matched.length {
|
||||
val rows := this.rows_of(q, m, p.since, p.now);
|
||||
if rows == 0 {
|
||||
continue;
|
||||
}
|
||||
if q[0].sifts {
|
||||
val s := this.sieve_of(q, m);
|
||||
for row in 0..rows {
|
||||
continue if !s.passes(row, p.since);
|
||||
s.stamp(row, p.now);
|
||||
var c1 := this.cursor_of(q, m, 0, row);
|
||||
f(take::<T1>(&mut c1));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
var c1 := this.cursor_of(q, m, 0, 0);
|
||||
for _ in 0..rows {
|
||||
f(take::<T1>(&mut c1));
|
||||
}
|
||||
}
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def world::walk_parallel<F, T1>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>()]);
|
||||
val p := this.begin_pass(last);
|
||||
var work := task::<F>{ owner = address(this), query = q, call = &mut f, since = p.since, now = p.now };
|
||||
this.run_pieces(q, p, &mut work as *mut u8, run_piece1::<F, T1>);
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def run_piece1<F, T1>(context: *mut u8, at: &piece): void where F: invokable<def(T1): void> {
|
||||
val work := &mut through(context as *mut task<F>);
|
||||
val w := &mut through(work.owner);
|
||||
val f := &mut through(work.call);
|
||||
if work.query[0].sifts {
|
||||
val s := w.sieve_of(work.query, at.which);
|
||||
for row in at.begin..at.end {
|
||||
continue if !s.passes(row, work.since);
|
||||
s.stamp(row, work.now);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, row);
|
||||
f(take::<T1>(&mut c1));
|
||||
}
|
||||
return;
|
||||
}
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
for _ in at.begin..at.end {
|
||||
f(take::<T1>(&mut c1));
|
||||
}
|
||||
}
|
||||
|
||||
def world::walk<F, T1, T2>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>()]);
|
||||
val p := this.begin_pass(last);
|
||||
for m in 0..q[0].matched.length {
|
||||
val rows := this.rows_of(q, m, p.since, p.now);
|
||||
if rows == 0 {
|
||||
continue;
|
||||
}
|
||||
if q[0].sifts {
|
||||
val s := this.sieve_of(q, m);
|
||||
for row in 0..rows {
|
||||
continue if !s.passes(row, p.since);
|
||||
s.stamp(row, p.now);
|
||||
var c1 := this.cursor_of(q, m, 0, row);
|
||||
var c2 := this.cursor_of(q, m, 1, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
var c1 := this.cursor_of(q, m, 0, 0);
|
||||
var c2 := this.cursor_of(q, m, 1, 0);
|
||||
for _ in 0..rows {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2));
|
||||
}
|
||||
}
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def world::walk_parallel<F, T1, T2>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>()]);
|
||||
val p := this.begin_pass(last);
|
||||
var work := task::<F>{ owner = address(this), query = q, call = &mut f, since = p.since, now = p.now };
|
||||
this.run_pieces(q, p, &mut work as *mut u8, run_piece2::<F, T1, T2>);
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def run_piece2<F, T1, T2>(context: *mut u8, at: &piece): void where F: invokable<def(T1, T2): void> {
|
||||
val work := &mut through(context as *mut task<F>);
|
||||
val w := &mut through(work.owner);
|
||||
val f := &mut through(work.call);
|
||||
if work.query[0].sifts {
|
||||
val s := w.sieve_of(work.query, at.which);
|
||||
for row in at.begin..at.end {
|
||||
continue if !s.passes(row, work.since);
|
||||
s.stamp(row, work.now);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, row);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2));
|
||||
}
|
||||
return;
|
||||
}
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, at.begin);
|
||||
for _ in at.begin..at.end {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2));
|
||||
}
|
||||
}
|
||||
|
||||
def world::walk<F, T1, T2, T3>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>()]);
|
||||
val p := this.begin_pass(last);
|
||||
for m in 0..q[0].matched.length {
|
||||
val rows := this.rows_of(q, m, p.since, p.now);
|
||||
if rows == 0 {
|
||||
continue;
|
||||
}
|
||||
if q[0].sifts {
|
||||
val s := this.sieve_of(q, m);
|
||||
for row in 0..rows {
|
||||
continue if !s.passes(row, p.since);
|
||||
s.stamp(row, p.now);
|
||||
var c1 := this.cursor_of(q, m, 0, row);
|
||||
var c2 := this.cursor_of(q, m, 1, row);
|
||||
var c3 := this.cursor_of(q, m, 2, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
var c1 := this.cursor_of(q, m, 0, 0);
|
||||
var c2 := this.cursor_of(q, m, 1, 0);
|
||||
var c3 := this.cursor_of(q, m, 2, 0);
|
||||
for _ in 0..rows {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3));
|
||||
}
|
||||
}
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def world::walk_parallel<F, T1, T2, T3>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>()]);
|
||||
val p := this.begin_pass(last);
|
||||
var work := task::<F>{ owner = address(this), query = q, call = &mut f, since = p.since, now = p.now };
|
||||
this.run_pieces(q, p, &mut work as *mut u8, run_piece3::<F, T1, T2, T3>);
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def run_piece3<F, T1, T2, T3>(context: *mut u8, at: &piece): void where F: invokable<def(T1, T2, T3): void> {
|
||||
val work := &mut through(context as *mut task<F>);
|
||||
val w := &mut through(work.owner);
|
||||
val f := &mut through(work.call);
|
||||
if work.query[0].sifts {
|
||||
val s := w.sieve_of(work.query, at.which);
|
||||
for row in at.begin..at.end {
|
||||
continue if !s.passes(row, work.since);
|
||||
s.stamp(row, work.now);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, row);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, row);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3));
|
||||
}
|
||||
return;
|
||||
}
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, at.begin);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, at.begin);
|
||||
for _ in at.begin..at.end {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3));
|
||||
}
|
||||
}
|
||||
|
||||
def world::walk<F, T1, T2, T3, T4>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>()]);
|
||||
val p := this.begin_pass(last);
|
||||
for m in 0..q[0].matched.length {
|
||||
val rows := this.rows_of(q, m, p.since, p.now);
|
||||
if rows == 0 {
|
||||
continue;
|
||||
}
|
||||
if q[0].sifts {
|
||||
val s := this.sieve_of(q, m);
|
||||
for row in 0..rows {
|
||||
continue if !s.passes(row, p.since);
|
||||
s.stamp(row, p.now);
|
||||
var c1 := this.cursor_of(q, m, 0, row);
|
||||
var c2 := this.cursor_of(q, m, 1, row);
|
||||
var c3 := this.cursor_of(q, m, 2, row);
|
||||
var c4 := this.cursor_of(q, m, 3, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
var c1 := this.cursor_of(q, m, 0, 0);
|
||||
var c2 := this.cursor_of(q, m, 1, 0);
|
||||
var c3 := this.cursor_of(q, m, 2, 0);
|
||||
var c4 := this.cursor_of(q, m, 3, 0);
|
||||
for _ in 0..rows {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4));
|
||||
}
|
||||
}
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def world::walk_parallel<F, T1, T2, T3, T4>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>()]);
|
||||
val p := this.begin_pass(last);
|
||||
var work := task::<F>{ owner = address(this), query = q, call = &mut f, since = p.since, now = p.now };
|
||||
this.run_pieces(q, p, &mut work as *mut u8, run_piece4::<F, T1, T2, T3, T4>);
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def run_piece4<F, T1, T2, T3, T4>(context: *mut u8, at: &piece): void where F: invokable<def(T1, T2, T3, T4): void> {
|
||||
val work := &mut through(context as *mut task<F>);
|
||||
val w := &mut through(work.owner);
|
||||
val f := &mut through(work.call);
|
||||
if work.query[0].sifts {
|
||||
val s := w.sieve_of(work.query, at.which);
|
||||
for row in at.begin..at.end {
|
||||
continue if !s.passes(row, work.since);
|
||||
s.stamp(row, work.now);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, row);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, row);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, row);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4));
|
||||
}
|
||||
return;
|
||||
}
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, at.begin);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, at.begin);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, at.begin);
|
||||
for _ in at.begin..at.end {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4));
|
||||
}
|
||||
}
|
||||
|
||||
def world::walk<F, T1, T2, T3, T4, T5>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4, T5): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>(), param_for::<T5>()]);
|
||||
val p := this.begin_pass(last);
|
||||
for m in 0..q[0].matched.length {
|
||||
val rows := this.rows_of(q, m, p.since, p.now);
|
||||
if rows == 0 {
|
||||
continue;
|
||||
}
|
||||
if q[0].sifts {
|
||||
val s := this.sieve_of(q, m);
|
||||
for row in 0..rows {
|
||||
continue if !s.passes(row, p.since);
|
||||
s.stamp(row, p.now);
|
||||
var c1 := this.cursor_of(q, m, 0, row);
|
||||
var c2 := this.cursor_of(q, m, 1, row);
|
||||
var c3 := this.cursor_of(q, m, 2, row);
|
||||
var c4 := this.cursor_of(q, m, 3, row);
|
||||
var c5 := this.cursor_of(q, m, 4, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
var c1 := this.cursor_of(q, m, 0, 0);
|
||||
var c2 := this.cursor_of(q, m, 1, 0);
|
||||
var c3 := this.cursor_of(q, m, 2, 0);
|
||||
var c4 := this.cursor_of(q, m, 3, 0);
|
||||
var c5 := this.cursor_of(q, m, 4, 0);
|
||||
for _ in 0..rows {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5));
|
||||
}
|
||||
}
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def world::walk_parallel<F, T1, T2, T3, T4, T5>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4, T5): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>(), param_for::<T5>()]);
|
||||
val p := this.begin_pass(last);
|
||||
var work := task::<F>{ owner = address(this), query = q, call = &mut f, since = p.since, now = p.now };
|
||||
this.run_pieces(q, p, &mut work as *mut u8, run_piece5::<F, T1, T2, T3, T4, T5>);
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def run_piece5<F, T1, T2, T3, T4, T5>(context: *mut u8, at: &piece): void where F: invokable<def(T1, T2, T3, T4, T5): void> {
|
||||
val work := &mut through(context as *mut task<F>);
|
||||
val w := &mut through(work.owner);
|
||||
val f := &mut through(work.call);
|
||||
if work.query[0].sifts {
|
||||
val s := w.sieve_of(work.query, at.which);
|
||||
for row in at.begin..at.end {
|
||||
continue if !s.passes(row, work.since);
|
||||
s.stamp(row, work.now);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, row);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, row);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, row);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, row);
|
||||
var c5 := w.cursor_of(work.query, at.which, 4, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5));
|
||||
}
|
||||
return;
|
||||
}
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, at.begin);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, at.begin);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, at.begin);
|
||||
var c5 := w.cursor_of(work.query, at.which, 4, at.begin);
|
||||
for _ in at.begin..at.end {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5));
|
||||
}
|
||||
}
|
||||
|
||||
def world::walk<F, T1, T2, T3, T4, T5, T6>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4, T5, T6): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>(), param_for::<T5>(), param_for::<T6>()]);
|
||||
val p := this.begin_pass(last);
|
||||
for m in 0..q[0].matched.length {
|
||||
val rows := this.rows_of(q, m, p.since, p.now);
|
||||
if rows == 0 {
|
||||
continue;
|
||||
}
|
||||
if q[0].sifts {
|
||||
val s := this.sieve_of(q, m);
|
||||
for row in 0..rows {
|
||||
continue if !s.passes(row, p.since);
|
||||
s.stamp(row, p.now);
|
||||
var c1 := this.cursor_of(q, m, 0, row);
|
||||
var c2 := this.cursor_of(q, m, 1, row);
|
||||
var c3 := this.cursor_of(q, m, 2, row);
|
||||
var c4 := this.cursor_of(q, m, 3, row);
|
||||
var c5 := this.cursor_of(q, m, 4, row);
|
||||
var c6 := this.cursor_of(q, m, 5, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
var c1 := this.cursor_of(q, m, 0, 0);
|
||||
var c2 := this.cursor_of(q, m, 1, 0);
|
||||
var c3 := this.cursor_of(q, m, 2, 0);
|
||||
var c4 := this.cursor_of(q, m, 3, 0);
|
||||
var c5 := this.cursor_of(q, m, 4, 0);
|
||||
var c6 := this.cursor_of(q, m, 5, 0);
|
||||
for _ in 0..rows {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6));
|
||||
}
|
||||
}
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def world::walk_parallel<F, T1, T2, T3, T4, T5, T6>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4, T5, T6): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>(), param_for::<T5>(), param_for::<T6>()]);
|
||||
val p := this.begin_pass(last);
|
||||
var work := task::<F>{ owner = address(this), query = q, call = &mut f, since = p.since, now = p.now };
|
||||
this.run_pieces(q, p, &mut work as *mut u8, run_piece6::<F, T1, T2, T3, T4, T5, T6>);
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def run_piece6<F, T1, T2, T3, T4, T5, T6>(context: *mut u8, at: &piece): void where F: invokable<def(T1, T2, T3, T4, T5, T6): void> {
|
||||
val work := &mut through(context as *mut task<F>);
|
||||
val w := &mut through(work.owner);
|
||||
val f := &mut through(work.call);
|
||||
if work.query[0].sifts {
|
||||
val s := w.sieve_of(work.query, at.which);
|
||||
for row in at.begin..at.end {
|
||||
continue if !s.passes(row, work.since);
|
||||
s.stamp(row, work.now);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, row);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, row);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, row);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, row);
|
||||
var c5 := w.cursor_of(work.query, at.which, 4, row);
|
||||
var c6 := w.cursor_of(work.query, at.which, 5, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6));
|
||||
}
|
||||
return;
|
||||
}
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, at.begin);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, at.begin);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, at.begin);
|
||||
var c5 := w.cursor_of(work.query, at.which, 4, at.begin);
|
||||
var c6 := w.cursor_of(work.query, at.which, 5, at.begin);
|
||||
for _ in at.begin..at.end {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6));
|
||||
}
|
||||
}
|
||||
|
||||
def world::walk<F, T1, T2, T3, T4, T5, T6, T7>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4, T5, T6, T7): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>(), param_for::<T5>(), param_for::<T6>(), param_for::<T7>()]);
|
||||
val p := this.begin_pass(last);
|
||||
for m in 0..q[0].matched.length {
|
||||
val rows := this.rows_of(q, m, p.since, p.now);
|
||||
if rows == 0 {
|
||||
continue;
|
||||
}
|
||||
if q[0].sifts {
|
||||
val s := this.sieve_of(q, m);
|
||||
for row in 0..rows {
|
||||
continue if !s.passes(row, p.since);
|
||||
s.stamp(row, p.now);
|
||||
var c1 := this.cursor_of(q, m, 0, row);
|
||||
var c2 := this.cursor_of(q, m, 1, row);
|
||||
var c3 := this.cursor_of(q, m, 2, row);
|
||||
var c4 := this.cursor_of(q, m, 3, row);
|
||||
var c5 := this.cursor_of(q, m, 4, row);
|
||||
var c6 := this.cursor_of(q, m, 5, row);
|
||||
var c7 := this.cursor_of(q, m, 6, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6), take::<T7>(&mut c7));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
var c1 := this.cursor_of(q, m, 0, 0);
|
||||
var c2 := this.cursor_of(q, m, 1, 0);
|
||||
var c3 := this.cursor_of(q, m, 2, 0);
|
||||
var c4 := this.cursor_of(q, m, 3, 0);
|
||||
var c5 := this.cursor_of(q, m, 4, 0);
|
||||
var c6 := this.cursor_of(q, m, 5, 0);
|
||||
var c7 := this.cursor_of(q, m, 6, 0);
|
||||
for _ in 0..rows {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6), take::<T7>(&mut c7));
|
||||
}
|
||||
}
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def world::walk_parallel<F, T1, T2, T3, T4, T5, T6, T7>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4, T5, T6, T7): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>(), param_for::<T5>(), param_for::<T6>(), param_for::<T7>()]);
|
||||
val p := this.begin_pass(last);
|
||||
var work := task::<F>{ owner = address(this), query = q, call = &mut f, since = p.since, now = p.now };
|
||||
this.run_pieces(q, p, &mut work as *mut u8, run_piece7::<F, T1, T2, T3, T4, T5, T6, T7>);
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def run_piece7<F, T1, T2, T3, T4, T5, T6, T7>(context: *mut u8, at: &piece): void where F: invokable<def(T1, T2, T3, T4, T5, T6, T7): void> {
|
||||
val work := &mut through(context as *mut task<F>);
|
||||
val w := &mut through(work.owner);
|
||||
val f := &mut through(work.call);
|
||||
if work.query[0].sifts {
|
||||
val s := w.sieve_of(work.query, at.which);
|
||||
for row in at.begin..at.end {
|
||||
continue if !s.passes(row, work.since);
|
||||
s.stamp(row, work.now);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, row);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, row);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, row);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, row);
|
||||
var c5 := w.cursor_of(work.query, at.which, 4, row);
|
||||
var c6 := w.cursor_of(work.query, at.which, 5, row);
|
||||
var c7 := w.cursor_of(work.query, at.which, 6, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6), take::<T7>(&mut c7));
|
||||
}
|
||||
return;
|
||||
}
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, at.begin);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, at.begin);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, at.begin);
|
||||
var c5 := w.cursor_of(work.query, at.which, 4, at.begin);
|
||||
var c6 := w.cursor_of(work.query, at.which, 5, at.begin);
|
||||
var c7 := w.cursor_of(work.query, at.which, 6, at.begin);
|
||||
for _ in at.begin..at.end {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6), take::<T7>(&mut c7));
|
||||
}
|
||||
}
|
||||
|
||||
def world::walk<F, T1, T2, T3, T4, T5, T6, T7, T8>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4, T5, T6, T7, T8): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>(), param_for::<T5>(), param_for::<T6>(), param_for::<T7>(), param_for::<T8>()]);
|
||||
val p := this.begin_pass(last);
|
||||
for m in 0..q[0].matched.length {
|
||||
val rows := this.rows_of(q, m, p.since, p.now);
|
||||
if rows == 0 {
|
||||
continue;
|
||||
}
|
||||
if q[0].sifts {
|
||||
val s := this.sieve_of(q, m);
|
||||
for row in 0..rows {
|
||||
continue if !s.passes(row, p.since);
|
||||
s.stamp(row, p.now);
|
||||
var c1 := this.cursor_of(q, m, 0, row);
|
||||
var c2 := this.cursor_of(q, m, 1, row);
|
||||
var c3 := this.cursor_of(q, m, 2, row);
|
||||
var c4 := this.cursor_of(q, m, 3, row);
|
||||
var c5 := this.cursor_of(q, m, 4, row);
|
||||
var c6 := this.cursor_of(q, m, 5, row);
|
||||
var c7 := this.cursor_of(q, m, 6, row);
|
||||
var c8 := this.cursor_of(q, m, 7, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6), take::<T7>(&mut c7), take::<T8>(&mut c8));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
var c1 := this.cursor_of(q, m, 0, 0);
|
||||
var c2 := this.cursor_of(q, m, 1, 0);
|
||||
var c3 := this.cursor_of(q, m, 2, 0);
|
||||
var c4 := this.cursor_of(q, m, 3, 0);
|
||||
var c5 := this.cursor_of(q, m, 4, 0);
|
||||
var c6 := this.cursor_of(q, m, 5, 0);
|
||||
var c7 := this.cursor_of(q, m, 6, 0);
|
||||
var c8 := this.cursor_of(q, m, 7, 0);
|
||||
for _ in 0..rows {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6), take::<T7>(&mut c7), take::<T8>(&mut c8));
|
||||
}
|
||||
}
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def world::walk_parallel<F, T1, T2, T3, T4, T5, T6, T7, T8>(&mut this, by: &filter, last: &mut u64, f: F): void where F: invokable<def(T1, T2, T3, T4, T5, T6, T7, T8): void> {
|
||||
val q := this.query_of(by, [param_for::<T1>(), param_for::<T2>(), param_for::<T3>(), param_for::<T4>(), param_for::<T5>(), param_for::<T6>(), param_for::<T7>(), param_for::<T8>()]);
|
||||
val p := this.begin_pass(last);
|
||||
var work := task::<F>{ owner = address(this), query = q, call = &mut f, since = p.since, now = p.now };
|
||||
this.run_pieces(q, p, &mut work as *mut u8, run_piece8::<F, T1, T2, T3, T4, T5, T6, T7, T8>);
|
||||
this.end_pass();
|
||||
}
|
||||
|
||||
def run_piece8<F, T1, T2, T3, T4, T5, T6, T7, T8>(context: *mut u8, at: &piece): void where F: invokable<def(T1, T2, T3, T4, T5, T6, T7, T8): void> {
|
||||
val work := &mut through(context as *mut task<F>);
|
||||
val w := &mut through(work.owner);
|
||||
val f := &mut through(work.call);
|
||||
if work.query[0].sifts {
|
||||
val s := w.sieve_of(work.query, at.which);
|
||||
for row in at.begin..at.end {
|
||||
continue if !s.passes(row, work.since);
|
||||
s.stamp(row, work.now);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, row);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, row);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, row);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, row);
|
||||
var c5 := w.cursor_of(work.query, at.which, 4, row);
|
||||
var c6 := w.cursor_of(work.query, at.which, 5, row);
|
||||
var c7 := w.cursor_of(work.query, at.which, 6, row);
|
||||
var c8 := w.cursor_of(work.query, at.which, 7, row);
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6), take::<T7>(&mut c7), take::<T8>(&mut c8));
|
||||
}
|
||||
return;
|
||||
}
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, at.begin);
|
||||
var c3 := w.cursor_of(work.query, at.which, 2, at.begin);
|
||||
var c4 := w.cursor_of(work.query, at.which, 3, at.begin);
|
||||
var c5 := w.cursor_of(work.query, at.which, 4, at.begin);
|
||||
var c6 := w.cursor_of(work.query, at.which, 5, at.begin);
|
||||
var c7 := w.cursor_of(work.query, at.which, 6, at.begin);
|
||||
var c8 := w.cursor_of(work.query, at.which, 7, at.begin);
|
||||
for _ in at.begin..at.end {
|
||||
f(take::<T1>(&mut c1), take::<T2>(&mut c2), take::<T3>(&mut c3), take::<T4>(&mut c4), take::<T5>(&mut c5), take::<T6>(&mut c6), take::<T7>(&mut c7), take::<T8>(&mut c8));
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#! Contains `ecs`: entities, the components each has, and the systems
|
||||
#! that pass over them, kept so that a pass over many entities is a walk along
|
||||
#! arrays.
|
||||
#!
|
||||
#! A `world` keeps its entities in tables, one for each set of components some
|
||||
#! entity has, its archetype, a column for each component, so the entities of a
|
||||
#! set lie side by side, and a pass over those having some components walks the
|
||||
#! columns of the tables having them. A component is a value of any type, and
|
||||
#! one that closes what it holds, as a `string` does, is closed as its entity
|
||||
#! loses it, or is despawned, or the world closes.
|
||||
|
||||
module malunal::ecs;
|
||||
|
||||
#! An entity: a number its world knows a set of components by. Its low 32 bits
|
||||
#! are its index among the world's entities, and its high 32 its generation,
|
||||
#! which rises each time the index is used again, so an entity kept past its
|
||||
#! despawning is never taken for the one using its index after it.
|
||||
pub struct entity {
|
||||
pub val bits: u64;
|
||||
}
|
||||
|
||||
#! No entity: no world gives it, so it's never alive.
|
||||
pub val entity::none := entity{};
|
||||
|
||||
#! Its index among its world's entities.
|
||||
pub val entity::index: u32 {
|
||||
get => (this.bits & 0xFFFFFFFF) as u32;
|
||||
}
|
||||
|
||||
#! How many times its index has been used, itself included.
|
||||
pub val entity::generation: u32 {
|
||||
get => (this.bits >> 32) as u32;
|
||||
}
|
||||
|
||||
def entity::of(index: u32, generation: u32): entity {
|
||||
return entity{ bits = index as u64 | (generation as u64 << 32) };
|
||||
}
|
||||
|
||||
pub def entity::equals(&this, other: &entity): bool {
|
||||
return this.bits == other.bits;
|
||||
}
|
||||
|
||||
pub def entity::compare(&this, other: &entity): i64 {
|
||||
return this.bits < other.bits ? -1 : (this.bits > other.bits ? 1 : 0);
|
||||
}
|
||||
|
||||
pub def entity::hash(&this): u64 {
|
||||
return mixed(this.bits);
|
||||
}
|
||||
|
||||
#! Its index and generation, as `12v3`.
|
||||
pub def entity::show(&this): string {
|
||||
return $"{this.index}v{this.generation}";
|
||||
}
|
||||
|
||||
#! What a world knows of a type of component, made while compiling, one for
|
||||
#! each type.
|
||||
pub struct component_info {
|
||||
pub val key: u64; #! Which type it is: a hash of its path, the same in every program.
|
||||
pub val name: strview; #! Its name, as `position`.
|
||||
pub val path: strview; #! Its name with the module of each type it names, as `game::position`, which no two types share.
|
||||
pub val size: u64; #! The bytes of one, 0 for a tag, which holds nothing.
|
||||
pub val align: u64; #! What its address is a multiple of.
|
||||
pub val closes: bool; #! Whether one closes what it holds.
|
||||
val dispose: def(*mut u8): void; # Closes the one at an address.
|
||||
}
|
||||
|
||||
# Each type's `component_info`, a constant: its address is the same wherever
|
||||
# it's asked for, and it lasts as long as the program.
|
||||
def info_of<T>(): *component_info {
|
||||
const made: component_info = component_info{
|
||||
key = hash_text(path_of::<T>(), fnv_basis),
|
||||
name = name_of::<T>(),
|
||||
path = path_of::<T>(),
|
||||
size = size_of::<T>(),
|
||||
align = align_of::<T>(),
|
||||
closes = T is closeable,
|
||||
dispose = close_at::<T>,
|
||||
};
|
||||
return &made;
|
||||
}
|
||||
|
||||
# The `component_info` of a value's type, for the values of a pack.
|
||||
def info_of_value<T>(value: &T): *component_info {
|
||||
return info_of::<T>();
|
||||
}
|
||||
|
||||
# Closes the value at an address, a `T`.
|
||||
def close_at<T>(at: *mut u8): void {
|
||||
close(&mut through(at as *mut T));
|
||||
}
|
||||
|
||||
# Moves a value into memory that holds none, leaving it empty: plain data by
|
||||
# a store of its type, and what closes byte for byte, as nothing there is
|
||||
# closed first.
|
||||
def place<T>(at: *mut u8, value: &mut T): void {
|
||||
if const T is closeable {
|
||||
memcpy(at, value as *u8, size_of::<T>());
|
||||
emptied(value);
|
||||
} else {
|
||||
through(at as *mut T) = value;
|
||||
}
|
||||
}
|
||||
|
||||
const fnv_basis: u64 = 0xCBF29CE484222325;
|
||||
|
||||
# FNV-1a of text, from a seed, while compiling as well as running.
|
||||
const def hash_text(text: strview, seed: u64): u64 {
|
||||
var h := seed;
|
||||
for i in 0..text.length {
|
||||
h = (h ^ text[i] as u64) * 0x100000001B3;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
# A number's bits mixed, so that numbers near one another hash far apart.
|
||||
def mixed(x: u64): u64 {
|
||||
var z := x ^ (x >> 30);
|
||||
z = z * 0xBF58476D1CE4E5B9;
|
||||
z = z ^ (z >> 27);
|
||||
z = z * 0x94D049BB133111EB;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
#! Contains `idmap`, the table of numbers by 64-bit keys that a world looks
|
||||
#! things up in on every call: a type of component by its key, a table by the
|
||||
#! hash of its components, an edge between tables, and a query by what it asks.
|
||||
|
||||
module malunal::ecs;
|
||||
|
||||
# Numbers by 64-bit keys, held open: a key's place is its hash, or the first
|
||||
# empty one after it, so a lookup reads one or two places of one array. Keys
|
||||
# are never 0, which marks a place empty, and nothing is ever taken out.
|
||||
struct idmap : owning {
|
||||
var keys: *mut u64;
|
||||
var values: *mut u32;
|
||||
var capacity: u64; # A power of two, or 0.
|
||||
var count: u64;
|
||||
var shift: u64; # 64 less the bits of the capacity.
|
||||
}
|
||||
|
||||
# What `get` gives for a key it doesn't hold.
|
||||
const absent: u32 = 0xFFFFFFFF;
|
||||
|
||||
def idmap::new(): idmap {
|
||||
return idmap{};
|
||||
}
|
||||
|
||||
# The key as held: 0 is taken for another, as 0 marks a place empty.
|
||||
def idmap::held(key: u64): u64 {
|
||||
return key == 0 ? 0x9E3779B97F4A7C15 : key;
|
||||
}
|
||||
|
||||
def idmap::get(&this, key: u64): u32 {
|
||||
return absent if this.capacity == 0;
|
||||
val k := idmap::held(key);
|
||||
var at := (k * 0x9E3779B97F4A7C15) >> this.shift;
|
||||
while true {
|
||||
val there := this.keys[at];
|
||||
return this.values[at] if there == k;
|
||||
return absent if there == 0;
|
||||
at = (at + 1) & (this.capacity - 1);
|
||||
}
|
||||
return absent;
|
||||
}
|
||||
|
||||
def idmap::set(&mut this, key: u64, value: u32): void {
|
||||
if (this.count + 1) * 2 > this.capacity {
|
||||
this.grow();
|
||||
}
|
||||
val k := idmap::held(key);
|
||||
var at := (k * 0x9E3779B97F4A7C15) >> this.shift;
|
||||
while true {
|
||||
val there := this.keys[at];
|
||||
if there == k {
|
||||
this.values[at] = value;
|
||||
return;
|
||||
}
|
||||
if there == 0 {
|
||||
this.keys[at] = k;
|
||||
this.values[at] = value;
|
||||
this.count++;
|
||||
return;
|
||||
}
|
||||
at = (at + 1) & (this.capacity - 1);
|
||||
}
|
||||
}
|
||||
|
||||
def idmap::grow(&mut this): void {
|
||||
val old_keys := this.keys;
|
||||
val old_values := this.values;
|
||||
val old := this.capacity;
|
||||
this.capacity = old == 0 ? 16 : old * 2;
|
||||
var bits := 0u;
|
||||
while (1u << bits) < this.capacity { bits++; }
|
||||
this.shift = 64 - bits;
|
||||
this.keys = raw_allocate_zeroed(this.capacity * 8) as *mut u64;
|
||||
this.values = raw_allocate(this.capacity * 4) as *mut u32;
|
||||
this.count = 0;
|
||||
for i in 0..old {
|
||||
if old_keys[i] != 0 {
|
||||
this.set(old_keys[i], old_values[i]);
|
||||
}
|
||||
}
|
||||
raw_release(old_keys as *mut u8);
|
||||
raw_release(old_values as *mut u8);
|
||||
}
|
||||
|
||||
pub def idmap::close(&mut this): void {
|
||||
raw_release(this.keys as *mut u8);
|
||||
raw_release(this.values as *mut u8);
|
||||
this.keys = null;
|
||||
this.values = null;
|
||||
this.capacity = 0;
|
||||
this.count = 0;
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
#! Contains reaching components and resources by their types' keys rather than
|
||||
#! their types, as a program does for code it runs that names a type the
|
||||
#! program doesn't, as an engine running scripts does: a key, and the
|
||||
#! bytes of a value, laid out as both build the type from one declaration.
|
||||
|
||||
module malunal::ecs;
|
||||
|
||||
#! The key a type of component is known by: a hash of its `path_of`, the same in
|
||||
#! every world, and in every program declaring the type.
|
||||
pub def component_key<T>(): u64 {
|
||||
return info_of::<T>()[0].key;
|
||||
}
|
||||
|
||||
#! The key a type is known by, of its path, as `game::position`: what
|
||||
#! `component_key` gives of the type, for a program that knows a type only by
|
||||
#! its path, as one reading what a function takes from its type's spelling.
|
||||
pub def key_of_path(path: strview): u64 {
|
||||
return hash_text(path, fnv_basis);
|
||||
}
|
||||
|
||||
#! What a world knows of a type of plain data, which closes nothing, made as a
|
||||
#! program runs rather than while it compiles, as a program makes one for a
|
||||
#! type of component a script declares. A world keeps its address, which, and
|
||||
#! the texts it views, must outlast every world meeting it.
|
||||
pub def component_info::plain(key: u64, name: strview, path: strview, size: u64, align: u64): component_info {
|
||||
return component_info{
|
||||
key = key,
|
||||
name = name,
|
||||
path = path,
|
||||
size = size,
|
||||
align = align,
|
||||
closes = false,
|
||||
dispose = close_nothing,
|
||||
};
|
||||
}
|
||||
|
||||
# Closes nothing, as plain data holds nothing to close.
|
||||
def close_nothing(at: *mut u8): void {}
|
||||
|
||||
#! What the world knows of the type of a key, or `null` where it never met it.
|
||||
pub def world::info_by_key(&this, key: u64): *component_info {
|
||||
val id := this.by_key.get(key);
|
||||
return id == absent ? null : this.infos[id as u64];
|
||||
}
|
||||
|
||||
#! An entity's component of the type of a key, or `null` where it lacks one, or
|
||||
#! it's a tag. It lasts until the entity next moves, as `get`'s does.
|
||||
pub def world::get_by_key(&this, e: entity, key: u64): *mut u8 {
|
||||
return this.value_of(e, this.by_key.get(key));
|
||||
}
|
||||
|
||||
#! Whether an entity has a component of the type of a key.
|
||||
pub def world::has_by_key(&this, e: entity, key: u64): bool {
|
||||
return this.has_id(e, this.by_key.get(key));
|
||||
}
|
||||
|
||||
#! Gives an entity a component, moving the bytes of a value in, which the
|
||||
#! caller lets go of, or replaces the one it has, closing it: as `set` does, so
|
||||
#! it's given once a pass over the world ends. The world may not have met the
|
||||
#! type, whose `info` it keeps; one it met is the same size.
|
||||
pub def world::set_by_info(&mut this, e: entity, info: *component_info, from: *mut u8): void {
|
||||
if !this.alive(e) {
|
||||
if this.awaited(e) {
|
||||
this.defer_put(e, info, from);
|
||||
return;
|
||||
}
|
||||
fault($"`set_by_info` was given {e.show()}, which isn't alive.");
|
||||
}
|
||||
if this.deferring > 0 {
|
||||
# One it has is replaced where it is, at once.
|
||||
val id := this.find_id(info);
|
||||
val r: record = this.records[e.index as u64];
|
||||
if id != absent && 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.wrote(slot, id, r.row as u64, this.stamp());
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.defer_put(e, info, from);
|
||||
return;
|
||||
}
|
||||
this.set_bytes(e, info, from);
|
||||
}
|
||||
|
||||
#! Takes an entity's component of the type of a key, closing it, once a pass
|
||||
#! over the world ends, as `remove` does.
|
||||
#! @returns Whether the entity had it.
|
||||
pub def world::remove_by_key(&mut this, e: entity, key: u64): bool {
|
||||
val id := this.by_key.get(key);
|
||||
return false if !this.has_id(e, id);
|
||||
if this.deferring > 0 {
|
||||
this.defer(op::remove, e, this.infos[id as u64]);
|
||||
} else {
|
||||
this.remove_now(e, id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The world's resource of the type of a key, or `null` where it holds none.
|
||||
pub def world::resource_by_key(&mut this, key: u64): *mut u8 {
|
||||
val found := this.by_resource.get(key);
|
||||
return null if found == absent;
|
||||
return this.resources[found as u64].data;
|
||||
}
|
||||
|
||||
#! What the world knows of the type of a resource's key, or `null` where it
|
||||
#! holds none.
|
||||
pub def world::resource_info_by_key(&this, key: u64): *component_info {
|
||||
val found := this.by_resource.get(key);
|
||||
return found == absent ? null : this.resources[found as u64].info;
|
||||
}
|
||||
|
||||
#! Gives the world a resource, moving the bytes of a value in, which the caller
|
||||
#! lets go of, or replaces the one it holds, closing it, as `set_resource` does.
|
||||
#! The world may not have met the type, whose `info` it keeps; one it met is the
|
||||
#! same size.
|
||||
pub def world::set_resource_by_info(&mut this, info: *component_info, from: *mut u8): void {
|
||||
this.refuse_while_shared("be given resources");
|
||||
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.info[0].size != info[0].size {
|
||||
fault($"`set_resource_by_info` was given `{info[0].path}` of {info[0].size} bytes, which the world holds of {held.info[0].size}.");
|
||||
}
|
||||
if held.data == null {
|
||||
held.data = raw_allocate(info[0].size == 0 ? 1 : info[0].size);
|
||||
} else if held.info[0].closes {
|
||||
held.info[0].dispose(held.data);
|
||||
}
|
||||
memcpy(held.data, from, info[0].size);
|
||||
}
|
||||
|
||||
#! Appends each entity having a component of the type of a key, table by table.
|
||||
pub def world::entities_by_key(&this, key: u64, into: &mut vector<entity>): void {
|
||||
val id := this.by_key.get(key);
|
||||
return if id == absent;
|
||||
for i in 0..this.tables.length {
|
||||
val t := &this.tables[i];
|
||||
continue if !t.has(id);
|
||||
for row in 0..t.count {
|
||||
into.append(t.entities[row]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
#! Contains observers: functions a world runs as an entity is given a
|
||||
#! component, or loses one, as a game keeps what follows from it up to date.
|
||||
|
||||
module malunal::ecs;
|
||||
|
||||
#! What an observer runs on: an entity given a component it lacked, or losing
|
||||
#! one, as it's taken or the entity despawned.
|
||||
pub enum change: u8 {
|
||||
added,
|
||||
removed,
|
||||
}
|
||||
|
||||
#! An observer a world runs, which `unobserve` takes out.
|
||||
pub struct observer {
|
||||
val index: u64;
|
||||
}
|
||||
|
||||
# An observer: the component it watches, the change it runs on, and what it
|
||||
# runs, or nothing once taken out.
|
||||
struct watch {
|
||||
var id: u32;
|
||||
var on: change;
|
||||
var run: def(&mut world, entity): void;
|
||||
var live: bool;
|
||||
}
|
||||
|
||||
#! Runs a function each time an entity is given a component it lacked, or
|
||||
#! loses one, given the world and the entity: as it's given, once the value is
|
||||
#! there, or as it loses it, while the value still is, so it reads it. Several
|
||||
#! observe a component in the order they were added.
|
||||
#!
|
||||
#! What it changes that would move an entity, as a component given or taken, a
|
||||
#! spawn, or a despawn, is made once the change it observed is done, as the
|
||||
#! world defers it, and runs observers in turn. A component replaced, or
|
||||
#! written, runs none. Observers run on the world's thread, once what threads
|
||||
#! sharing it deferred is made.
|
||||
#!
|
||||
#! ```sakura
|
||||
#! _ = w.observe::<health>(change::removed, def(w, e) { ... });
|
||||
#! ```
|
||||
#! @remarks A lambda's captures must outlast the world, which keeps it.
|
||||
pub def world::observe<T>(&mut this, on: change, run: def(&mut world, entity): void): observer {
|
||||
this.refuse_while_shared("be given observers");
|
||||
if this.parallel {
|
||||
fault("A function `par_each` calls can't give the world observers.");
|
||||
}
|
||||
val id := this.id_of(info_of::<T>());
|
||||
this.watches.append(watch{ id = id, on = on, run = run, live = true });
|
||||
while this.watched.length <= id as u64 {
|
||||
this.watched.append(0 as u8);
|
||||
}
|
||||
this.watched[id as u64] |= bit_of(on);
|
||||
return observer{ index = this.watches.length - 1 };
|
||||
}
|
||||
|
||||
#! Takes out an observer, which runs no more.
|
||||
#! @returns Whether it ran till now.
|
||||
pub def world::unobserve(&mut this, o: observer): bool {
|
||||
this.refuse_while_shared("have observers taken");
|
||||
return false if o.index >= this.watches.length || !this.watches[o.index].live;
|
||||
val w := &mut this.watches[o.index];
|
||||
w.live = false;
|
||||
var still: u8 = 0;
|
||||
for i in 0..this.watches.length {
|
||||
val each := &this.watches[i];
|
||||
if each.live && each.id == w.id {
|
||||
still |= bit_of(each.on);
|
||||
}
|
||||
}
|
||||
this.watched[w.id as u64] = still;
|
||||
return true;
|
||||
}
|
||||
|
||||
def bit_of(on: change): u8 {
|
||||
return on == change::added ? 1 as u8 : 2 as u8;
|
||||
}
|
||||
|
||||
# Whether any observer watches a component, for a change.
|
||||
def world::watches_for(&this, id: u32, on: change): bool {
|
||||
return id < this.watched.length && (this.watched[id as u64] & bit_of(on)) != 0;
|
||||
}
|
||||
|
||||
# Runs the observers of a change to an entity's component, the world
|
||||
# deferring what they change till the change they observed is done.
|
||||
def world::notify(&mut this, e: entity, id: u32, on: change): void {
|
||||
return if !this.watches_for(id, on);
|
||||
this.deferring++;
|
||||
for i in 0..this.watches.length {
|
||||
val each: watch = this.watches[i];
|
||||
if each.live && each.id == id && each.on == on {
|
||||
val run := each.run;
|
||||
run(this, e);
|
||||
}
|
||||
}
|
||||
this.deferring--;
|
||||
}
|
||||
|
||||
# Runs the observers of an entity given each component of a table, as it's
|
||||
# spawned with them.
|
||||
def world::notify_all(&mut this, e: entity, table: u32, on: change): void {
|
||||
return if this.watches.length == 0;
|
||||
val count := this.tables[table as u64].ids.length;
|
||||
for i in 0..count {
|
||||
this.notify(e, this.tables[table as u64].ids[i], on);
|
||||
}
|
||||
}
|
||||
|
||||
# Makes what observers deferred, once a change is done, where no pass goes
|
||||
# over the world.
|
||||
def world::settle(&mut this): void {
|
||||
if this.deferring == 0 && this.pending.length > 0 {
|
||||
this.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
#! 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 malunal::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.
|
||||
added, # That it has one, given it 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 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;
|
||||
}
|
||||
|
||||
#! 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 had written, or been given, since the query last
|
||||
#! passed. A program knowing a type only by its path names it so, as
|
||||
#! `with_path("game::player")`.
|
||||
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 whose component was written since the query
|
||||
#! last passed over them.
|
||||
pub def changed<T>(): filter {
|
||||
val none := filter{};
|
||||
return none.changed::<T>();
|
||||
}
|
||||
|
||||
#! A filter passing the entities given a component since the query last passed
|
||||
#! over them.
|
||||
pub def added<T>(): filter {
|
||||
val none := filter{};
|
||||
return none.added::<T>();
|
||||
}
|
||||
|
||||
#! The filter, passing only the entities having a component too.
|
||||
pub def filter::with<T>(&this): filter {
|
||||
return this.and(path_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(path_of::<T>(), term_kind::lacks);
|
||||
}
|
||||
|
||||
#! The filter, passing only the entities having a component written since the
|
||||
#! query last passed over them, too: by a pass taking it as `&mut T`, a
|
||||
#! chunk's `write`, or `set`, or given it. A value written through `get` isn't
|
||||
#! known as written. The world knows when each entity's was written once some
|
||||
#! query asks, and of no component no query asks of, so passes over those cost
|
||||
#! nothing more; a query's first pass finds every entity changed.
|
||||
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(path_of::<T>(), term_kind::changed);
|
||||
}
|
||||
|
||||
#! The filter, passing only the entities given a component since the query
|
||||
#! last passed over them, too: spawned with it, or given it as they lacked it.
|
||||
#! A tag is given too. A query's first pass finds every entity given it.
|
||||
pub def filter::added<T>(&this): filter {
|
||||
return this.and(path_of::<T>(), term_kind::added);
|
||||
}
|
||||
|
||||
#! A filter passing the entities having a component, named by its type's path,
|
||||
#! as `game::position`, as a program knowing a type only by its path names it:
|
||||
#! what `with` gives of the type. The text must outlast the queries asking it.
|
||||
pub def with_path(path: strview): filter {
|
||||
val none := filter{};
|
||||
return none.with_path(path);
|
||||
}
|
||||
|
||||
#! A filter passing the entities lacking a component, named by its type's path.
|
||||
pub def without_path(path: strview): filter {
|
||||
val none := filter{};
|
||||
return none.without_path(path);
|
||||
}
|
||||
|
||||
#! A filter passing the entities of tables whose component, named by its type's
|
||||
#! path, was written since the query last passed over them. A tag is never
|
||||
#! written, so none pass.
|
||||
pub def changed_path(path: strview): filter {
|
||||
val none := filter{};
|
||||
return none.changed_path(path);
|
||||
}
|
||||
|
||||
#! The filter, passing only the entities having a component, named by its
|
||||
#! type's path, too.
|
||||
pub def filter::with_path(&this, path: strview): filter {
|
||||
return this.and(path, term_kind::has);
|
||||
}
|
||||
|
||||
#! The filter, passing only the entities lacking a component, named by its
|
||||
#! type's path, too.
|
||||
pub def filter::without_path(&this, path: strview): filter {
|
||||
return this.and(path, term_kind::lacks);
|
||||
}
|
||||
|
||||
#! The filter, passing only the entities having a component, named by its
|
||||
#! type's path, written since the query last passed over them, too.
|
||||
pub def filter::changed_path(&this, path: strview): filter {
|
||||
return this.and(path, term_kind::changed);
|
||||
}
|
||||
|
||||
#! A filter passing the entities given a component, named by its type's path,
|
||||
#! since the query last passed over them.
|
||||
pub def added_path(path: strview): filter {
|
||||
val none := filter{};
|
||||
return none.added_path(path);
|
||||
}
|
||||
|
||||
#! The filter, passing only the entities given a component, named by its
|
||||
#! type's path, since the query last passed over them, too.
|
||||
pub def filter::added_path(&this, path: strview): filter {
|
||||
return this.and(path, term_kind::added);
|
||||
}
|
||||
|
||||
def filter::and(&this, path: strview, 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{ name = path, hash = key_of_path(path), 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, each found by its type's
|
||||
# key once the world meets the type.
|
||||
struct term {
|
||||
var name: strview;
|
||||
var hash: u64;
|
||||
var kind: term_kind;
|
||||
var id: u32; # Or `absent`, for a 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'.
|
||||
var sifts: bool; # Whether it asks what was added or changed of each entity.
|
||||
}
|
||||
|
||||
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. It stays where it is, so a pass
|
||||
# keeps its address while threads sharing the world find others.
|
||||
def world::query_of(&mut this, by: &filter, params: span<param>): *mut query_state {
|
||||
if this.parallel {
|
||||
fault("A function `par_each` calls can't query the world itself.");
|
||||
}
|
||||
this.lock();
|
||||
val found := this.find_query(by, params);
|
||||
this.unlock();
|
||||
return found;
|
||||
}
|
||||
|
||||
def world::find_query(&mut this, by: &filter, params: span<param>): *mut query_state {
|
||||
var key := fnv_basis;
|
||||
for i in 0..by.count {
|
||||
key = mixed(key ^ by.terms[i].hash) + 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 {
|
||||
val known := address(this.queries[found as u64].get());
|
||||
this.refresh(known);
|
||||
return known;
|
||||
}
|
||||
|
||||
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{ name = t.name, hash = t.hash, kind = t.kind, id = absent });
|
||||
made.sifts = made.sifts || t.kind == term_kind::changed || t.kind == term_kind::added;
|
||||
}
|
||||
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(box::new(move(made)));
|
||||
this.cached.set(key, index);
|
||||
val st := address(this.queries[index as u64].get());
|
||||
this.refresh(st);
|
||||
return st;
|
||||
}
|
||||
|
||||
# Finds the types of a query's terms that the world hadn't met, by their
|
||||
# paths, whose hashes are their keys.
|
||||
def world::resolve(&mut this, at: *mut query_state): void {
|
||||
val st := &mut through(at);
|
||||
return if st.known == this.infos.length;
|
||||
st.known = this.infos.length;
|
||||
var found := false;
|
||||
for i in 0..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 t.kind == term_kind::changed || t.kind == term_kind::added {
|
||||
this.track(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
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, at: *mut query_state): void {
|
||||
this.resolve(at);
|
||||
val st := &mut through(at);
|
||||
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::added, 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, or,
|
||||
# where threads share it, until the sharing does.
|
||||
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.");
|
||||
}
|
||||
if !this.sharing {
|
||||
this.deferring++;
|
||||
}
|
||||
val now := this.next_tick();
|
||||
val since := last;
|
||||
last = now;
|
||||
return pass{ since = since, now = now };
|
||||
}
|
||||
|
||||
def world::end_pass(&mut this): void {
|
||||
return if this.sharing;
|
||||
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 the table may
|
||||
# have none, and all of them otherwise, which a pass asking of each entity
|
||||
# sifts. Stamps the columns the pass writes, and, where it goes over each row,
|
||||
# each entity's.
|
||||
def world::rows_of(&mut this, at: *mut query_state, m: u64, since: u64, now: u64): u64 {
|
||||
return 0 if !this.table_passes(at, m, since);
|
||||
val st := &through(at);
|
||||
val t := &mut this.tables[st.matched[m] as u64];
|
||||
val stride := st.terms.length;
|
||||
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 {
|
||||
if st.sifts {
|
||||
t.columns[slot as u64].changed = now;
|
||||
} else {
|
||||
t.wrote_all(slot, st.terms[i].id, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
return t.count;
|
||||
}
|
||||
|
||||
# Whether a table a query matched may have entities its pass goes over: it has
|
||||
# some, and where the query asks what was written or given since it last
|
||||
# passed, a column was written, or an entity came in, since; or it never did.
|
||||
def world::table_passes(&this, at: *mut query_state, m: u64, since: u64): bool {
|
||||
val st := &through(at);
|
||||
val t := &this.tables[st.matched[m] as u64];
|
||||
return false if t.count == 0;
|
||||
val stride := st.terms.length;
|
||||
for i in 0..stride {
|
||||
val kind := st.terms[i].kind;
|
||||
if kind == term_kind::changed {
|
||||
val slot := st.slots[m * stride + i];
|
||||
return false if slot >= tagged || (since > 0 && t.columns[slot as u64].changed <= since);
|
||||
} else if kind == term_kind::added {
|
||||
return false if since > 0 && t.added <= since;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# 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, at: *mut query_state, m: u64, index: u64, from: u64): cursor {
|
||||
val st := &through(at);
|
||||
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: where it asks what was written or
|
||||
#! given, since the query last passed, which counting doesn't move on.
|
||||
pub def query::count(&mut this): u64 {
|
||||
val w := &mut through(this.owner);
|
||||
val st := w.query_of(&this.by, span::<param>::blank());
|
||||
var total := 0u;
|
||||
for m in 0..st[0].matched.length {
|
||||
continue if !w.table_passes(st, m, this.last);
|
||||
val rows := w.tables[st[0].matched[m] as u64].count;
|
||||
if st[0].sifts {
|
||||
val s := w.sieve_of(st, m);
|
||||
for row in 0..rows {
|
||||
if s.passes(row, this.last) {
|
||||
total++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
total += rows;
|
||||
}
|
||||
}
|
||||
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>::blank());
|
||||
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. Where the
|
||||
#! query asks what was written or given of each entity, `passes` says which.
|
||||
pub struct chunk {
|
||||
var owner: *mut world;
|
||||
var table: u32;
|
||||
pub val length: u64; #! How many entities.
|
||||
var now: u64;
|
||||
var since: u64;
|
||||
var test: sieve;
|
||||
}
|
||||
|
||||
#! Whether an entity of it, by its place, passes what its query asks of each
|
||||
#! entity: what was written or given since the query last passed. Where it
|
||||
#! asks neither, every one does.
|
||||
pub def chunk::passes(&this, index: u64): bool {
|
||||
return this.test.passes(index, this.since);
|
||||
}
|
||||
|
||||
#! 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, each of them.
|
||||
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.wrote_all(slot, id, 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, iter<chunk> {
|
||||
var owner: *mut world;
|
||||
var query: *mut query_state;
|
||||
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 := this.query[0].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 := this.query[0].matched[m];
|
||||
return chunk{ owner = this.owner, table = table, length = rows, now = this.now, since = this.since, test = w.sieve_of(this.query, m) };
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
#! Contains relationships: parents and children, which a world keeps of its
|
||||
#! own, as a scene's transforms are within their parents', and despawns
|
||||
#! together.
|
||||
|
||||
import std::containers;
|
||||
module malunal::ecs;
|
||||
|
||||
#! The entity an entity is a child of, which `world::set_parent` gives it: it's
|
||||
#! despawned with its parent, and its parent's `children` lists it.
|
||||
pub struct child_of {
|
||||
val of: entity;
|
||||
}
|
||||
|
||||
#! Its parent.
|
||||
pub val child_of::parent: entity {
|
||||
get => this.of;
|
||||
}
|
||||
|
||||
#! The children of an entity, in the order they were given it, which the world
|
||||
#! keeps as its children are given and taken.
|
||||
pub struct children : owning {
|
||||
var list: vector<entity>;
|
||||
}
|
||||
|
||||
pub def children::close(&mut this): void {
|
||||
this.list.close();
|
||||
}
|
||||
|
||||
#! How many it has.
|
||||
pub val children::length: u64 {
|
||||
get => this.list.length;
|
||||
}
|
||||
|
||||
#! Them, in order.
|
||||
pub val children::span: span<entity> {
|
||||
get => this.list.span;
|
||||
}
|
||||
|
||||
#! One of them, by its place in the order.
|
||||
pub def children::at(&this, index: u64): entity {
|
||||
return this.list[index];
|
||||
}
|
||||
|
||||
#! Makes an entity a child of another: it's despawned with it, and its parent's
|
||||
#! `children` lists it, last. It leaves the parent it had. Where a pass goes
|
||||
#! over the world, it's made as the pass ends, as what moves an entity is.
|
||||
#! @param this The world.
|
||||
#! @param child The entity.
|
||||
#! @param parent Its parent, which mustn't be the child or within it.
|
||||
pub def world::set_parent(&mut this, child: entity, parent: entity): void {
|
||||
if (!this.alive(child) && !this.awaited(child)) || (!this.alive(parent) && !this.awaited(parent)) {
|
||||
fault("`set_parent` was given an entity that isn't alive.");
|
||||
}
|
||||
if this.deferring > 0 {
|
||||
this.lock();
|
||||
this.pending.list.append(command{ what = op::parent, who = child, at = parent.bits });
|
||||
this.unlock();
|
||||
return;
|
||||
}
|
||||
this.set_parent_now(child, parent);
|
||||
}
|
||||
|
||||
#! Takes an entity from its parent, so it's of the world itself, as `set_parent`
|
||||
#! makes a child, once a pass ends.
|
||||
#! @returns Whether it had one.
|
||||
pub def world::remove_parent(&mut this, child: entity): bool {
|
||||
return false if !this.has_id(child, this.child_of_id);
|
||||
if this.deferring > 0 {
|
||||
this.defer(op::unparent, child, null);
|
||||
} else {
|
||||
this.remove_now(child, this.child_of_id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The parent of an entity, where it has one.
|
||||
pub def world::parent_of(&this, child: entity): maybe<entity> {
|
||||
val at := this.value_of(child, this.child_of_id);
|
||||
return nothing{} if at == null;
|
||||
return through(at as *child_of).of;
|
||||
}
|
||||
|
||||
#! The children of an entity, in order, none where it has none. They last until
|
||||
#! it's next given or loses one.
|
||||
pub def world::children_of(&this, parent: entity): span<entity> {
|
||||
val at := this.value_of(parent, this.children_id);
|
||||
return span::<entity>::blank() if at == null;
|
||||
return through(at as *children).list.span;
|
||||
}
|
||||
|
||||
# Makes an entity a child of another at once.
|
||||
def world::set_parent_now(&mut this, child: entity, parent: entity): void {
|
||||
return if !this.alive(child) || !this.alive(parent);
|
||||
var above := parent;
|
||||
while above != entity::none {
|
||||
if above == child {
|
||||
fault($"`set_parent` would make {child.show()} a child of itself.");
|
||||
}
|
||||
above = this.parent_of(above).unwrap_or(entity::none);
|
||||
}
|
||||
if this.parent_of(child) is some(had) && had == parent {
|
||||
return;
|
||||
}
|
||||
this.deferring++;
|
||||
this.leave_parent(child);
|
||||
var link := child_of{ of = parent };
|
||||
this.set_bytes(child, info_of::<child_of>(), &mut link as *mut u8);
|
||||
val list := this.value_of(parent, this.children_id);
|
||||
if list != null {
|
||||
through(list as *mut children).list.append(child);
|
||||
} else {
|
||||
var made := children{ list = vector::<entity>::new() };
|
||||
made.list.append(child);
|
||||
this.set_bytes(parent, info_of::<children>(), &mut made as *mut u8);
|
||||
emptied(&mut made);
|
||||
}
|
||||
this.deferring--;
|
||||
this.settle();
|
||||
}
|
||||
|
||||
# Takes an entity from its parent's `children`, where it has a parent, leaving
|
||||
# its `child_of` for the caller.
|
||||
def world::leave_parent(&mut this, child: entity): void {
|
||||
val above := this.parent_of(child) else { return; };
|
||||
val list := this.value_of(above, this.children_id);
|
||||
if list != null {
|
||||
through(list as *mut children).list.remove(&child);
|
||||
}
|
||||
}
|
||||
|
||||
# Each entity within one, its children before theirs, appended.
|
||||
def world::within(&this, e: entity, into: &mut vector<entity>): void {
|
||||
var at := into.length;
|
||||
val kids := this.children_of(e);
|
||||
for i in 0..kids.length {
|
||||
into.append(kids[i]);
|
||||
}
|
||||
while at < into.length {
|
||||
val each := into[at];
|
||||
at++;
|
||||
val more := this.children_of(each);
|
||||
for i in 0..more.length {
|
||||
into.append(more[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
#! Contains `schedule`: systems, the functions a program runs over its world,
|
||||
#! in order, timing each.
|
||||
|
||||
import std::time;
|
||||
module malunal::ecs;
|
||||
|
||||
# A system of a schedule, and how long it took.
|
||||
struct step : owning {
|
||||
var name: string;
|
||||
var run: function<def(&mut world): void>;
|
||||
var last: i64; # Nanoseconds.
|
||||
var total: i64;
|
||||
var runs: u64;
|
||||
}
|
||||
|
||||
pub def step::close(&mut this): void {
|
||||
this.name.close();
|
||||
this.run.close();
|
||||
}
|
||||
|
||||
#! Systems, each a function over a world, which `run` calls in the order they
|
||||
#! were added, timing each, so a program sees what each costs.
|
||||
pub struct schedule : owning {
|
||||
var steps: vector<step>;
|
||||
}
|
||||
|
||||
pub def schedule::new(): schedule {
|
||||
return schedule{ steps = vector::<step>::new() };
|
||||
}
|
||||
|
||||
#! How many systems it runs.
|
||||
pub val schedule::length: u64 {
|
||||
get => this.steps.length;
|
||||
}
|
||||
|
||||
#! Adds a system, run after those added before it: a function of the world,
|
||||
#! or a type of one's own with an `invoke` taking the world, which then holds
|
||||
#! what the system keeps between runs, as its queries.
|
||||
pub def schedule::add<F>(&mut this, name: strview, system: F): void where F: invokable<def(&mut world): void> {
|
||||
this.steps.append(step{
|
||||
name = string::from(name, nothing{}),
|
||||
run = function::<def(&mut world): void>::new(move(system)),
|
||||
});
|
||||
}
|
||||
|
||||
#! Takes out the systems of a name, as a program stops what it added.
|
||||
#! @returns Whether it ran any.
|
||||
pub def schedule::remove(&mut this, name: strview): bool {
|
||||
var found := false;
|
||||
var i := 0u;
|
||||
while i < this.steps.length {
|
||||
if this.steps[i].name.span == name {
|
||||
this.steps.remove_at(i);
|
||||
found = true;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
#! Runs every system over a world, in order.
|
||||
pub def schedule::run(&mut this, w: &mut world): void {
|
||||
for i in 0..this.steps.length {
|
||||
val each := &mut this.steps[i];
|
||||
val started := instant::now();
|
||||
each.run(w);
|
||||
each.last = started.elapsed().in_nanoseconds;
|
||||
each.total += each.last;
|
||||
each.runs++;
|
||||
}
|
||||
}
|
||||
|
||||
#! How long each system took as it last ran, and on average, in
|
||||
#! milliseconds, a line for each, as `movement: 0.412 ms, 0.398 on average`.
|
||||
pub def schedule::timings(&this): string {
|
||||
var text := string::from("", nothing{});
|
||||
for i in 0..this.steps.length {
|
||||
val each := &this.steps[i];
|
||||
val average := each.runs == 0 ? 0.0 : each.total as f64 / each.runs as f64;
|
||||
text.append($"{each.name}: {milliseconds(each.last as f64)} ms, {milliseconds(average)} on average\n");
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
# Nanoseconds as milliseconds, to three places.
|
||||
def milliseconds(ns: f64): f64 {
|
||||
return (ns / 1000 + 0.5) as i64 as f64 / 1000;
|
||||
}
|
||||
|
||||
pub def schedule::close(&mut this): void {
|
||||
this.steps.close();
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
#! Contains how `std::serial` writes and reads an `entity`: as a number, its
|
||||
#! bits, which name it only in its own world while the program runs; or, while
|
||||
#! a program writes or reads a world as data of its own, as a scene file does,
|
||||
#! by an `entity_numbering`, as the number the program gave it there, so a
|
||||
#! component naming an entity names the one it was read as.
|
||||
|
||||
import std::serial;
|
||||
module malunal::ecs;
|
||||
|
||||
#! The numbers a program writes entities as, where it writes a world's entities
|
||||
#! as data of its own, as a scene file writes each by an id, and the entities
|
||||
#! the numbers it reads stand for. While a numbering is applied, `std::serial`
|
||||
#! writes and reads every entity by it.
|
||||
#!
|
||||
#! Each entity is given one number, and each number names one entity; giving
|
||||
#! either another replaces what it had.
|
||||
pub struct entity_numbering : owning {
|
||||
var by_entity: idmap; # Each entity's place in `entries`, by its bits.
|
||||
var by_number: idmap; # Each number's place in `entries`, by the number.
|
||||
var entries: vector<numbered>;
|
||||
}
|
||||
|
||||
# An entity, and the number it's given.
|
||||
struct numbered {
|
||||
var bits: u64;
|
||||
var number: u64;
|
||||
}
|
||||
|
||||
#! A numbering of no entities.
|
||||
pub def entity_numbering::new(): entity_numbering {
|
||||
return entity_numbering{ by_entity = idmap::new(), by_number = idmap::new(), entries = vector::<numbered>::new() };
|
||||
}
|
||||
|
||||
pub def entity_numbering::close(&mut this): void {
|
||||
this.by_entity.close();
|
||||
this.by_number.close();
|
||||
this.entries.close();
|
||||
}
|
||||
|
||||
#! Gives an entity a number, which names it from now on.
|
||||
pub def entity_numbering::set(&mut this, e: entity, number: u64): void {
|
||||
val at := this.entries.length as u32;
|
||||
this.entries.append(numbered{ bits = e.bits, number = number });
|
||||
this.by_entity.set(e.bits, at);
|
||||
this.by_number.set(number, at);
|
||||
}
|
||||
|
||||
#! The number an entity was given, where it was given one.
|
||||
pub def entity_numbering::number_of(&this, e: entity): maybe<u64> {
|
||||
val at := this.by_entity.get(e.bits);
|
||||
return nothing{} if at == absent;
|
||||
return this.entries[at as u64].number;
|
||||
}
|
||||
|
||||
#! The entity a number names, where it names one.
|
||||
pub def entity_numbering::entity_of(&this, number: u64): maybe<entity> {
|
||||
val at := this.by_number.get(number);
|
||||
return nothing{} if at == absent;
|
||||
return entity{ bits = this.entries[at as u64].bits };
|
||||
}
|
||||
|
||||
# The numbering `std::serial` writes and reads entities by, or `null` where
|
||||
# none is applied.
|
||||
var applied_numbering: *entity_numbering = null;
|
||||
|
||||
#! Writes and reads every entity by the numbering, until what this gives closes,
|
||||
#! as its scope ends, when the numbering applied before it is again. A numbering
|
||||
#! is applied on one thread, and the program writes and reads entities on that
|
||||
#! thread while it is.
|
||||
#! @param this The numbering, which stays where it is while it's applied.
|
||||
#! @returns What applies it while it's held.
|
||||
pub def entity_numbering::apply(&this): numbering_applied {
|
||||
val made := numbering_applied{ before = applied_numbering, held = true };
|
||||
applied_numbering = this as *entity_numbering;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A numbering applied, until it closes.
|
||||
pub struct numbering_applied : owning {
|
||||
var before: *entity_numbering; # The numbering applied before, applied again as this closes.
|
||||
var held: bool; # Whether it applies one, which a value moved from doesn't.
|
||||
}
|
||||
|
||||
pub def numbering_applied::close(&mut this): void {
|
||||
return if !this.held;
|
||||
applied_numbering = this.before;
|
||||
this.held = false;
|
||||
}
|
||||
|
||||
#! Writes an entity as its number in the numbering applied, or as nothing where
|
||||
#! it has none there, as one the data leaves out; and as its bits where no
|
||||
#! numbering is applied. `entity::none` is nothing either way.
|
||||
pub def entity::encode(&this, out: &mut serial::encoder): void {
|
||||
if this.bits == 0 {
|
||||
out.empty();
|
||||
return;
|
||||
}
|
||||
if applied_numbering == null {
|
||||
out.unsigned(this.bits);
|
||||
return;
|
||||
}
|
||||
if through(applied_numbering).number_of(entity{ bits = this.bits }) is some(number) {
|
||||
out.unsigned(number);
|
||||
} else {
|
||||
out.empty();
|
||||
}
|
||||
}
|
||||
|
||||
#! Reads an entity `encode` wrote: nothing as `entity::none`, and a number as
|
||||
#! the entity it names in the numbering applied, which must name one, or as its
|
||||
#! bits where none is applied.
|
||||
pub def entity::decode(from: &serial::decoder, at: u32, given: serial::options): result<entity, serial::error> {
|
||||
return entity::none if from.kind_of(at) == serial::kind::empty;
|
||||
val number := from.as_u64(at) else (e) { return e; };
|
||||
return entity{ bits = number } if applied_numbering == null;
|
||||
val found := through(applied_numbering).entity_of(number) else {
|
||||
return serial::error::at(serial::error_kind::out_of_range, from.place(at));
|
||||
};
|
||||
return found;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#! Contains sharing a world between threads: several passing over it at once,
|
||||
#! each over what no other writes, as an engine runs systems reaching
|
||||
#! different components on threads of its own.
|
||||
|
||||
module malunal::ecs;
|
||||
|
||||
#! Lets several threads pass over the world at once, until `end_sharing`, as an
|
||||
#! engine runs systems reaching different components on threads of its own.
|
||||
#! Each thread passes over it by `each`, queries, and chunks, gets and replaces
|
||||
#! the components entities have, and reads its resources. What would move an
|
||||
#! entity, a component given that it lacks or taken, a spawn, or a despawn, is
|
||||
#! deferred, as within a pass, and made as the sharing ends, in the order the
|
||||
#! threads deferred them. An entity spawned is alive once the sharing ends, and
|
||||
#! given components, despawned, or given a parent till then as one alive.
|
||||
#!
|
||||
#! Threads may read a component at once, but one writing it must be the only
|
||||
#! thread reaching it, which the world leaves to its caller, as an engine knows
|
||||
#! what each system reads and writes. While shared, the world can't meet types
|
||||
#! it hasn't, be given resources or observers or have them taken, or `apply`
|
||||
#! commands; `par_each` calls its function on its own thread, as the threads
|
||||
#! sharing the world are its threads.
|
||||
#! @remarks Only the thread that began sharing ends it, once the others are
|
||||
#! done with the world.
|
||||
pub def world::begin_sharing(&mut this): void {
|
||||
if this.sharing {
|
||||
fault("`begin_sharing` was called on a world threads share already.");
|
||||
}
|
||||
if this.parallel || this.deferring > 0 {
|
||||
fault("`begin_sharing` can't run while a pass goes over the world: run it after.");
|
||||
}
|
||||
this.sharing = true;
|
||||
this.deferring++;
|
||||
}
|
||||
|
||||
#! Ends the sharing `begin_sharing` began, once every other thread is done with
|
||||
#! the world, and makes what the threads deferred.
|
||||
pub def world::end_sharing(&mut this): void {
|
||||
if !this.sharing {
|
||||
fault("`end_sharing` was called on a world no threads share.");
|
||||
}
|
||||
this.sharing = false;
|
||||
this.deferring--;
|
||||
this.materialize();
|
||||
this.track_asked();
|
||||
if this.pending.length > 0 {
|
||||
this.flush();
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether threads share the world, between `begin_sharing` and `end_sharing`.
|
||||
pub val world::shared: bool {
|
||||
get => this.sharing;
|
||||
}
|
||||
|
||||
# Stops the program where threads share the world, which can't do what's named.
|
||||
def world::refuse_while_shared(&this, what: strview): void {
|
||||
if this.sharing {
|
||||
fault($"A world threads share can't {what}: do it before `begin_sharing`, or after `end_sharing`.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
#! Contains `table`: the entities having one set of components, an archetype,
|
||||
#! each component a column of their values in the entities' order.
|
||||
|
||||
module malunal::ecs;
|
||||
|
||||
# A component's column of a table: a value for each of the table's entities.
|
||||
struct column {
|
||||
var data: *mut u8;
|
||||
var size: u64;
|
||||
var id: u32;
|
||||
var info: *component_info;
|
||||
var changed: u64; # The world's tick as it was last written, which `changed` filters read.
|
||||
}
|
||||
|
||||
# What a table's `slot_of` gives for a component it has without a column: a
|
||||
# tag, which holds nothing.
|
||||
const tagged: u32 = 0xFFFFFFFE;
|
||||
|
||||
# The ticks of a component a table keeps of each of its entities, once a
|
||||
# query asks what was added or changed of it: as each was given it, and as
|
||||
# each's was last written.
|
||||
struct ticks {
|
||||
var id: u32;
|
||||
var added: *mut u64;
|
||||
var changed: *mut u64;
|
||||
}
|
||||
|
||||
# The entities having one set of components. A row is an entity, and its
|
||||
# values, one in each column; taking a row out moves the last into its place,
|
||||
# so the rows stay side by side. What spawning, moving, and despawning reach
|
||||
# comes first, so it's read together.
|
||||
struct table : owning {
|
||||
var columns: vector<column>;
|
||||
var entities: *mut entity;
|
||||
var count: u64;
|
||||
var capacity: u64;
|
||||
var ticked: vector<ticks>; # The ticks of each entity, of each component the world tracks.
|
||||
var added: u64; # The world's tick as an entity last came into it.
|
||||
var kin: bool; # Whether its entities are children or parents.
|
||||
var ids: vector<u32>; # Its components, in order.
|
||||
var slots: vector<u32>; # Each one's column, or `tagged`.
|
||||
var hash: u64; # Of `ids`.
|
||||
var next: u32; # The next table of the same hash, or `absent`.
|
||||
var edges: idmap; # The tables an entity goes to as it gains or loses a component.
|
||||
}
|
||||
|
||||
# The column of a component, `tagged` where it's a tag, or `absent` where the
|
||||
# table hasn't the component.
|
||||
def table::slot_of(&this, id: u32): u32 {
|
||||
var low := 0u;
|
||||
var high := this.ids.length;
|
||||
while low < high {
|
||||
val middle := (low + high) / 2;
|
||||
val at := this.ids[middle];
|
||||
if at == id {
|
||||
return this.slots[middle];
|
||||
}
|
||||
if at < id {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
return absent;
|
||||
}
|
||||
|
||||
def table::has(&this, id: u32): bool {
|
||||
return this.slot_of(id) != absent;
|
||||
}
|
||||
|
||||
# Where a row's value of a column is.
|
||||
def table::at(&this, slot: u32, row: u64): *mut u8 {
|
||||
val c := &this.columns[slot as u64];
|
||||
return c.data + row * c.size;
|
||||
}
|
||||
|
||||
# Gives the table room for a number of rows, doubling what it has.
|
||||
def table::reserve(&mut this, wanted: u64): void {
|
||||
return if wanted <= this.capacity;
|
||||
var size := this.capacity == 0 ? 8u : this.capacity * 2;
|
||||
while size < wanted {
|
||||
size *= 2;
|
||||
}
|
||||
for i in 0..this.columns.length {
|
||||
val c := &mut this.columns[i];
|
||||
c.data = resized(c.data, size * c.size);
|
||||
}
|
||||
for i in 0..this.ticked.length {
|
||||
val k := &mut this.ticked[i];
|
||||
k.added = resized(k.added as *mut u8, size * 8) as *mut u64;
|
||||
k.changed = resized(k.changed as *mut u8, size * 8) as *mut u64;
|
||||
}
|
||||
this.entities = resized(this.entities as *mut u8, size * 8) as *mut entity;
|
||||
this.capacity = size;
|
||||
}
|
||||
|
||||
# The ticks it keeps of a component, or `null` where the world doesn't track
|
||||
# it, or the table hasn't it.
|
||||
def table::ticks_of(&this, id: u32): *ticks {
|
||||
for i in 0..this.ticked.length {
|
||||
return address(&this.ticked[i]) if this.ticked[i].id == id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
# Starts keeping the ticks of a component of each entity, each the tick given,
|
||||
# as the world starts tracking it.
|
||||
def table::track(&mut this, id: u32, added: u64, changed: u64): void {
|
||||
var made := ticks{ id = id };
|
||||
if this.capacity > 0 {
|
||||
made.added = raw_allocate(this.capacity * 8) as *mut u64;
|
||||
made.changed = raw_allocate(this.capacity * 8) as *mut u64;
|
||||
}
|
||||
for row in 0..this.count {
|
||||
made.added[row] = added;
|
||||
made.changed[row] = changed;
|
||||
}
|
||||
this.ticked.append(made);
|
||||
}
|
||||
|
||||
# Adds a row for an entity, whose values the caller writes, and gives it.
|
||||
def table::push(&mut this, e: entity): u64 {
|
||||
if this.count == this.capacity {
|
||||
this.reserve(this.count + 1);
|
||||
}
|
||||
this.entities[this.count] = e;
|
||||
this.count++;
|
||||
return this.count - 1;
|
||||
}
|
||||
|
||||
# Takes a row out, whose values were moved or closed already, moving the last
|
||||
# row into its place. Gives the entity moved, or `entity::none` where the row
|
||||
# was the last.
|
||||
def table::take_out(&mut this, row: u64): entity {
|
||||
val last := this.count - 1;
|
||||
this.count = last;
|
||||
return entity::none if row == last;
|
||||
for i in 0..this.columns.length {
|
||||
val c := &this.columns[i];
|
||||
memcpy(c.data + row * c.size, c.data + last * c.size, c.size);
|
||||
}
|
||||
for i in 0..this.ticked.length {
|
||||
val k := &this.ticked[i];
|
||||
k.added[row] = k.added[last];
|
||||
k.changed[row] = k.changed[last];
|
||||
}
|
||||
val moved := this.entities[last];
|
||||
this.entities[row] = moved;
|
||||
return moved;
|
||||
}
|
||||
|
||||
# Closes the values of a row that close what they hold.
|
||||
def table::close_row(&mut this, row: u64): void {
|
||||
for i in 0..this.columns.length {
|
||||
val c := &this.columns[i];
|
||||
if c.info[0].closes {
|
||||
c.info[0].dispose(c.data + row * c.size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub def table::close(&mut this): void {
|
||||
for row in 0..this.count {
|
||||
this.close_row(row);
|
||||
}
|
||||
for i in 0..this.columns.length {
|
||||
raw_release(this.columns[i].data);
|
||||
}
|
||||
for i in 0..this.ticked.length {
|
||||
raw_release(this.ticked[i].added as *mut u8);
|
||||
raw_release(this.ticked[i].changed as *mut u8);
|
||||
}
|
||||
this.ticked.close();
|
||||
raw_release(this.entities as *mut u8);
|
||||
this.entities = null;
|
||||
this.count = 0;
|
||||
this.capacity = 0;
|
||||
this.columns.close();
|
||||
this.ids.close();
|
||||
this.slots.close();
|
||||
this.edges.close();
|
||||
}
|
||||
|
||||
# A block made larger, or made where there was none.
|
||||
def resized(at: *mut u8, size: u64): *mut u8 {
|
||||
return at == null ? raw_allocate(size) : raw_resize(at, size);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
#! Contains what a world knows of when each entity was given a component, and
|
||||
#! when its value was last written: ticks it keeps of the components some
|
||||
#! query asks what was `added` or `changed` of, and of no others, so passes
|
||||
#! over the rest cost nothing more.
|
||||
|
||||
module malunal::ecs;
|
||||
|
||||
# Starts keeping the ticks of a component of each entity, where it doesn't. Of
|
||||
# the entities each table has, each tick is taken as the table's own, which no
|
||||
# entity's is past, so no query misses what was added or changed before. While
|
||||
# threads share the world, it starts once the sharing ends, as tables can't
|
||||
# change while threads pass over them; till then, a pass asks of tables alone.
|
||||
def world::track(&mut this, id: u32): void {
|
||||
return if id == absent || this.tracks(id);
|
||||
if this.sharing {
|
||||
for i in 0..this.to_track.length {
|
||||
return if this.to_track[i] == id;
|
||||
}
|
||||
this.to_track.append(id);
|
||||
return;
|
||||
}
|
||||
while this.tracked.length <= id as u64 {
|
||||
this.tracked.append(false);
|
||||
}
|
||||
this.tracked[id as u64] = true;
|
||||
for i in 0..this.tables.length {
|
||||
val t := &mut this.tables[i];
|
||||
val slot := t.slot_of(id);
|
||||
continue if slot == absent;
|
||||
t.track(id, t.added, slot == tagged ? t.added : t.columns[slot as u64].changed);
|
||||
}
|
||||
}
|
||||
|
||||
# Starts keeping the ticks queries asked for while threads shared the world.
|
||||
def world::track_asked(&mut this): void {
|
||||
for i in 0..this.to_track.length {
|
||||
this.track(this.to_track[i]);
|
||||
}
|
||||
this.to_track.clear();
|
||||
}
|
||||
|
||||
# Whether the world keeps the ticks of a component of each entity.
|
||||
def world::tracks(&this, id: u32): bool {
|
||||
return id < this.tracked.length && this.tracked[id as u64];
|
||||
}
|
||||
|
||||
# Notes an entity's value of a component written, as a tick says: its
|
||||
# column's, which no entity's is past, and its own where the world tracks it.
|
||||
def table::wrote(&mut this, slot: u32, id: u32, row: u64, now: u64): void {
|
||||
this.columns[slot as u64].changed = now;
|
||||
if this.ticked.length > 0 {
|
||||
val k := this.ticks_of(id);
|
||||
if k != null {
|
||||
k[0].changed[row] = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Notes every entity's value of a component written.
|
||||
def table::wrote_all(&mut this, slot: u32, id: u32, now: u64): void {
|
||||
this.columns[slot as u64].changed = now;
|
||||
if this.ticked.length > 0 {
|
||||
val k := this.ticks_of(id);
|
||||
if k != null {
|
||||
for row in 0..this.count {
|
||||
k[0].changed[row] = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Notes a row's entity given every component of the table, as it's spawned.
|
||||
def table::entered(&mut this, row: u64, now: u64): void {
|
||||
this.added = now;
|
||||
for i in 0..this.ticked.length {
|
||||
val k := &mut this.ticked[i];
|
||||
k.added[row] = now;
|
||||
k.changed[row] = now;
|
||||
}
|
||||
}
|
||||
|
||||
# Notes the ticks of a row's entity come from another table: what it had there
|
||||
# it keeps the ticks of, and what it has newly, it was given now.
|
||||
def table::came_from(&mut this, other: &table, row: u64, from: u64, now: u64): void {
|
||||
for i in 0..this.ticked.length {
|
||||
val k := &mut this.ticked[i];
|
||||
val known := other.ticks_of(k.id);
|
||||
if known != null {
|
||||
k.added[row] = known[0].added[from];
|
||||
k.changed[row] = known[0].changed[from];
|
||||
} else {
|
||||
k.added[row] = now;
|
||||
k.changed[row] = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# A tick a pass reads or writes of each row of a table.
|
||||
struct tick_at {
|
||||
var at: *mut u64;
|
||||
}
|
||||
|
||||
# What a pass asks of each entity of a table it matched, as its query asks what
|
||||
# was added or changed of each: the ticks that must be past its last pass, and
|
||||
# those of what it writes, which it stamps.
|
||||
struct sieve {
|
||||
var asks: tick_at[12];
|
||||
var asked: u64;
|
||||
var stamps: tick_at[8];
|
||||
var stamped: u64;
|
||||
}
|
||||
|
||||
# What a query asks of each entity of a table it matched. A component the
|
||||
# world doesn't track yet, as threads share it, is asked of by its table alone.
|
||||
def world::sieve_of(&this, at: *mut query_state, m: u64): sieve {
|
||||
val st := &through(at);
|
||||
val t := &this.tables[st.matched[m] as u64];
|
||||
var made: sieve;
|
||||
return made if t.ticked.length == 0;
|
||||
for i in 0..st.terms.length {
|
||||
val term := &st.terms[i];
|
||||
continue if term.id == absent;
|
||||
val kind := term.kind;
|
||||
if kind == term_kind::changed || kind == term_kind::added {
|
||||
val k := t.ticks_of(term.id);
|
||||
if k != null {
|
||||
made.asks[made.asked] = tick_at{ at = kind == term_kind::added ? k[0].added : k[0].changed };
|
||||
made.asked++;
|
||||
}
|
||||
} else if kind == term_kind::writes || kind == term_kind::maybe_writes {
|
||||
val k := t.ticks_of(term.id);
|
||||
if k != null {
|
||||
made.stamps[made.stamped] = tick_at{ at = k[0].changed };
|
||||
made.stamped++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Whether a row passes: each tick asked of is past the query's last pass, or
|
||||
# the query never passed.
|
||||
def sieve::passes(&this, row: u64, since: u64): bool {
|
||||
return true if since == 0;
|
||||
for i in 0..this.asked {
|
||||
return false if this.asks[i].at[row] <= since;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Stamps a row's values a pass writes.
|
||||
def sieve::stamp(&this, row: u64, now: u64): void {
|
||||
for i in 0..this.stamped {
|
||||
this.stamps[i].at[row] = now;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
#! Contains `workers`: the threads `par_each` calls functions on, started as
|
||||
#! it's first called and kept, waiting, until the world closes.
|
||||
|
||||
import system;
|
||||
import std::thread;
|
||||
module malunal::ecs;
|
||||
|
||||
# A run of a table's rows a thread calls a function for.
|
||||
struct piece {
|
||||
var which: u64; # The table, among those its query matched.
|
||||
var begin: u64;
|
||||
var end: u64;
|
||||
}
|
||||
|
||||
# What the threads are given to do: a function for each piece.
|
||||
struct job {
|
||||
var run: def(*mut u8, &piece): void;
|
||||
var context: *mut u8;
|
||||
var pieces: *piece;
|
||||
var count: u64;
|
||||
}
|
||||
|
||||
# What the threads share, on the heap, so it stays where it is.
|
||||
struct crew {
|
||||
var job: *job;
|
||||
var next: atomic<u64>; # The next piece to take.
|
||||
var busy: atomic<u32>; # The workers yet to finish the job.
|
||||
var round: atomic<u32>; # Counts jobs, and the workers wait on it.
|
||||
var done: atomic<u32>; # 1 once the workers finished the job, which the world waits on.
|
||||
var stopping: atomic<u32>;
|
||||
}
|
||||
|
||||
# The threads a world calls functions on, besides its own.
|
||||
struct workers : owning {
|
||||
var shared: *mut crew;
|
||||
var threads: vector<thread::handle<void>>;
|
||||
var wanted: u32; # How many threads in all, the world's own among them, or 0 for one for each processor.
|
||||
}
|
||||
|
||||
def workers::new(): workers {
|
||||
return workers{ threads = vector::<thread::handle<void>>::new() };
|
||||
}
|
||||
|
||||
# Starts the threads, where they aren't.
|
||||
def workers::start(&mut this): void {
|
||||
return if this.shared != null;
|
||||
this.shared = raw_allocate_zeroed(size_of::<crew>()) as *mut crew;
|
||||
val all := this.wanted == 0 ? thread::cpu_count() : this.wanted;
|
||||
for _ in 1..all {
|
||||
var started := thread::spawn_with(work, this.shared) else (_) { break; };
|
||||
this.threads.append(move(started));
|
||||
}
|
||||
}
|
||||
|
||||
# Calls a job's function for each of its pieces, on every thread, this one
|
||||
# among them, and returns once they're done.
|
||||
def workers::run(&mut this, given: &job): void {
|
||||
this.start();
|
||||
val s := &mut through(this.shared);
|
||||
s.job = address(given);
|
||||
s.next.store(0, order::relaxed);
|
||||
if this.threads.length > 0 {
|
||||
s.done.store(0, order::relaxed);
|
||||
s.busy.store(this.threads.length as u32, order::relaxed);
|
||||
_ = s.round.fetch_add(1, order::release);
|
||||
_ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF);
|
||||
}
|
||||
drain(s);
|
||||
if this.threads.length > 0 {
|
||||
while s.done.load(order::acquire) == 0 {
|
||||
_ = system::futex_wait(word_of(&mut s.done), 0, -1);
|
||||
}
|
||||
}
|
||||
s.job = null;
|
||||
}
|
||||
|
||||
pub def workers::close(&mut this): void {
|
||||
if this.shared != null {
|
||||
val s := &mut through(this.shared);
|
||||
s.stopping.store(1, order::release);
|
||||
_ = s.round.fetch_add(1, order::release);
|
||||
_ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF);
|
||||
this.threads.close();
|
||||
raw_release(this.shared as *mut u8);
|
||||
this.shared = null;
|
||||
}
|
||||
this.threads.close();
|
||||
}
|
||||
|
||||
# What each worker does: waits for a job, takes its pieces until none are
|
||||
# left, and says it's done.
|
||||
def work(shared: *mut crew): void {
|
||||
val s := &mut through(shared);
|
||||
var seen: u32 = 0;
|
||||
while true {
|
||||
var round := s.round.load(order::acquire);
|
||||
while round == seen {
|
||||
_ = system::futex_wait(word_of(&mut s.round), seen, -1);
|
||||
round = s.round.load(order::acquire);
|
||||
}
|
||||
seen = round;
|
||||
return if s.stopping.load(order::acquire) != 0;
|
||||
drain(s);
|
||||
if s.busy.fetch_sub(1, order::acq_rel) == 1 {
|
||||
s.done.store(1, order::release);
|
||||
_ = system::futex_wake(word_of(&mut s.done), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Takes pieces of the job, calling its function for each, until none are left.
|
||||
def drain(s: &mut crew): void {
|
||||
val given := &through(s.job);
|
||||
while true {
|
||||
val i := s.next.fetch_add(1, order::relaxed);
|
||||
return if i >= given.count;
|
||||
given.run(given.context, &given.pieces[i]);
|
||||
}
|
||||
}
|
||||
|
||||
# The word of an atomic, which the system's futexes wait on.
|
||||
def word_of(of: &mut atomic<u32>): *mut u32 {
|
||||
return (address(of) as *mut atomic<u32>) as *mut u32;
|
||||
}
|
||||
|
||||
#! Says how many threads `par_each` calls functions on, the world's own among
|
||||
#! them: by default, one for each processor. Those it started already end.
|
||||
pub def world::threads(&mut this, count: u32): void {
|
||||
this.crew.close();
|
||||
this.crew.wanted = count == 0 ? 1 : count;
|
||||
}
|
||||
|
||||
# Fewer rows than this a pass calls its function for on its own thread, as
|
||||
# waking the workers would cost more than they'd save.
|
||||
const alone: u64 = 4096;
|
||||
|
||||
# Cuts the rows of the tables a pass matched into pieces, and has the workers
|
||||
# call a function for each. Where threads share the world, this one calls it
|
||||
# for each alone, as those threads are the workers.
|
||||
def world::run_pieces(&mut this, q: *mut query_state, p: pass, context: *mut u8, run: def(*mut u8, &piece): void): void {
|
||||
var pieces := vector::<piece>::new();
|
||||
var total := 0u;
|
||||
for m in 0..q[0].matched.length {
|
||||
val rows := this.rows_of(q, m, p.since, p.now);
|
||||
if rows > 0 {
|
||||
pieces.append(piece{ which = m, begin = 0, end = rows });
|
||||
total += rows;
|
||||
}
|
||||
}
|
||||
if this.sharing {
|
||||
for i in 0..pieces.length {
|
||||
run(context, &pieces[i]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
# What the function may do is the same however many threads it's called on.
|
||||
this.parallel = true;
|
||||
val all := this.crew.wanted == 0 ? thread::cpu_count() as u64 : this.crew.wanted as u64;
|
||||
if total < alone || all <= 1 {
|
||||
for i in 0..pieces.length {
|
||||
run(context, &pieces[i]);
|
||||
}
|
||||
this.parallel = false;
|
||||
return;
|
||||
}
|
||||
|
||||
# Pieces small enough that every thread gets several, so those finishing
|
||||
# first take more.
|
||||
var grain := total / (all * 8);
|
||||
grain = grain < 1024 ? 1024u : grain;
|
||||
var cut := vector::<piece>::new();
|
||||
for i in 0..pieces.length {
|
||||
val whole: piece = pieces[i];
|
||||
var at := whole.begin;
|
||||
while at < whole.end {
|
||||
val end := at + grain < whole.end ? at + grain : whole.end;
|
||||
cut.append(piece{ which = whole.which, begin = at, end = end });
|
||||
at = end;
|
||||
}
|
||||
}
|
||||
val given := job{ run = run, context = context, pieces = cut.span.data, count = cut.length };
|
||||
this.crew.run(&given);
|
||||
this.parallel = false;
|
||||
}
|
||||
@@ -0,0 +1,969 @@
|
||||
#! Contains `world`: entities, the components each has, and the resources the
|
||||
#! world holds apart from any entity.
|
||||
|
||||
import system;
|
||||
module malunal::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, spawns, or finds a query, as `parallel` or `sharing` is.
|
||||
var beyond: u64; # Entities spawned past the end of `records` while threads shared it, whose records it makes after.
|
||||
var tracked: vector<bool>; # Whether it keeps the ticks of each entity's component, by the component's id.
|
||||
var to_track: vector<u32>; # Components queries asked of while threads shared it, tracked once they're done.
|
||||
var watches: vector<watch>; # Its observers.
|
||||
var watched: vector<u8>; # The changes observers watch each component for, by its id.
|
||||
var child_of_id: u32;
|
||||
var children_id: u32;
|
||||
}
|
||||
|
||||
#! 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(),
|
||||
tracked = vector::<bool>::new(),
|
||||
to_track = vector::<u32>::new(),
|
||||
watches = vector::<watch>::new(),
|
||||
watched = vector::<u8>::new(),
|
||||
};
|
||||
val none := span::<u32>::blank();
|
||||
_ = made.make_table(none, hash_ids(none));
|
||||
made.child_of_id = made.id_of(info_of::<child_of>());
|
||||
made.children_id = made.id_of(info_of::<children>());
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Closes every component and resource it holds: its resources last given
|
||||
#! first, so one made of another, as a renderer of a window, closes before it.
|
||||
pub def world::close(&mut this): void {
|
||||
this.crew.close();
|
||||
this.pending.close();
|
||||
var i := this.resources.length;
|
||||
while i > 0 {
|
||||
i--;
|
||||
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();
|
||||
this.tracked.close();
|
||||
this.to_track.close();
|
||||
this.watches.close();
|
||||
this.watched.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;
|
||||
}
|
||||
}
|
||||
t.entered(row, now);
|
||||
if this.watches.length > 0 {
|
||||
this.notify_all(e, to, change::added);
|
||||
this.settle();
|
||||
}
|
||||
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, and each entity within it: its
|
||||
#! children, theirs, and so on. It's taken from its parent's `children`.
|
||||
#! @returns Whether it was alive.
|
||||
pub def world::despawn(&mut this, e: entity): bool {
|
||||
return false if !this.alive(e) && !this.awaited(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 || this.sharing {
|
||||
return this.reserve();
|
||||
}
|
||||
this.materialize();
|
||||
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);
|
||||
}
|
||||
|
||||
# An entity's index and generation, in no table yet, reserved under the guard,
|
||||
# as threads may spawn at once: an index freed, or one past the end of the
|
||||
# records, which threads read as they spawn, so it's made once they're done.
|
||||
def world::reserve(&mut this): entity {
|
||||
this.lock();
|
||||
this.living++;
|
||||
var made := entity::none;
|
||||
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;
|
||||
made = entity::of(index, r.generation);
|
||||
} else {
|
||||
made = entity::of((this.records.length + this.beyond) as u32, 1);
|
||||
this.beyond++;
|
||||
}
|
||||
this.unlock();
|
||||
return made;
|
||||
}
|
||||
|
||||
# Makes the records of the entities spawned past their end while threads
|
||||
# shared the world, as they're done, each spawned as the world deferred.
|
||||
def world::materialize(&mut this): void {
|
||||
for _ in 0..this.beyond {
|
||||
this.records.append(record{ table = pending, row = 0, generation = 1 });
|
||||
}
|
||||
this.beyond = 0;
|
||||
}
|
||||
|
||||
# Whether an entity was spawned while threads share the world, past the end of
|
||||
# its records, which it makes once they're done.
|
||||
def world::awaited(&this, e: entity): bool {
|
||||
val index := e.index as u64;
|
||||
return index >= this.records.length && index < this.records.length + this.beyond && e.generation == 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;
|
||||
}
|
||||
|
||||
# Despawns an entity and those within it, the deepest first, so each one's
|
||||
# parent is there as its observers run.
|
||||
def world::despawn_now(&mut this, e: entity): void {
|
||||
val r: record = this.records[e.index as u64];
|
||||
if this.watches.length == 0 && (r.table == pending || !this.related(r.table)) {
|
||||
# No observer, and no parent or child: it's taken out alone.
|
||||
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;
|
||||
}
|
||||
}
|
||||
this.free_record(e);
|
||||
return;
|
||||
}
|
||||
this.deferring++;
|
||||
if this.has_id(e, this.children_id) {
|
||||
var inner := vector::<entity>::new();
|
||||
this.within(e, &mut inner);
|
||||
var i := inner.length;
|
||||
while i > 0 {
|
||||
i--;
|
||||
if this.alive(inner[i]) {
|
||||
this.despawn_alone(inner[i], false);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.despawn_alone(e, true);
|
||||
this.deferring--;
|
||||
this.settle();
|
||||
}
|
||||
|
||||
# Despawns an entity alone: runs the observers of what it loses, takes it from
|
||||
# its parent where asked, and closes its components.
|
||||
def world::despawn_alone(&mut this, e: entity, leave: bool): void {
|
||||
val r: record = this.records[e.index as u64];
|
||||
if r.table != pending {
|
||||
this.notify_all(e, r.table, change::removed);
|
||||
if leave && this.related(r.table) {
|
||||
this.leave_parent(e);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
this.free_record(e);
|
||||
}
|
||||
|
||||
# Frees an entity's index, for the next entity spawned to use, of the next
|
||||
# generation.
|
||||
def world::free_record(&mut this, e: entity): void {
|
||||
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 {
|
||||
val info := info_of::<T>();
|
||||
if !this.alive(e) {
|
||||
if this.awaited(e) {
|
||||
this.defer_put(e, info, &mut value as *mut u8);
|
||||
emptied(&mut value);
|
||||
return;
|
||||
}
|
||||
fault($"`set` was given {e.show()}, which isn't alive.");
|
||||
}
|
||||
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.wrote(slot, id, r.row as u64, 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 given := this.id_of(info);
|
||||
val at := this.add_now(e, given);
|
||||
if at != null {
|
||||
place(at, &mut value);
|
||||
}
|
||||
this.notify(e, given, change::added);
|
||||
this.settle();
|
||||
}
|
||||
|
||||
#! 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.wrote(slot, id, r.row as u64, this.stamp());
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
this.place(e);
|
||||
}
|
||||
val at := this.add_now(e, id);
|
||||
if at != null {
|
||||
memcpy(at, from, info[0].size);
|
||||
}
|
||||
this.notify(e, id, change::added);
|
||||
this.settle();
|
||||
}
|
||||
|
||||
# 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 now := this.stamp();
|
||||
val row := this.move_row(e, r.table, r.row as u64, to, now);
|
||||
val t := &mut this.tables[to as u64];
|
||||
t.added = now;
|
||||
val slot := t.slot_of(id);
|
||||
return null if slot == tagged;
|
||||
t.columns[slot as u64].changed = now;
|
||||
return t.at(slot, row);
|
||||
}
|
||||
|
||||
# Takes a component a living entity has, closing it, once its observers ran.
|
||||
# Taken from a child, its parent's `children` no longer lists it; taken from a
|
||||
# parent, its children are of the world itself.
|
||||
def world::remove_now(&mut this, e: entity, id: u32): void {
|
||||
if id > this.children_id && !this.watches_for(id, change::removed) {
|
||||
this.take_now(e, id);
|
||||
return;
|
||||
}
|
||||
this.deferring++;
|
||||
this.notify(e, id, change::removed);
|
||||
var orphans := vector::<entity>::new();
|
||||
if id == this.child_of_id {
|
||||
this.leave_parent(e);
|
||||
} else if id == this.children_id {
|
||||
val kids := this.children_of(e);
|
||||
for i in 0..kids.length {
|
||||
orphans.append(kids[i]);
|
||||
}
|
||||
}
|
||||
this.take_now(e, id);
|
||||
for i in 0..orphans.length {
|
||||
if this.parent_of(orphans[i]) is some(above) && above == e {
|
||||
this.remove_now(orphans[i], this.child_of_id);
|
||||
}
|
||||
}
|
||||
this.deferring--;
|
||||
this.settle();
|
||||
}
|
||||
|
||||
# Takes a component an entity has, closing it, and moves it to the table
|
||||
# without it.
|
||||
def world::take_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);
|
||||
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, 0);
|
||||
}
|
||||
|
||||
# Whether a table's entities are children or parents.
|
||||
def world::related(&this, table: u32): bool {
|
||||
return this.tables[table as u64].kin;
|
||||
}
|
||||
|
||||
# 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, given at the tick given. What the two
|
||||
# share the second's ticks are as new as the first's of.
|
||||
def world::move_row(&mut this, e: entity, from: u32, row: u64, to: u32, now: u64): 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 {
|
||||
val into := &mut target.columns[slot as u64];
|
||||
memcpy(into.data + made * into.size, c.data + row * c.size, c.size);
|
||||
if c.changed > into.changed {
|
||||
into.changed = c.changed;
|
||||
}
|
||||
}
|
||||
}
|
||||
if source.added > target.added {
|
||||
target.added = source.added;
|
||||
}
|
||||
if target.ticked.length > 0 {
|
||||
target.came_from(source, made, row, now);
|
||||
}
|
||||
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.span == 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 });
|
||||
}
|
||||
if this.tracks(ids[i]) {
|
||||
made.track(ids[i], 0, 0);
|
||||
}
|
||||
}
|
||||
# `child_of` and `children` are the first two components every world meets,
|
||||
# so the first of a table's, where it has either.
|
||||
made.kin = ids.length > 0 && (ids[0] == this.child_of_id || ids[0] == this.children_id);
|
||||
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.span);
|
||||
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.span);
|
||||
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.");
|
||||
}
|
||||
this.materialize();
|
||||
var i := 0u;
|
||||
while i < changes.list.length {
|
||||
val c: command = changes.list[i];
|
||||
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 {
|
||||
# What it's given next, it's put in the table of at once.
|
||||
var end := i;
|
||||
while end < changes.list.length && changes.list[end].what == op::set && changes.list[end].who == c.who {
|
||||
end++;
|
||||
}
|
||||
if end > i && this.place_with(changes, i, end) {
|
||||
i = end;
|
||||
} else {
|
||||
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);
|
||||
}
|
||||
}
|
||||
op::parent => {
|
||||
this.set_parent_now(c.who, entity{ bits = c.at });
|
||||
}
|
||||
op::unparent => {
|
||||
if this.has_id(c.who, this.child_of_id) {
|
||||
this.remove_now(c.who, this.child_of_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
changes.forget();
|
||||
}
|
||||
|
||||
# Puts an entity spawned as the world deferred, or by commands, into the table
|
||||
# of the components the commands give it next, at once, as `spawn_with` does,
|
||||
# rather than moving it through a table for each. Gives false, doing nothing,
|
||||
# where two are of one type, or there are more than 32.
|
||||
def world::place_with(&mut this, changes: &mut commands, from: u64, to: u64): bool {
|
||||
val count := to - from;
|
||||
return false if count > 32;
|
||||
var bundle := 0u;
|
||||
for k in from..to {
|
||||
bundle += mixed(changes.list[k].info[0].key);
|
||||
}
|
||||
var at := this.bundles.get(bundle);
|
||||
if at == absent || this.tables[at as u64].ids.length != count {
|
||||
var ids: u32[32];
|
||||
for k in 0..count {
|
||||
ids[k] = this.id_of(changes.list[from + k].info);
|
||||
for j in 0..k {
|
||||
return false if ids[j] == ids[k];
|
||||
}
|
||||
}
|
||||
at = this.table_of_unsorted(&mut ids, count);
|
||||
this.bundles.set(bundle, at);
|
||||
}
|
||||
val e := changes.list[from].who;
|
||||
val row := this.tables[at as u64].push(e);
|
||||
val r := &mut this.records[e.index as u64];
|
||||
r.table = at;
|
||||
r.row = row as u32;
|
||||
val now := this.stamp();
|
||||
val t := &mut this.tables[at as u64];
|
||||
for k in from..to {
|
||||
val c: command = changes.list[k];
|
||||
val slot := t.slot_of(this.find_id(c.info));
|
||||
if slot != tagged {
|
||||
memcpy(t.at(slot, row), changes.data + c.at, c.info[0].size);
|
||||
t.columns[slot as u64].changed = now;
|
||||
}
|
||||
}
|
||||
t.entered(row, now);
|
||||
if this.watches.length > 0 {
|
||||
this.notify_all(e, at, change::added);
|
||||
this.settle();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# 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, and what observers deferred as it was made.
|
||||
def world::flush(&mut this): void {
|
||||
while this.pending.length > 0 {
|
||||
var queued := move(this.pending);
|
||||
this.pending = commands::new();
|
||||
this.apply(&mut queued);
|
||||
if this.pending.length == 0 {
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,968 @@
|
||||
#! Contains the tests of `ecs`: entities and their components, the
|
||||
#! tables they move between, closing what components hold, passes and their
|
||||
#! filters, by type and by path, deferring, chunks, what changed, passes on
|
||||
#! several threads, a world shared by threads, resources, commands, schedules,
|
||||
#! components of one name in two modules, components reached by their types'
|
||||
#! keys, entities written by a numbering, what was written and given of each
|
||||
#! entity, observers, parents and children, and entities spawned by threads.
|
||||
|
||||
import std::json;
|
||||
import std::serial;
|
||||
import std::testing;
|
||||
import std::thread;
|
||||
import malunal::ecs;
|
||||
|
||||
struct position {
|
||||
var x: f32;
|
||||
var y: f32;
|
||||
}
|
||||
|
||||
struct velocity {
|
||||
var x: f32;
|
||||
var y: f32;
|
||||
}
|
||||
|
||||
struct health {
|
||||
var points: i64;
|
||||
}
|
||||
|
||||
struct frozen {}
|
||||
|
||||
struct player {}
|
||||
|
||||
# Counts how many `named` were closed holding a name.
|
||||
var names_closed: u64 = 0;
|
||||
|
||||
# A component holding what closes, which counts its closing.
|
||||
struct named : owning {
|
||||
var text: string;
|
||||
}
|
||||
|
||||
def named::close(&mut this): void {
|
||||
if this.text.length > 0 {
|
||||
names_closed++;
|
||||
}
|
||||
this.text.close();
|
||||
}
|
||||
|
||||
def named::of(text: strview): named {
|
||||
return named{ text = string::from(text, nothing{}) };
|
||||
}
|
||||
|
||||
# Whether an entity has a component a test passes.
|
||||
def given<T, F>(w: &mut world, e: entity, test: F): bool where F: invokable<def(&T): bool> {
|
||||
if w.get::<T>(e) is some(&mut value) {
|
||||
return test(value);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
# Whether the world holds a resource a test passes.
|
||||
def held<T, F>(w: &mut world, test: F): bool where F: invokable<def(&T): bool> {
|
||||
if w.resource::<T>() is some(&mut value) {
|
||||
return test(value);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@test def spawns_and_despawns_entities(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val a := w.spawn();
|
||||
val b := w.spawn();
|
||||
t.expects(w.alive(a) && w.alive(b) && a != b && w.count == 2);
|
||||
t.expects(!w.alive(entity::none));
|
||||
t.expects(w.despawn(a));
|
||||
t.expects(!w.alive(a) && !w.despawn(a) && w.count == 1);
|
||||
# The index is used again, by a generation after.
|
||||
val c := w.spawn();
|
||||
t.expects(c.index == a.index && c.generation == a.generation + 1);
|
||||
t.expects(w.alive(c) && !w.alive(a));
|
||||
}
|
||||
|
||||
@test def sets_gets_and_removes_components(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val e := w.spawn();
|
||||
w.set(e, position{ x = 1, y = 2 });
|
||||
t.expects(w.has::<position>(e) && !w.has::<velocity>(e));
|
||||
if w.get::<position>(e) is some(&mut p) {
|
||||
t.expects(p.x == 1 && p.y == 2);
|
||||
p.x = 5;
|
||||
}
|
||||
t.expects(given(&mut w, e, def(p: &position) => p.x == 5));
|
||||
t.expects(w.get::<velocity>(e).is_none);
|
||||
|
||||
w.set(e, position{ x = 7, y = 8 });
|
||||
t.expects(given(&mut w, e, def(p: &position) => p.x == 7 && p.y == 8));
|
||||
|
||||
w.add::<frozen>(e);
|
||||
t.expects(w.has::<frozen>(e) && w.get::<frozen>(e).is_none);
|
||||
t.expects(given(&mut w, e, def(p: &position) => p.x == 7));
|
||||
|
||||
t.expects(w.remove::<position>(e));
|
||||
t.expects(!w.has::<position>(e) && w.has::<frozen>(e) && !w.remove::<position>(e));
|
||||
t.expects(w.describe(e) == "frozen");
|
||||
}
|
||||
|
||||
@test def moves_entities_between_tables(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
var all := vector::<entity>::new();
|
||||
for i in 0..100u {
|
||||
val e := w.spawn();
|
||||
w.set(e, position{ x = i as f32 });
|
||||
if i % 2 == 0 {
|
||||
w.set(e, velocity{ y = i as f32 });
|
||||
}
|
||||
if i % 3 == 0 {
|
||||
w.set(e, health{ points = i as i64 });
|
||||
}
|
||||
all.append(e);
|
||||
}
|
||||
# Despawning some moves others within their tables.
|
||||
for i in 0..100u {
|
||||
if i % 5 == 0 {
|
||||
_ = w.despawn(all[i]);
|
||||
}
|
||||
}
|
||||
for i in 0..100u {
|
||||
val e := all[i];
|
||||
if i % 5 == 0 {
|
||||
t.expects(!w.alive(e));
|
||||
continue;
|
||||
}
|
||||
t.expects(given(&mut w, e, def(p: &position) => p.x == i as f32));
|
||||
t.expects(w.has::<velocity>(e) == (i % 2 == 0));
|
||||
if i % 2 == 0 {
|
||||
t.expects(given(&mut w, e, def(v: &velocity) => v.y == i as f32));
|
||||
}
|
||||
t.expects(w.has::<health>(e) == (i % 3 == 0));
|
||||
if i % 3 == 0 {
|
||||
t.expects(given(&mut w, e, def(h: &health) => h.points == i as i64));
|
||||
}
|
||||
}
|
||||
t.expects(w.count == 80);
|
||||
}
|
||||
|
||||
@test def spawns_with_components(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val e := w.spawn_with(velocity{ x = 3 }, position{ x = 1 }, frozen{});
|
||||
t.expects(given(&mut w, e, def(p: &position) => p.x == 1));
|
||||
t.expects(given(&mut w, e, def(v: &velocity) => v.x == 3));
|
||||
t.expects(w.has::<frozen>(e));
|
||||
val tables := w.archetypes;
|
||||
# The same set in another order is the same table.
|
||||
val f := w.spawn_with(frozen{}, position{ x = 2 }, velocity{});
|
||||
t.expects(w.archetypes == tables);
|
||||
t.expects(given(&mut w, f, def(p: &position) => p.x == 2));
|
||||
}
|
||||
|
||||
@test def closes_what_components_hold(t: &mut tester): void {
|
||||
names_closed = 0;
|
||||
{
|
||||
var w := world::new();
|
||||
val a := w.spawn_with(named::of("a"), position{});
|
||||
val b := w.spawn_with(named::of("b"));
|
||||
val c := w.spawn();
|
||||
w.set(c, named::of("c"));
|
||||
t.expects(given(&mut w, a, def(n: &named) => n.text == "a"));
|
||||
t.expects(names_closed == 0);
|
||||
|
||||
w.set(a, named::of("a2"));
|
||||
t.expects(names_closed == 1);
|
||||
t.expects(given(&mut w, a, def(n: &named) => n.text == "a2"));
|
||||
|
||||
# Moving to another table moves what it holds, without closing it.
|
||||
w.set(b, position{});
|
||||
t.expects(names_closed == 1 && given(&mut w, b, def(n: &named) => n.text == "b"));
|
||||
|
||||
t.expects(w.remove::<named>(b));
|
||||
t.expects(names_closed == 2);
|
||||
t.expects(w.despawn(a));
|
||||
t.expects(names_closed == 3);
|
||||
w.set_resource(named::of("kept"));
|
||||
}
|
||||
# The world closes what's left: `c`'s, and the resource.
|
||||
t.expects(names_closed == 5);
|
||||
}
|
||||
|
||||
@test def passes_over_entities_with_each(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
for i in 0..10u {
|
||||
val e := w.spawn_with(position{ x = i as f32 }, velocity{ x = 1, y = 2 });
|
||||
if i % 2 == 0 {
|
||||
w.set(e, health{ points = 10 });
|
||||
}
|
||||
}
|
||||
_ = w.spawn_with(position{ x = 100 });
|
||||
|
||||
w.each(def(p: &mut position, v: &velocity) {
|
||||
p.x += v.x;
|
||||
p.y += v.y;
|
||||
});
|
||||
var sum: f32 = 0;
|
||||
var count := 0u;
|
||||
w.each(def(p: &position) {
|
||||
sum += p.x;
|
||||
count++;
|
||||
});
|
||||
t.expects(count == 11 && sum == 45 + 10 + 100);
|
||||
|
||||
# The entity, and what an entity may lack, in any order.
|
||||
var with_health := 0u;
|
||||
var without := 0u;
|
||||
w.each(def(h: maybe<&mut health>, e: entity, v: &velocity) {
|
||||
t.expects(w.alive(e));
|
||||
if h is some(&mut got) {
|
||||
got.points -= 1;
|
||||
with_health++;
|
||||
} else {
|
||||
without++;
|
||||
}
|
||||
});
|
||||
t.expects(with_health == 5 && without == 5);
|
||||
var points: i64 = 0;
|
||||
w.each(def(h: &health) { points += h.points; });
|
||||
t.expects(points == 45);
|
||||
}
|
||||
|
||||
@test def filters_by_with_and_without(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
for i in 0..12u {
|
||||
val e := w.spawn_with(position{ x = i as f32 });
|
||||
if i % 3 == 0 {
|
||||
w.add::<player>(e);
|
||||
}
|
||||
if i % 2 == 0 {
|
||||
w.add::<frozen>(e);
|
||||
}
|
||||
}
|
||||
t.expects(w.query(with::<player>()).count() == 4);
|
||||
t.expects(w.query(without::<frozen>()).count() == 6);
|
||||
t.expects(w.query(with::<player>().without::<frozen>()).count() == 2);
|
||||
|
||||
var seen := vector::<f32>::new();
|
||||
w.query(with::<player>().without::<frozen>()).each(def(p: &position) { seen.append(p.x); });
|
||||
seen.sort();
|
||||
t.expects(seen.length == 2 && seen[0] == 3 && seen[1] == 9);
|
||||
|
||||
# A tag taken as a parameter is asked for too.
|
||||
var tagged := 0u;
|
||||
w.each(def(p: &position, f: &frozen) { tagged++; });
|
||||
t.expects(tagged == 6);
|
||||
}
|
||||
|
||||
@test def filters_by_paths(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
for i in 0..12u {
|
||||
val e := w.spawn_with(position{ x = i as f32 });
|
||||
if i % 3 == 0 {
|
||||
w.add::<player>(e);
|
||||
}
|
||||
if i % 2 == 0 {
|
||||
w.add::<frozen>(e);
|
||||
}
|
||||
}
|
||||
# A type named by its path is the type.
|
||||
t.expects(key_of_path(path_of::<player>()) == component_key::<player>());
|
||||
t.expects(w.query(with_path(path_of::<player>())).count() == 4);
|
||||
t.expects(w.query(with::<player>().without_path(path_of::<frozen>())).count() == 2);
|
||||
|
||||
# No entity has a type the world hasn't met, and every one lacks it, until
|
||||
# it's met.
|
||||
t.expects(w.query(with_path("game::nothing")).count() == 0);
|
||||
t.expects(w.query(without_path("game::nothing")).count() == 12);
|
||||
var healthy := w.query(with_path(path_of::<health>()));
|
||||
t.expects(healthy.count() == 0);
|
||||
_ = w.spawn_with(health{});
|
||||
t.expects(healthy.count() == 1);
|
||||
|
||||
# What changed, by path.
|
||||
var moved := w.query(changed_path(path_of::<position>()));
|
||||
var seen := 0u;
|
||||
moved.each(def(p: &position) { seen++; });
|
||||
t.expects(seen == 12);
|
||||
seen = 0;
|
||||
moved.each(def(p: &position) { seen++; });
|
||||
t.expects(seen == 0);
|
||||
}
|
||||
|
||||
@test def defers_changes_while_passing(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
var all := vector::<entity>::new();
|
||||
for i in 0..20u {
|
||||
all.append(w.spawn_with(health{ points = i as i64 }));
|
||||
}
|
||||
var passed := 0u;
|
||||
w.each(def(e: entity, h: &mut health) {
|
||||
passed++;
|
||||
if h.points % 2 == 0 {
|
||||
t.expects(w.despawn(e));
|
||||
# Despawning is deferred, so the entity is alive until the pass ends.
|
||||
t.expects(w.alive(e));
|
||||
} else {
|
||||
# A component it lacks is given as the pass ends, and one it has at once.
|
||||
w.set(e, velocity{ x = 1 });
|
||||
t.expects(!w.has::<velocity>(e));
|
||||
w.set(e, health{ points = 100 });
|
||||
t.expects(given(&mut w, e, def(got: &health) => got.points == 100));
|
||||
}
|
||||
val spawned := w.spawn();
|
||||
t.expects(w.alive(spawned) && !w.has::<health>(spawned));
|
||||
});
|
||||
t.expects(passed == 20);
|
||||
t.expects(w.count == 10 + 20);
|
||||
t.expects(w.query(with::<velocity>()).count() == 10);
|
||||
for i in 0..20u {
|
||||
t.expects(w.alive(all[i]) == (i % 2 == 1));
|
||||
}
|
||||
}
|
||||
|
||||
@test def walks_chunks(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
for i in 0..50u {
|
||||
val e := w.spawn_with(position{ x = i as f32 }, velocity{ x = 2 });
|
||||
if i >= 30 {
|
||||
w.add::<frozen>(e);
|
||||
}
|
||||
}
|
||||
var chunks := 0u;
|
||||
for c in w.query(with::<position>().with::<velocity>()).chunks() {
|
||||
chunks++;
|
||||
val ps := c.write::<position>();
|
||||
val vs := c.read::<velocity>();
|
||||
for i in 0..c.length {
|
||||
ps[i].x += vs[i].x;
|
||||
}
|
||||
t.expects(c.entities().length == c.length && c.has::<velocity>());
|
||||
}
|
||||
t.expects(chunks == 2);
|
||||
var sum: f32 = 0;
|
||||
w.each(def(p: &position) { sum += p.x; });
|
||||
t.expects(sum == 1225 + 100);
|
||||
}
|
||||
|
||||
@test def sees_what_changed(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val a := w.spawn_with(position{}, velocity{ x = 1 });
|
||||
val b := w.spawn_with(position{}, frozen{});
|
||||
var moved := w.query(changed::<position>());
|
||||
|
||||
# Every table is new to the query, and was written as its entities were made.
|
||||
t.expects(moved.count() == 2);
|
||||
var seen := 0u;
|
||||
moved.each(def(p: &position) { seen++; });
|
||||
t.expects(seen == 2);
|
||||
|
||||
# Nothing was written since.
|
||||
seen = 0;
|
||||
moved.each(def(p: &position) { seen++; });
|
||||
t.expects(seen == 0);
|
||||
|
||||
# A pass writing positions writes those of its tables.
|
||||
w.each(def(p: &mut position, v: &velocity) { p.x += v.x; });
|
||||
seen = 0;
|
||||
moved.each(def(e: entity, p: &position) {
|
||||
t.expects(e == a);
|
||||
seen++;
|
||||
});
|
||||
t.expects(seen == 1);
|
||||
|
||||
# As does `set`.
|
||||
w.set(b, position{ x = 4 });
|
||||
seen = 0;
|
||||
moved.each(def(e: entity, p: &position) {
|
||||
t.expects(e == b);
|
||||
seen++;
|
||||
});
|
||||
t.expects(seen == 1);
|
||||
}
|
||||
|
||||
@test def passes_in_parallel(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
w.threads(4);
|
||||
val count: u64 = 100000;
|
||||
for i in 0..count {
|
||||
_ = w.spawn_with(position{ x = i as f32 }, velocity{ x = 1, y = 2 }, health{ points = i as i64 });
|
||||
}
|
||||
w.par_each(def(p: &mut position, v: &velocity) {
|
||||
p.x += v.x;
|
||||
p.y += v.y;
|
||||
});
|
||||
var wrong := 0u;
|
||||
var total: i64 = 0;
|
||||
w.each(def(p: &position, h: &health) {
|
||||
if p.x != h.points as f32 + 1 || p.y != 2 {
|
||||
wrong++;
|
||||
}
|
||||
total += h.points;
|
||||
});
|
||||
t.expects(wrong == 0 && total == (count * (count - 1) / 2) as i64);
|
||||
|
||||
# Changes deferred on several threads are made as the pass ends, entities
|
||||
# spawned among them.
|
||||
w.par_each(def(e: entity, h: &health) {
|
||||
if h.points % 4 == 0 {
|
||||
_ = w.despawn(e);
|
||||
}
|
||||
if h.points % 100 == 1 {
|
||||
_ = w.spawn_with(frozen{}, health{ points = -1 });
|
||||
}
|
||||
});
|
||||
t.expects(w.count == count - count / 4 + count / 100);
|
||||
t.expects(w.query(with::<frozen>()).count() == count / 100);
|
||||
}
|
||||
|
||||
# What the threads sharing a world counted, each writing its own.
|
||||
var shared_frozen: u64 = 0;
|
||||
var shared_rows: u64 = 0;
|
||||
var shared_unfrozen: u64 = 0;
|
||||
|
||||
# Moves each position by its velocity, twenty times.
|
||||
def moves(at: *mut world): void {
|
||||
val w := &mut through(at);
|
||||
for _ in 0..20u {
|
||||
w.each(def(p: &mut position, v: &velocity) { p.x += v.x; });
|
||||
}
|
||||
}
|
||||
|
||||
# Takes ten points from each health, then despawns those left with none.
|
||||
def ages(at: *mut world): void {
|
||||
val w := &mut through(at);
|
||||
for _ in 0..10u {
|
||||
w.each(def(h: &mut health) { h.points -= 1; });
|
||||
}
|
||||
w.each(def(e: entity, h: &health) {
|
||||
if h.points <= 0 {
|
||||
_ = w.despawn(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
# Counts by queries the world hasn't seen: by a path, by `par_each`, and by
|
||||
# chunks.
|
||||
def counts(at: *mut world): void {
|
||||
val w := &mut through(at);
|
||||
shared_frozen = w.query(with_path(path_of::<frozen>())).count();
|
||||
var rows := 0u;
|
||||
w.par_each(def(v: &velocity) { rows++; });
|
||||
shared_rows = rows;
|
||||
for c in w.query(with::<velocity>().without::<frozen>()).chunks() {
|
||||
shared_unfrozen += c.length;
|
||||
}
|
||||
}
|
||||
|
||||
# Makes every fifth entity a player, which the world defers.
|
||||
def picks(at: *mut world): void {
|
||||
val w := &mut through(at);
|
||||
w.each(def(e: entity, v: &velocity) {
|
||||
if e.index % 5 == 0 {
|
||||
w.add::<player>(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@test def shares_the_world_between_threads(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val count: u64 = 40000;
|
||||
for i in 0..count {
|
||||
val e := w.spawn_with(position{}, velocity{ x = 1 }, health{ points = (i % 20) as i64 });
|
||||
if i % 4 == 0 {
|
||||
w.add::<frozen>(e);
|
||||
}
|
||||
}
|
||||
w.begin_sharing();
|
||||
t.expects(w.shared);
|
||||
val at := address(&mut w);
|
||||
var a := thread::spawn_with(moves, at) else (_) { return; };
|
||||
var b := thread::spawn_with(ages, at) else (_) { return; };
|
||||
var c := thread::spawn_with(counts, at) else (_) { return; };
|
||||
var d := thread::spawn_with(picks, at) else (_) { return; };
|
||||
a.join();
|
||||
b.join();
|
||||
c.join();
|
||||
d.join();
|
||||
t.expects(shared_frozen == count / 4 && shared_rows == count && shared_unfrozen == count - count / 4);
|
||||
|
||||
# What the threads deferred is made as the sharing ends: those of health
|
||||
# 10 or less despawned, and a player made of every fifth left.
|
||||
t.expects(w.count == count);
|
||||
w.end_sharing();
|
||||
t.expects(!w.shared && w.count == count * 9 / 20);
|
||||
var wrong := 0u;
|
||||
w.each(def(p: &position, h: &health) {
|
||||
if p.x != 20 || h.points <= 0 {
|
||||
wrong++;
|
||||
}
|
||||
});
|
||||
t.expects(wrong == 0);
|
||||
t.expects(w.query(with::<player>()).count() == count / 20);
|
||||
}
|
||||
|
||||
@test def holds_resources(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
t.expects(w.resource::<health>().is_none);
|
||||
w.set_resource(health{ points = 3 });
|
||||
if w.resource::<health>() is some(&mut h) {
|
||||
h.points++;
|
||||
}
|
||||
t.expects(held(&mut w, def(h: &health) => h.points == 4));
|
||||
w.set_resource(health{ points = 9 });
|
||||
t.expects(held(&mut w, def(h: &health) => h.points == 9));
|
||||
t.expects(w.remove_resource::<health>() && !w.remove_resource::<health>());
|
||||
t.expects(w.resource::<health>().is_none);
|
||||
|
||||
# Closed the last given first, as one made of another closes before it.
|
||||
closed_order = 0;
|
||||
hold_two_and_close();
|
||||
t.expects(closed_order == 21);
|
||||
}
|
||||
|
||||
# The marks of the resources closed, a digit each, in the order they closed.
|
||||
var closed_order: u64 = 0;
|
||||
|
||||
# Resources noting their closing, as a window, and a renderer drawing into it.
|
||||
struct held_first : owning {
|
||||
var mark: u64;
|
||||
}
|
||||
|
||||
def held_first::close(&mut this): void {
|
||||
if this.mark != 0 {
|
||||
closed_order = closed_order * 10 + this.mark;
|
||||
}
|
||||
}
|
||||
|
||||
struct held_second : owning {
|
||||
var mark: u64;
|
||||
}
|
||||
|
||||
def held_second::close(&mut this): void {
|
||||
if this.mark != 0 {
|
||||
closed_order = closed_order * 10 + this.mark;
|
||||
}
|
||||
}
|
||||
|
||||
# Gives a world two resources, which close with it.
|
||||
def hold_two_and_close(): void {
|
||||
var w := world::new();
|
||||
w.set_resource(held_first{ mark = 1 });
|
||||
w.set_resource(held_second{ mark = 2 });
|
||||
}
|
||||
|
||||
# A system of its own type, keeping its query between runs, so it sees what
|
||||
# changed since it last ran.
|
||||
struct watcher : invokable<def(&mut world): void> {
|
||||
var moved: query;
|
||||
var counts: *mut vector<u64>; # How many it saw, each run.
|
||||
}
|
||||
|
||||
def watcher::invoke(&mut this, w: &mut world): void {
|
||||
var seen := 0u;
|
||||
this.moved.each(def(p: &position) { seen++; });
|
||||
through(this.counts).append(seen);
|
||||
}
|
||||
|
||||
@test def runs_systems_in_order(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
for _ in 0..3u {
|
||||
_ = w.spawn_with(position{}, velocity{ x = 1 });
|
||||
}
|
||||
_ = w.spawn_with(position{});
|
||||
var order := vector::<u64>::new();
|
||||
var counts := vector::<u64>::new();
|
||||
var plan := schedule::new();
|
||||
plan.add("watch", watcher{ moved = w.query(changed::<position>()), counts = &mut counts });
|
||||
plan.add("move", def(into: &mut world) {
|
||||
order.append(1);
|
||||
into.each(def(p: &mut position, v: &velocity) { p.x += v.x; });
|
||||
});
|
||||
plan.add("count", def(into: &mut world) { order.append(2); });
|
||||
t.expects(plan.length == 3);
|
||||
|
||||
plan.run(&mut w);
|
||||
plan.run(&mut w);
|
||||
t.expects(order.length == 4 && order[0] == 1 && order[1] == 2 && order[2] == 1 && order[3] == 2);
|
||||
w.each(def(p: &position, v: &velocity) { t.expects(p.x == 2); });
|
||||
# The watcher saw every position first, then those `move` wrote since.
|
||||
t.expects(counts.length == 2 && counts[0] == 4 && counts[1] == 3);
|
||||
val timings := plan.timings();
|
||||
t.expects(timings.span.find("watch: ").is_some && timings.span.find("count: ").is_some);
|
||||
}
|
||||
|
||||
@test def applies_commands(t: &mut tester): void {
|
||||
names_closed = 0;
|
||||
var w := world::new();
|
||||
val a := w.spawn_with(position{});
|
||||
val b := w.spawn_with(position{}, velocity{});
|
||||
var later := commands::new();
|
||||
later.set(a, velocity{ x = 3 });
|
||||
later.remove::<velocity>(b);
|
||||
later.despawn(b);
|
||||
later.set(b, named::of("never"));
|
||||
later.add::<frozen>(a);
|
||||
t.expects(later.length == 5 && !w.has::<velocity>(a));
|
||||
w.apply(&mut later);
|
||||
t.expects(later.length == 0);
|
||||
t.expects(given(&mut w, a, def(v: &velocity) => v.x == 3) && w.has::<frozen>(a));
|
||||
t.expects(!w.alive(b));
|
||||
# The value given the despawned entity was closed.
|
||||
t.expects(names_closed == 1);
|
||||
}
|
||||
|
||||
@test def tells_apart_components_of_one_name(t: &mut tester): void {
|
||||
# Types are known by their paths, so another module's `position` is a
|
||||
# component of its own, which a function names as its module does.
|
||||
var w := world::new();
|
||||
val e := w.spawn_with(position{ x = 1 }, elsewhere::position{ x = 2 });
|
||||
var mine: f32 = 0;
|
||||
var theirs: f32 = 0;
|
||||
w.each(def(p: &position, q: &mut elsewhere::position) {
|
||||
mine = p.x;
|
||||
theirs = q.x;
|
||||
q.x = 3;
|
||||
});
|
||||
t.expects(mine == 1 && theirs == 2);
|
||||
t.expects(given(&mut w, e, def(q: &elsewhere::position) => q.x == 3));
|
||||
t.expects(w.describe(e) == "position, elsewhere::position");
|
||||
}
|
||||
|
||||
@test def reaches_components_by_their_keys(t: &mut tester): void {
|
||||
# By its type's key, and the bytes of a value, as a program does for code it
|
||||
# runs that names a type the program doesn't.
|
||||
var w := world::new();
|
||||
val e := w.spawn_with(position{ x = 1 }, named::of("box"));
|
||||
val key := component_key::<position>();
|
||||
t.expects(w.info_by_key(key) != null && w.info_by_key(key)[0].size == 8);
|
||||
val at := w.get_by_key(e, key) as *mut position;
|
||||
t.expects(at != null && at[0].x == 1);
|
||||
at[0].x = 4;
|
||||
t.expects(given(&mut w, e, def(p: &position) => p.x == 4));
|
||||
t.expects(w.has_by_key(e, component_key::<named>()) && !w.has_by_key(e, component_key::<velocity>()));
|
||||
# A type of plain data the world never met, as the program makes it.
|
||||
var speed := velocity{ x = 2, y = 3 };
|
||||
val made := component_info::plain(component_key::<velocity>(), "velocity", "velocity", size_of::<velocity>(), align_of::<velocity>());
|
||||
w.set_by_info(e, &made, (&mut speed) as *mut u8);
|
||||
t.expects(given(&mut w, e, def(v: &velocity) => v.x == 2 && v.y == 3));
|
||||
var found := vector::<entity>::new();
|
||||
w.entities_by_key(component_key::<velocity>(), &mut found);
|
||||
t.expects(found.length == 1 && found[0] == e);
|
||||
t.expects(w.remove_by_key(e, component_key::<velocity>()) && !w.has::<velocity>(e));
|
||||
w.set_resource(health{ points = 9 });
|
||||
val held := w.resource_by_key(component_key::<health>()) as *mut health;
|
||||
t.expects(held != null && held[0].points == 9 && w.resource_info_by_key(component_key::<health>()) != null);
|
||||
t.expects(w.resource_by_key(component_key::<frozen>()) == null);
|
||||
# A resource of a type the world never met, and one replaced.
|
||||
w.set_resource_by_info(&made, (&mut speed) as *mut u8);
|
||||
var faster := velocity{ x = 5, y = 6 };
|
||||
w.set_resource_by_info(&made, (&mut faster) as *mut u8);
|
||||
t.expects(w.resource::<velocity>() is some(&mut v) && v.x == 5 && v.y == 6);
|
||||
var less := health{ points = 2 };
|
||||
w.set_resource_by_info(w.resource_info_by_key(component_key::<health>()), (&mut less) as *mut u8);
|
||||
t.expects(w.resource::<health>() is some(&mut h) && h.points == 2);
|
||||
# A schedule's systems are taken out by name.
|
||||
var plan := schedule::new();
|
||||
plan.add("first", def(into: &mut world) {});
|
||||
plan.add("second", def(into: &mut world) {});
|
||||
t.expects(plan.remove("first") && !plan.remove("first") && plan.length == 1);
|
||||
}
|
||||
|
||||
# What follows another entity, as a camera its player: a component naming an
|
||||
# entity, which a format writes by the numbering applied.
|
||||
@serial
|
||||
struct follows {
|
||||
@serial var target: entity;
|
||||
@serial var gap: f32 = 2;
|
||||
}
|
||||
|
||||
# The JSON of a `follows` naming a number, then the text after it.
|
||||
def naming(number: u64, after: strview): string {
|
||||
var made := string::from("{\"target\":", nothing{});
|
||||
made.append($"{number}".span);
|
||||
made.append(after);
|
||||
return made;
|
||||
}
|
||||
|
||||
# The entity a `follows` read from JSON names, or `entity::none`.
|
||||
def target_read(text: strview): entity {
|
||||
val read := json::from_text::<follows>(text) else (_) { return entity::none; };
|
||||
return read.target;
|
||||
}
|
||||
|
||||
# Reads with another numbering applied, which names an entity 20 too.
|
||||
def read_within(w: &mut world): entity {
|
||||
var other := entity_numbering::new();
|
||||
val c := w.spawn();
|
||||
other.set(c, 20);
|
||||
val applied := other.apply();
|
||||
seen_within = c;
|
||||
return target_read("{\"target\": 20, \"gap\": 1}");
|
||||
}
|
||||
|
||||
var seen_within := entity::none;
|
||||
|
||||
@test def writes_entities_by_a_numbering(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val a := w.spawn();
|
||||
val b := w.spawn();
|
||||
# With none applied, an entity is written as its bits, and none as nothing.
|
||||
t.expects(json::to_text(&follows{ target = b }).value.span == naming(b.bits, ",\"gap\":2}").span);
|
||||
t.expects(json::to_text(&follows{ target = entity::none }).value.span == "{\"target\":null,\"gap\":2}");
|
||||
t.expects(target_read(naming(b.bits, ",\"gap\":1}").span) == b);
|
||||
|
||||
# Applied, each is written as its number, and read as the entity its number
|
||||
# names; one it gives no number is written as nothing.
|
||||
var ids := entity_numbering::new();
|
||||
ids.set(a, 10);
|
||||
ids.set(b, 20);
|
||||
t.expects(ids.number_of(b).some == 20 && ids.entity_of(10).some == a && ids.entity_of(30) is none);
|
||||
val applied := ids.apply();
|
||||
t.expects(json::to_text(&follows{ target = b, gap = 1.5 }).value.span == "{\"target\":20,\"gap\":1.5}");
|
||||
t.expects(json::to_text(&follows{ target = w.spawn() }).value.span == "{\"target\":null,\"gap\":2}");
|
||||
t.expects(target_read("{\"target\": 20, \"gap\": 1}") == b);
|
||||
t.expects(json::from_text::<follows>("{\"target\": 30, \"gap\": 1}").error.kind == json::error_kind::out_of_range);
|
||||
|
||||
# One applied within it is applied until it closes, then this one again.
|
||||
t.expects(read_within(&mut w) == seen_within && seen_within != b);
|
||||
t.expects(target_read("{\"target\": 20, \"gap\": 1}") == b);
|
||||
}
|
||||
|
||||
# How many entities a query passes, by a pass.
|
||||
def passed(q: &mut query): u64 {
|
||||
var seen := 0u;
|
||||
q.each(def(e: entity) { seen++; });
|
||||
return seen;
|
||||
}
|
||||
|
||||
@test def knows_what_changed_of_each_entity(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val a := w.spawn_with(position{}, velocity{ x = 1 });
|
||||
val b := w.spawn_with(position{}, velocity{});
|
||||
val c := w.spawn_with(position{}, frozen{});
|
||||
var moved := w.query(changed::<position>());
|
||||
|
||||
# Every entity, the first time; none since.
|
||||
t.expects(moved.count() == 3 && passed(&mut moved) == 3);
|
||||
t.expects(moved.count() == 0 && passed(&mut moved) == 0);
|
||||
|
||||
# One set, and not the other of its table.
|
||||
w.set(b, position{ x = 2 });
|
||||
t.expects(moved.count() == 1);
|
||||
moved.each(def(e: entity) { t.expects(e == b); });
|
||||
|
||||
# A pass writing positions writes those it passes.
|
||||
w.each(def(p: &mut position, v: &velocity) { p.x += v.x; });
|
||||
t.expects(passed(&mut moved) == 2);
|
||||
|
||||
# One moved to another table keeps when its value was written.
|
||||
w.add::<player>(c);
|
||||
t.expects(passed(&mut moved) == 0);
|
||||
w.set(c, position{ x = 1 });
|
||||
t.expects(passed(&mut moved) == 1);
|
||||
|
||||
# A pass of those whose velocity changed writes the positions of those alone.
|
||||
var fast := w.query(changed::<velocity>());
|
||||
t.expects(passed(&mut fast) == 2);
|
||||
w.set(a, velocity{ x = 3 });
|
||||
fast.each(def(p: &mut position, v: &velocity) { p.x += v.x; });
|
||||
moved.each(def(e: entity) { t.expects(e == a); });
|
||||
|
||||
# Chunks say which of their entities pass.
|
||||
w.set(b, position{ x = 7 });
|
||||
var walked := 0u;
|
||||
for ch in moved.chunks() {
|
||||
val es := ch.entities();
|
||||
for i in 0..ch.length {
|
||||
if ch.passes(i) {
|
||||
t.expects(es[i] == b);
|
||||
walked++;
|
||||
}
|
||||
}
|
||||
}
|
||||
t.expects(walked == 1);
|
||||
}
|
||||
|
||||
@test def knows_what_was_added_to_each_entity(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val a := w.spawn_with(position{});
|
||||
var given := w.query(added::<frozen>());
|
||||
t.expects(passed(&mut given) == 0);
|
||||
|
||||
# Tags as well as values, given or spawned with.
|
||||
w.add::<frozen>(a);
|
||||
val b := w.spawn_with(position{}, frozen{});
|
||||
t.expects(given.count() == 2 && passed(&mut given) == 2);
|
||||
t.expects(passed(&mut given) == 0);
|
||||
|
||||
# Moving to another table, it isn't given it again; taken and given, it is.
|
||||
w.add::<player>(b);
|
||||
_ = w.remove::<frozen>(a);
|
||||
w.add::<frozen>(a);
|
||||
given.each(def(e: entity) { t.expects(e == a); });
|
||||
t.expects(passed(&mut given) == 0);
|
||||
|
||||
# Of a value, as `set` gives one the entity lacked, and not as it replaces it.
|
||||
var speeds := w.query(added::<velocity>());
|
||||
t.expects(passed(&mut speeds) == 0);
|
||||
w.set(a, velocity{ x = 1 });
|
||||
w.set(a, velocity{ x = 2 });
|
||||
t.expects(passed(&mut speeds) == 1);
|
||||
}
|
||||
|
||||
# What the observers of the tests saw.
|
||||
var observed_added: u64 = 0;
|
||||
var observed_speed: f32 = 0;
|
||||
|
||||
def count_added(w: &mut world, e: entity): void {
|
||||
observed_added++;
|
||||
}
|
||||
|
||||
@test def runs_observers_as_components_are_given_and_taken(t: &mut tester): void {
|
||||
observed_added = 0;
|
||||
observed_speed = 0;
|
||||
var w := world::new();
|
||||
val counting := w.observe::<velocity>(change::added, count_added);
|
||||
# Run as it's taken, the value still there to read.
|
||||
_ = w.observe::<velocity>(change::removed, def(at, e) {
|
||||
if at.get::<velocity>(e) is some(&mut v) {
|
||||
observed_speed += v.x;
|
||||
}
|
||||
});
|
||||
val a := w.spawn_with(position{}, velocity{ x = 2 });
|
||||
w.set(a, velocity{ x = 5 });
|
||||
t.expects(observed_added == 1);
|
||||
_ = w.remove::<velocity>(a);
|
||||
w.set(a, velocity{ x = 1 });
|
||||
t.expects(observed_added == 2 && observed_speed == 5);
|
||||
_ = w.despawn(a);
|
||||
t.expects(observed_speed == 6);
|
||||
|
||||
# What an observer changes is made once the change it saw is done.
|
||||
_ = w.observe::<frozen>(change::added, def(at, e) { at.add::<player>(e); });
|
||||
val b := w.spawn_with(position{});
|
||||
w.add::<frozen>(b);
|
||||
t.expects(w.has::<player>(b));
|
||||
|
||||
# Given within a pass, as it ends.
|
||||
w.each(def(e: entity, p: &position) { w.set(e, velocity{}); });
|
||||
t.expects(observed_added == 3);
|
||||
|
||||
# Taken out, it runs no more.
|
||||
t.expects(w.unobserve(counting) && !w.unobserve(counting));
|
||||
_ = w.remove::<velocity>(b);
|
||||
w.set(b, velocity{});
|
||||
t.expects(observed_added == 3);
|
||||
}
|
||||
|
||||
@test def keeps_parents_and_children(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val root := w.spawn_with(position{});
|
||||
val arm := w.spawn_with(position{});
|
||||
val hand := w.spawn_with(position{});
|
||||
val other := w.spawn();
|
||||
w.set_parent(arm, root);
|
||||
w.set_parent(hand, arm);
|
||||
t.expects(w.parent_of(hand) is some(p) && p == arm);
|
||||
t.expects(w.children_of(root).length == 1 && w.children_of(root)[0] == arm);
|
||||
|
||||
# Given another parent, it leaves the one it had; taken from it, it's of the
|
||||
# world.
|
||||
w.set_parent(hand, other);
|
||||
t.expects(w.children_of(arm).length == 0 && w.children_of(other).length == 1);
|
||||
t.expects(w.remove_parent(hand) && w.parent_of(hand) is none && w.children_of(other).length == 0);
|
||||
t.expects(!w.remove_parent(hand));
|
||||
w.set_parent(hand, arm);
|
||||
|
||||
# Despawned, those within it are too, and it leaves its parent.
|
||||
_ = w.despawn(root);
|
||||
t.expects(!w.alive(root) && !w.alive(arm) && !w.alive(hand) && w.alive(other));
|
||||
val p := w.spawn();
|
||||
val first := w.spawn();
|
||||
val second := w.spawn();
|
||||
w.set_parent(first, p);
|
||||
w.set_parent(second, p);
|
||||
_ = w.despawn(first);
|
||||
t.expects(w.children_of(p).length == 1 && w.children_of(p)[0] == second);
|
||||
|
||||
# Commands spawn children; within a pass, a child is given as it ends.
|
||||
var later := w.commands();
|
||||
val kid := later.spawn_with(position{ x = 3 });
|
||||
later.set_parent(kid, p);
|
||||
w.apply(&mut later);
|
||||
t.expects(w.parent_of(kid) is some(q) && q == p && given(&mut w, kid, def(x: &position) => x.x == 3));
|
||||
w.each(def(e: entity, x: &position) { w.set_parent(e, second); });
|
||||
t.expects(w.parent_of(kid) is some(q) && q == second && w.children_of(p).length == 1);
|
||||
|
||||
# Their `children` taken, they're of the world.
|
||||
_ = w.remove::<children>(second);
|
||||
t.expects(w.parent_of(kid) is none);
|
||||
}
|
||||
|
||||
# Spawns a child of each entity of an index a multiple of 10, and of a parity,
|
||||
# and spawns by commands of the world as well.
|
||||
def spawns_children(at: *mut world, parity: u32, later: *mut commands): void {
|
||||
val w := &mut through(at);
|
||||
w.each(def(e: entity, v: &velocity) {
|
||||
if e.index % 10 == 0 && e.index % 20 == parity * 10 {
|
||||
val made := w.spawn_with(position{ x = e.index as f32 });
|
||||
w.set_parent(made, e);
|
||||
_ = through(later).spawn_with(health{ points = 1 });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
# The commands of each of two threads.
|
||||
var even_commands: commands;
|
||||
var odd_commands: commands;
|
||||
|
||||
def spawns_even(at: *mut world): void { spawns_children(at, 0, address(&mut even_commands)); }
|
||||
def spawns_odd(at: *mut world): void { spawns_children(at, 1, address(&mut odd_commands)); }
|
||||
|
||||
@test def spawns_while_threads_share_the_world(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
for i in 0..1000 {
|
||||
val e := w.spawn_with(velocity{ x = 1 });
|
||||
# Some freed, so threads take those numbers too.
|
||||
if i % 200 == 3 {
|
||||
_ = w.despawn(e);
|
||||
}
|
||||
}
|
||||
even_commands = w.commands();
|
||||
odd_commands = w.commands();
|
||||
w.begin_sharing();
|
||||
val at := address(&mut w);
|
||||
var a := thread::spawn_with(spawns_even, at) else (_) { return; };
|
||||
var b := thread::spawn_with(spawns_odd, at) else (_) { return; };
|
||||
a.join();
|
||||
b.join();
|
||||
w.end_sharing();
|
||||
w.apply(&mut even_commands);
|
||||
w.apply(&mut odd_commands);
|
||||
# A child of each of a hundred, and a hundred by commands.
|
||||
t.expects(w.query(with::<position>()).count() == 100 && w.query(with::<health>()).count() == 100);
|
||||
var wrong := 0u;
|
||||
w.each(def(e: entity, p: &position) {
|
||||
if !(w.parent_of(e) is some(above) && above.index as f32 == p.x && w.has::<velocity>(above)) {
|
||||
wrong++;
|
||||
}
|
||||
});
|
||||
t.expects(wrong == 0 && w.count == 995 + 200);
|
||||
even_commands.close();
|
||||
odd_commands.close();
|
||||
}
|
||||
|
||||
@test def tracks_what_queries_first_ask_while_shared(t: &mut tester): void {
|
||||
var w := world::new();
|
||||
val a := w.spawn_with(health{ points = 1 });
|
||||
_ = w.spawn_with(health{ points = 2 });
|
||||
var hurt := w.query(changed::<health>());
|
||||
w.begin_sharing();
|
||||
t.expects(passed(&mut hurt) == 2);
|
||||
w.end_sharing();
|
||||
t.expects(passed(&mut hurt) == 0);
|
||||
w.set(a, health{ points = 0 });
|
||||
t.expects(passed(&mut hurt) == 1);
|
||||
}
|
||||
|
||||
module elsewhere;
|
||||
|
||||
pub struct position {
|
||||
pub var x: f32;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#! Contains the `main` that runs the tests of `ecs`, each in a copy of the
|
||||
#! program of its own. `blossom test` runs them, and `-- --only TEXT` those
|
||||
#! whose name holds the text.
|
||||
|
||||
import system;
|
||||
import std::testing;
|
||||
|
||||
def main(args: span<strview>): void {
|
||||
exit(tester::run(args));
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
#! Times what `ecs` does most, over a million entities: spawning them, passing
|
||||
#! over them by `each`, by chunks, and by `par_each`, against a loop over plain
|
||||
#! arrays, which is as fast as a pass can be; getting and setting a component;
|
||||
#! moving entities between tables; and despawning them.
|
||||
#!
|
||||
#! `blossom build`, then run `malunal.ecs.bench`, as an executable: the VM's
|
||||
#! times aren't the program's.
|
||||
|
||||
import std::io;
|
||||
import std::time;
|
||||
import malunal::ecs;
|
||||
|
||||
struct pos3 {
|
||||
var x: f32;
|
||||
var y: f32;
|
||||
var z: f32;
|
||||
}
|
||||
|
||||
struct vel3 {
|
||||
var x: f32;
|
||||
var y: f32;
|
||||
var z: f32;
|
||||
}
|
||||
|
||||
struct life {
|
||||
var points: i64;
|
||||
}
|
||||
|
||||
struct marked {}
|
||||
struct tag1 {}
|
||||
struct tag2 {}
|
||||
struct tag3 {}
|
||||
struct tag4 {}
|
||||
struct tag5 {}
|
||||
struct tag6 {}
|
||||
|
||||
# What `each` is given as a type of its own, rather than a lambda, whose calls
|
||||
# go through its address.
|
||||
struct mover : invokable<def(&mut pos3, &vel3): void> {}
|
||||
|
||||
def mover::invoke(&mut this, p: &mut pos3, v: &vel3): void {
|
||||
p.x += v.x;
|
||||
p.y += v.y;
|
||||
p.z += v.z;
|
||||
}
|
||||
|
||||
# How long something took, for each of the things it did.
|
||||
def report(what: strview, started: &instant, things: u64): void {
|
||||
val ns := started.elapsed().in_nanoseconds as f64;
|
||||
println($"{what}: {ns / things as f64} ns each, {ns / 1000000} ms in all");
|
||||
}
|
||||
|
||||
def main(): void {
|
||||
val n: u64 = 1000000;
|
||||
val passes: u64 = 20;
|
||||
var w := world::new();
|
||||
var all := vector::<entity>::new();
|
||||
all.reserve(n);
|
||||
|
||||
var at := instant::now();
|
||||
for i in 0..n {
|
||||
all.append(w.spawn_with(pos3{ x = i as f32 }, vel3{ x = 1, y = 2, z = 3 }));
|
||||
}
|
||||
report("spawn_with of 2 components", &at, n);
|
||||
# Half have another component, so passes go over two tables.
|
||||
for i in 0..n {
|
||||
if i % 2 == 0 {
|
||||
w.set(all[i], life{ points = 1 });
|
||||
}
|
||||
}
|
||||
|
||||
var xs := vector::<pos3>::new();
|
||||
var vs := vector::<vel3>::new();
|
||||
for i in 0..n {
|
||||
xs.append(pos3{ x = i as f32 });
|
||||
vs.append(vel3{ x = 1, y = 2, z = 3 });
|
||||
}
|
||||
at = instant::now();
|
||||
for _ in 0..passes {
|
||||
for i in 0..n {
|
||||
xs[i].x += vs[i].x;
|
||||
xs[i].y += vs[i].y;
|
||||
xs[i].z += vs[i].z;
|
||||
}
|
||||
}
|
||||
report("plain arrays, a pass", &at, n * passes);
|
||||
|
||||
at = instant::now();
|
||||
for _ in 0..passes {
|
||||
w.each(def(p: &mut pos3, v: &vel3) {
|
||||
p.x += v.x;
|
||||
p.y += v.y;
|
||||
p.z += v.z;
|
||||
});
|
||||
}
|
||||
report("each, given a lambda", &at, n * passes);
|
||||
|
||||
at = instant::now();
|
||||
for _ in 0..passes {
|
||||
w.each(mover{});
|
||||
}
|
||||
report("each, given a functor", &at, n * passes);
|
||||
|
||||
at = instant::now();
|
||||
var q := w.query(with::<pos3>().with::<vel3>());
|
||||
for _ in 0..passes {
|
||||
for c in q.chunks() {
|
||||
val ps := c.write::<pos3>();
|
||||
val vels := c.read::<vel3>();
|
||||
for i in 0..c.length {
|
||||
ps[i].x += vels[i].x;
|
||||
ps[i].y += vels[i].y;
|
||||
ps[i].z += vels[i].z;
|
||||
}
|
||||
}
|
||||
}
|
||||
report("chunks", &at, n * passes);
|
||||
|
||||
w.par_each(def(p: &mut pos3, v: &vel3) { p.x += 0; });
|
||||
at = instant::now();
|
||||
for _ in 0..passes {
|
||||
w.par_each(def(p: &mut pos3, v: &vel3) {
|
||||
p.x += v.x;
|
||||
p.y += v.y;
|
||||
p.z += v.z;
|
||||
});
|
||||
}
|
||||
report("par_each", &at, n * passes);
|
||||
|
||||
# Each pass moved every pos3 on by 1.
|
||||
var wrong := 0u;
|
||||
for i in 0..n {
|
||||
if w.get::<pos3>(all[i]) is some(&mut p) {
|
||||
if p.x != (i + passes * 4) as f32 {
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if wrong > 0 {
|
||||
println($"{wrong} positions are wrong");
|
||||
}
|
||||
|
||||
var sum: f64 = 0;
|
||||
at = instant::now();
|
||||
for i in 0..n {
|
||||
if w.get::<pos3>(all[i]) is some(&mut p) {
|
||||
sum += p.x as f64;
|
||||
}
|
||||
}
|
||||
report("get, in order", &at, n);
|
||||
|
||||
at = instant::now();
|
||||
for i in 0..n {
|
||||
if w.get::<pos3>(all[(i * 7919) % n]) is some(&mut p) {
|
||||
sum += p.x as f64;
|
||||
}
|
||||
}
|
||||
report("get, in no order", &at, n);
|
||||
|
||||
at = instant::now();
|
||||
for i in 0..n {
|
||||
w.set(all[i], vel3{ x = 2 });
|
||||
}
|
||||
report("set of a component an entity has", &at, n);
|
||||
|
||||
at = instant::now();
|
||||
for i in 0..n / 10 {
|
||||
w.add::<marked>(all[i * 10]);
|
||||
}
|
||||
for i in 0..n / 10 {
|
||||
_ = w.remove::<marked>(all[i * 10]);
|
||||
}
|
||||
report("add and remove of a tag, each a move", &at, n / 10 * 2);
|
||||
|
||||
# Six tags, given by the bits of each entity's index, spread the entities
|
||||
# over 128 tables.
|
||||
for i in 0..n {
|
||||
val e := all[i];
|
||||
if (i & 1) != 0 { w.add::<tag1>(e); }
|
||||
if (i & 2) != 0 { w.add::<tag2>(e); }
|
||||
if (i & 4) != 0 { w.add::<tag3>(e); }
|
||||
if (i & 8) != 0 { w.add::<tag4>(e); }
|
||||
if (i & 16) != 0 { w.add::<tag5>(e); }
|
||||
if (i & 32) != 0 { w.add::<tag6>(e); }
|
||||
}
|
||||
at = instant::now();
|
||||
for _ in 0..passes {
|
||||
w.each(def(p: &mut pos3, v: &vel3) {
|
||||
p.x += v.x;
|
||||
p.y += v.y;
|
||||
p.z += v.z;
|
||||
});
|
||||
}
|
||||
report($"each, over {w.archetypes} tables", &at, n * passes);
|
||||
|
||||
at = instant::now();
|
||||
for i in 0..n {
|
||||
_ = w.despawn(all[i]);
|
||||
}
|
||||
report("despawn", &at, n);
|
||||
|
||||
var later := w.commands();
|
||||
at = instant::now();
|
||||
for i in 0..n {
|
||||
all[i] = later.spawn_with(pos3{}, vel3{});
|
||||
}
|
||||
w.apply(&mut later);
|
||||
report("spawn_with of 2 components by commands, applied", &at, n);
|
||||
|
||||
# A query asking what changed tracks each entity's `vel3` from its first
|
||||
# pass, which then costs what writes and moves it more.
|
||||
var moved := w.query(changed::<vel3>());
|
||||
moved.each(def(v: &vel3) {});
|
||||
for i in 0..n / 100 {
|
||||
w.set(all[i * 100], vel3{ x = 3 });
|
||||
}
|
||||
var found := 0u;
|
||||
at = instant::now();
|
||||
moved.each(def(p: &mut pos3, v: &vel3) { found++; });
|
||||
report($"each over what changed, {found} of a million", &at, n);
|
||||
|
||||
at = instant::now();
|
||||
for i in 0..n {
|
||||
w.set(all[i], vel3{ x = 2 });
|
||||
}
|
||||
report("set of a component tracked", &at, n);
|
||||
|
||||
at = instant::now();
|
||||
for i in 0..n / 10 {
|
||||
w.add::<marked>(all[i * 10]);
|
||||
}
|
||||
for i in 0..n / 10 {
|
||||
_ = w.remove::<marked>(all[i * 10]);
|
||||
}
|
||||
report("add and remove of a tag, with a component tracked", &at, n / 10 * 2);
|
||||
|
||||
at = instant::now();
|
||||
for i in 0..n {
|
||||
_ = w.despawn(all[i]);
|
||||
}
|
||||
report("despawn, with a component tracked", &at, n);
|
||||
|
||||
println($"(sums {sum} {xs[n - 1].x} {found}, {w.count} left)");
|
||||
}
|
||||
Reference in new issue
Block a user