Initial Commit
This commit is contained in:
19 files changed
+3767
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,106 @@
|
||||
# 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 ecs;
|
||||
|
||||
struct position { var x: f32; var y: f32; }
|
||||
struct velocity { var x: f32; var y: f32; }
|
||||
struct asleep {} # a tag: a component holding nothing
|
||||
|
||||
var w := world::new();
|
||||
val ball := w.spawn_with(position{}, velocity{ x = 1 });
|
||||
w.add::<asleep>(w.spawn_with(position{ x = 5 }));
|
||||
|
||||
# Each entity having what the function takes, `&T` to read, `&mut T` to write.
|
||||
w.each(def(p: &mut position, v: &velocity) {
|
||||
p.x += v.x;
|
||||
p.y += v.y;
|
||||
});
|
||||
|
||||
# A filter says what the function doesn't take.
|
||||
w.query(without::<asleep>()).each(def(e: entity, p: &position) { ... });
|
||||
|
||||
# Chunks: a table's entities at once, each component a column, for loops of one's own.
|
||||
for c in w.query(with::<position>().with::<velocity>()).chunks() {
|
||||
val ps := c.write::<position>();
|
||||
val vs := c.read::<velocity>();
|
||||
for i in 0..c.length { ps[i].x += vs[i].x; }
|
||||
}
|
||||
|
||||
# On every processor.
|
||||
w.par_each(def(p: &mut position, v: &velocity) { p.x += v.x; });
|
||||
|
||||
if w.get::<position>(ball) is some(&mut p) { p.y = 10; }
|
||||
w.set(ball, velocity{ y = -1 }); # replaces the one it has
|
||||
_ = w.remove::<velocity>(ball);
|
||||
_ = w.despawn(ball);
|
||||
```
|
||||
`tests/ecs.sakura` drives all of it, and `tools/bench.sakura` times it.
|
||||
|
||||
A project reads it by requiring this folder, or its remote, and naming `ecs` among a target's `deps`:
|
||||
|
||||
```yaml
|
||||
requires:
|
||||
- ../ecs
|
||||
targets:
|
||||
- name: game
|
||||
type: program
|
||||
deps: [ecs]
|
||||
```
|
||||
|
||||
## Layout
|
||||
| Path | Holds |
|
||||
|---|---|
|
||||
| `ecs/ecs.sakura` | `entity`, and `component_info`, what a world knows of a type of component |
|
||||
| `ecs/world.sakura` | `world`: spawning and despawning, giving, replacing, taking, and getting components, deferring, `apply`, and resources |
|
||||
| `ecs/table.sakura` | Tables: the entities having one set of components, a column of each component's values |
|
||||
| `ecs/query.sakura` | Filters, 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/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, 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 tables whose `T` was written since its query last passed, as a pass taking `&mut T`, a chunk's `write`, or `set`, writes them: a table passes whole where any of its entities was written. A query remembers when it last passed, so a system keeps its query from one run to the next; a new one finds every table changed, those entities moved into among them.
|
||||
- **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.
|
||||
- **`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, and defer what would move one, but not spawn, 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, and reads resources, and what would move an entity is deferred, as within a pass, until the sharing ends. 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 spawn, meet types it hasn't, be given resources 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 takes a lock, which no world not shared takes.
|
||||
- **Resources** are values of a type a world holds one of, apart from any entity, as a clock: `set_resource`, `resource`, and `remove_resource`.
|
||||
- **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 ecs.bench` over a million entities of two components, built with `-O2`, on a Ryzen 9 9950X3D of 16 cores and 32 threads, its passes each over 36 MB, which its 128 MB of L3 holds:
|
||||
|
||||
| What | Time for each entity |
|
||||
|---|---|
|
||||
| A loop over plain vectors | 1.63 ns |
|
||||
| A loop over a query's chunks | 1.20 ns |
|
||||
| `each`, given a type of one's own with an `invoke` | 1.20 ns |
|
||||
| `each`, given a lambda | 1.95 ns |
|
||||
| `each`, over 67 tables | 1.95 ns |
|
||||
| `par_each`, on 32 threads | 0.28 ns |
|
||||
| `spawn_with` of two components | 27 ns |
|
||||
| `get`, in the order they were spawned | 5.9 ns |
|
||||
| `get`, in no order | 20 ns |
|
||||
| `set` of a component the entity has | 16 ns |
|
||||
| A move to another table, as a tag is added or removed | 50 ns |
|
||||
| `despawn` | 25 ns |
|
||||
|
||||
`each` adds nothing to the loop it makes: given a type of its own, it's as fast as chunks. A lambda costs a call through its address for each entity, 0.75 ns here, as Sakura calls a lambda given to generic code, where a type's `invoke` is inlined; a hot pass gives a type, or walks chunks. A pass this light is bound by memory, which `par_each`'s threads share, so heavier work gains more from them.
|
||||
|
||||
## Testing
|
||||
`blossom test` runs `tests/ecs.sakura`: entities and their generations, components given, replaced, taken, and moved between tables, what closes closed once, passes of every kind of parameter, filters, 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, commands, schedules, components of one name in two modules, components reached by their types' keys, and entities written and read by a numbering. `sakurac run --checks` runs them with every read and write checked, and reports nothing left unreleased.
|
||||
|
||||
## Not yet
|
||||
Relationships between entities, which a program keeps of its own, as hearth's scenes keep parents and children; hooks run as a component is given or taken; the tables a world no longer uses given back; what changed known of each entity rather than each table; spawning, by commands or while threads share a world; 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: ecs
|
||||
type: library
|
||||
root: ./ecs
|
||||
deps:
|
||||
- std.serial
|
||||
- std.thread
|
||||
- std.time
|
||||
|
||||
# Times `ecs` over a million entities; see its header.
|
||||
- name: ecs.bench
|
||||
type: program
|
||||
level: ${level}
|
||||
deps:
|
||||
- ecs
|
||||
- std.io
|
||||
- std.time
|
||||
srcs:
|
||||
- tools/bench.sakura
|
||||
|
||||
tests:
|
||||
- name: ecs.tests
|
||||
type: program
|
||||
deps: [ecs, std.json, std.serial, std.testing, std.thread]
|
||||
srcs: [tests/main.sakura, tests/ecs.sakura]
|
||||
|
||||
exports:
|
||||
- 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,115 @@
|
||||
#! 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 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.
|
||||
}
|
||||
|
||||
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`.
|
||||
}
|
||||
|
||||
#! 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.
|
||||
pub struct commands : owning {
|
||||
var list: vector<command>;
|
||||
var data: *mut u8;
|
||||
var used: u64;
|
||||
var capacity: u64;
|
||||
}
|
||||
|
||||
pub def commands::new(): commands {
|
||||
return commands{ list = vector::<command>::new() };
|
||||
}
|
||||
|
||||
#! 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>());
|
||||
}
|
||||
}
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
#! 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.
|
||||
|
||||
module 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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
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 };
|
||||
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);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
val f := &mut through(work.call);
|
||||
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;
|
||||
}
|
||||
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 };
|
||||
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);
|
||||
var c1 := w.cursor_of(work.query, at.which, 0, at.begin);
|
||||
var c2 := w.cursor_of(work.query, at.which, 1, at.begin);
|
||||
val f := &mut through(work.call);
|
||||
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;
|
||||
}
|
||||
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 };
|
||||
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);
|
||||
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);
|
||||
val f := &mut through(work.call);
|
||||
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;
|
||||
}
|
||||
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 };
|
||||
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);
|
||||
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);
|
||||
val f := &mut through(work.call);
|
||||
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;
|
||||
}
|
||||
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 };
|
||||
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);
|
||||
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);
|
||||
val f := &mut through(work.call);
|
||||
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;
|
||||
}
|
||||
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 };
|
||||
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);
|
||||
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);
|
||||
val f := &mut through(work.call);
|
||||
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;
|
||||
}
|
||||
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 };
|
||||
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);
|
||||
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);
|
||||
val f := &mut through(work.call);
|
||||
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;
|
||||
}
|
||||
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 };
|
||||
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);
|
||||
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);
|
||||
val f := &mut through(work.call);
|
||||
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 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 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;
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#! 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 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) {
|
||||
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.columns[slot as u64].changed = 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,567 @@
|
||||
#! Contains queries: filters saying which entities a pass goes over, passes
|
||||
#! calling a function for each entity, which says what it takes by its
|
||||
#! parameters, and chunks, the columns a table's entities have, for loops of
|
||||
#! one's own.
|
||||
|
||||
module ecs;
|
||||
|
||||
# What a term of a query asks.
|
||||
enum term_kind: u8 {
|
||||
has, # That a table has a component.
|
||||
lacks, # That it hasn't.
|
||||
changed, # That it has one, written since the query last passed.
|
||||
entity_of, # A parameter taking the entity.
|
||||
reads, # A parameter taking `&T`, which a table must have.
|
||||
writes, # A parameter taking `&mut T`, which a table must have.
|
||||
maybe_reads, # A parameter taking `maybe<&T>`.
|
||||
maybe_writes, # A parameter taking `maybe<&mut T>`.
|
||||
by_value, # A parameter taking anything else, which `each` refuses.
|
||||
}
|
||||
|
||||
struct filter_term {
|
||||
var 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 changed. 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 of tables whose component was written since
|
||||
#! the query last passed over them.
|
||||
pub def changed<T>(): filter {
|
||||
val none := filter{};
|
||||
return none.changed::<T>();
|
||||
}
|
||||
|
||||
#! The filter, passing only the entities having a component too.
|
||||
pub def filter::with<T>(&this): filter {
|
||||
return this.and(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. What's written is known of each table, as
|
||||
#! a pass writing a column, or `set` writing one value of it: a table any
|
||||
#! entity of which had its component written passes whole.
|
||||
pub def filter::changed<T>(&this): filter {
|
||||
if size_of::<T>() == 0 {
|
||||
fault($"`changed` was given `{name_of::<T>()}`, a tag, which is never written.");
|
||||
}
|
||||
return this.and(path_of::<T>(), term_kind::changed);
|
||||
}
|
||||
|
||||
#! 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);
|
||||
}
|
||||
|
||||
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'.
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
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 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::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 it's empty, or
|
||||
# a column a `changed` term asks of wasn't written since the query last passed,
|
||||
# where it ever did. Stamps the columns the pass writes.
|
||||
def world::rows_of(&mut this, at: *mut query_state, m: u64, since: u64, now: u64): u64 {
|
||||
val st := &through(at);
|
||||
val t := &mut this.tables[st.matched[m] as u64];
|
||||
return 0 if t.count == 0;
|
||||
val stride := st.terms.length;
|
||||
for i in 0..stride {
|
||||
if st.terms[i].kind == term_kind::changed {
|
||||
val slot := st.slots[m * stride + i];
|
||||
# A query that never passed finds every table changed, though an entity
|
||||
# moved into it, as a tag was added, left its column unwritten there.
|
||||
return 0 if slot >= tagged || (since > 0 && t.columns[slot as u64].changed <= since);
|
||||
}
|
||||
}
|
||||
for i in 0..stride {
|
||||
val kind := st.terms[i].kind;
|
||||
val slot := st.slots[m * stride + i];
|
||||
if (kind == term_kind::writes || kind == term_kind::maybe_writes) && slot < tagged {
|
||||
t.columns[slot as u64].changed = now;
|
||||
}
|
||||
}
|
||||
return t.count;
|
||||
}
|
||||
|
||||
# A place in a column a pass reads from, and how far apart its rows are.
|
||||
struct cursor {
|
||||
var at: *mut u8;
|
||||
var stride: u64;
|
||||
}
|
||||
|
||||
# Where a parameter's values begin in a table matched, from a row: the
|
||||
# column's, the entities', or `null` where an entity may lack it and these do.
|
||||
def world::cursor_of(&this, 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.
|
||||
pub def query::count(&mut this): u64 {
|
||||
val w := &mut through(this.owner);
|
||||
val st := w.query_of(&this.by, span::<param>::empty());
|
||||
var total := 0u;
|
||||
for m in 0..st[0].matched.length {
|
||||
total += w.tables[st[0].matched[m] as u64].count;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
#! The chunks of the entities the filter passes: a chunk for each table, its
|
||||
#! components as columns, for loops of one's own over them. The world defers
|
||||
#! what would move an entity until the chunks are done with.
|
||||
pub def query::chunks(&mut this): chunks {
|
||||
val w := &mut through(this.owner);
|
||||
val q := w.query_of(&this.by, span::<param>::empty());
|
||||
val p := w.begin_pass(&mut this.last);
|
||||
return chunks{ owner = this.owner, query = q, since = p.since, now = p.now, open = true };
|
||||
}
|
||||
|
||||
#! The entities of a table a query passes, side by side, and their components,
|
||||
#! each a column of one value for each entity, in the same order.
|
||||
pub struct chunk {
|
||||
var owner: *mut world;
|
||||
var table: u32;
|
||||
pub val length: u64; #! How many entities.
|
||||
var now: u64;
|
||||
}
|
||||
|
||||
#! Its entities.
|
||||
pub def chunk::entities(&this): span<entity> {
|
||||
val t := &through(this.owner).tables[this.table as u64];
|
||||
return span::<entity>::over(t.entities, this.length);
|
||||
}
|
||||
|
||||
#! Whether its entities have a component.
|
||||
pub def chunk::has<T>(&this): bool {
|
||||
val w := &mut through(this.owner);
|
||||
return w.tables[this.table as u64].has(w.find_id(info_of::<T>()));
|
||||
}
|
||||
|
||||
#! Its entities' values of a component, to read.
|
||||
pub def chunk::read<T>(&this): span<T> {
|
||||
return span::<T>::over(this.column_of(info_of::<T>(), false) as *T, this.length);
|
||||
}
|
||||
|
||||
#! Its entities' values of a component, to write, which `changed` filters then
|
||||
#! pass.
|
||||
pub def chunk::write<T>(&this): slice<T> {
|
||||
return slice::<T>::over(this.column_of(info_of::<T>(), true) as *mut T, this.length);
|
||||
}
|
||||
|
||||
def chunk::column_of(&this, info: *component_info, writing: bool): *mut u8 {
|
||||
val w := &mut through(this.owner);
|
||||
val id := w.find_id(info);
|
||||
val t := &mut w.tables[this.table as u64];
|
||||
val slot := id == absent ? absent : t.slot_of(id);
|
||||
if slot == absent {
|
||||
fault($"A chunk's entities haven't `{info[0].path}`: a filter `with` it passes only those that have it.");
|
||||
}
|
||||
if slot == tagged {
|
||||
fault($"`{info[0].path}` is a tag, which has no values: `has` asks of it.");
|
||||
}
|
||||
if writing {
|
||||
t.columns[slot as u64].changed = this.now;
|
||||
}
|
||||
return t.columns[slot as u64].data;
|
||||
}
|
||||
|
||||
#! The chunks a query passes, one for each table having entities, which `for`
|
||||
#! walks. Closing it ends the pass, whether walked to its end or not.
|
||||
pub struct chunks : owning, iterator<chunk> {
|
||||
var owner: *mut world;
|
||||
var query: *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 };
|
||||
}
|
||||
}
|
||||
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,93 @@
|
||||
#! Contains `schedule`: systems, the functions a program runs over its world,
|
||||
#! in order, timing each.
|
||||
|
||||
import std::time;
|
||||
module 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.view() == 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 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,57 @@
|
||||
#! 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 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, or a despawn, is deferred,
|
||||
#! as within a pass, and made as the sharing ends, in the order the threads
|
||||
#! deferred them.
|
||||
#!
|
||||
#! 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 spawn
|
||||
#! entities, meet types it hasn't, be given resources 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--;
|
||||
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,135 @@
|
||||
#! Contains `table`: the entities having one set of components, an archetype,
|
||||
#! each component a column of their values in the entities' order.
|
||||
|
||||
module 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 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.
|
||||
struct table : owning {
|
||||
var ids: vector<u32>; # Its components, in order.
|
||||
var slots: vector<u32>; # Each one's column, or `tagged`.
|
||||
var columns: vector<column>;
|
||||
var entities: *mut entity;
|
||||
var count: u64;
|
||||
var capacity: u64;
|
||||
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);
|
||||
}
|
||||
this.entities = resized(this.entities as *mut u8, size * 8) as *mut entity;
|
||||
this.capacity = size;
|
||||
}
|
||||
|
||||
# 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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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,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 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.view().data, count = cut.length };
|
||||
this.crew.run(&given);
|
||||
this.parallel = false;
|
||||
}
|
||||
@@ -0,0 +1,727 @@
|
||||
#! Contains `world`: entities, the components each has, and the resources the
|
||||
#! world holds apart from any entity.
|
||||
|
||||
import system;
|
||||
module ecs;
|
||||
|
||||
# Where an entity is.
|
||||
struct record {
|
||||
var table: u32; # Its table; `absent` where its index is free, or `pending` where it was spawned while the world deferred.
|
||||
var row: u32; # Its row; while its index is free, the next free index, or `absent`.
|
||||
var generation: u32;
|
||||
}
|
||||
|
||||
# A record's table where its entity was spawned while the world deferred, and
|
||||
# is in no table until the world stops.
|
||||
const pending: u32 = 0xFFFFFFFD;
|
||||
|
||||
# One value of a type, which the world holds apart from any entity.
|
||||
struct resource {
|
||||
var info: *component_info;
|
||||
var data: *mut u8; # Or `null` where it was removed.
|
||||
}
|
||||
|
||||
#! Entities, and the components each has.
|
||||
#!
|
||||
#! Entities with the same set of components are kept together, in a table
|
||||
#! whose columns are their components, so a pass over the entities having some
|
||||
#! components walks along the columns of the tables having them. An entity
|
||||
#! gaining or losing a component moves to the table having its new set, which
|
||||
#! each table remembers, so the move is found once.
|
||||
#!
|
||||
#! While a query passes over it, the world defers what would move an entity:
|
||||
#! components given or taken, spawns, and despawns are kept, and made as the
|
||||
#! outermost pass ends, so the tables a pass walks stay as they are. A value an
|
||||
#! entity has already is replaced where it is, at once.
|
||||
#!
|
||||
#! Several threads pass over it at once while it's shared, from `begin_sharing`
|
||||
#! to `end_sharing`, as an engine runs systems reaching different components.
|
||||
pub struct world : owning {
|
||||
var records: vector<record>;
|
||||
var free: u32; # The first free index, or `absent`.
|
||||
var living: u64;
|
||||
var infos: vector<*component_info>; # Of each component, by its id.
|
||||
var by_key: idmap; # Ids by the types' keys.
|
||||
var tables: vector<table>; # The first holds the entities with no components.
|
||||
var by_hash: idmap; # The first table of each hash of components.
|
||||
var bundles: idmap; # Tables by the types `spawn_with` was given.
|
||||
var queries: vector<box<query_state>>; # Each where it stays, as a pass keeps its address.
|
||||
var cached: idmap; # Queries by the hash of what they ask.
|
||||
var deferring: u32; # How many passes are going on, and whether it's shared.
|
||||
var pending: commands; # What the passes deferred.
|
||||
var tick: atomic<u64>; # Counts passes and changes, for `changed`.
|
||||
var resources: vector<resource>;
|
||||
var by_resource: idmap;
|
||||
var crew: workers;
|
||||
var parallel: bool; # Whether `par_each` is calling functions on several threads.
|
||||
var sharing: bool; # Whether threads share it, between `begin_sharing` and `end_sharing`.
|
||||
var guard: atomic<u32>; # Held while a thread defers a change or finds a query, as `parallel` or `sharing` is.
|
||||
}
|
||||
|
||||
#! A world with no entities.
|
||||
pub def world::new(): world {
|
||||
var made := world{
|
||||
records = vector::<record>::new(),
|
||||
free = absent,
|
||||
infos = vector::<*component_info>::new(),
|
||||
by_key = idmap::new(),
|
||||
tables = vector::<table>::new(),
|
||||
by_hash = idmap::new(),
|
||||
bundles = idmap::new(),
|
||||
queries = vector::<box<query_state>>::new(),
|
||||
cached = idmap::new(),
|
||||
pending = commands::new(),
|
||||
resources = vector::<resource>::new(),
|
||||
by_resource = idmap::new(),
|
||||
crew = workers::new(),
|
||||
};
|
||||
val none := span::<u32>::empty();
|
||||
_ = made.make_table(none, hash_ids(none));
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Closes every component and resource it holds.
|
||||
pub def world::close(&mut this): void {
|
||||
this.crew.close();
|
||||
this.pending.close();
|
||||
for i in 0..this.resources.length {
|
||||
val held := &mut this.resources[i];
|
||||
if held.data != null {
|
||||
if held.info[0].closes {
|
||||
held.info[0].dispose(held.data);
|
||||
}
|
||||
raw_release(held.data);
|
||||
held.data = null;
|
||||
}
|
||||
}
|
||||
this.resources.close();
|
||||
this.by_resource.close();
|
||||
this.tables.close();
|
||||
this.by_hash.close();
|
||||
this.bundles.close();
|
||||
this.queries.close();
|
||||
this.cached.close();
|
||||
this.infos.close();
|
||||
this.by_key.close();
|
||||
this.records.close();
|
||||
}
|
||||
|
||||
#! How many entities are alive.
|
||||
pub val world::count: u64 {
|
||||
get => this.living;
|
||||
}
|
||||
|
||||
#! How many tables it keeps entities in: one for each set of components an
|
||||
#! entity has had.
|
||||
pub val world::archetypes: u64 {
|
||||
get => this.tables.length;
|
||||
}
|
||||
|
||||
# Entities.
|
||||
|
||||
#! Spawns an entity with no components.
|
||||
pub def world::spawn(&mut this): entity {
|
||||
val e := this.new_entity();
|
||||
if this.deferring > 0 {
|
||||
this.defer(op::place, e, null);
|
||||
} else {
|
||||
this.place(e);
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
#! Spawns an entity with components, which it moves into their table at once,
|
||||
#! rather than through one table for each, as giving them one at a time would.
|
||||
pub def world::spawn_with<Ts...>(&mut this, components: Ts...): entity {
|
||||
val e := this.new_entity();
|
||||
if this.deferring > 0 {
|
||||
this.defer(op::place, e, null);
|
||||
for const c in components {
|
||||
this.defer_put(e, info_of_value(&c), &mut c as *mut u8);
|
||||
emptied(&mut c);
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
# The table of a set of types is kept by the sum of their keys' hashes, which
|
||||
# their order doesn't change, so it's found once.
|
||||
var bundle := 0u;
|
||||
for const c in components {
|
||||
bundle += mixed(info_of_value(&c)[0].key);
|
||||
}
|
||||
var to := this.bundles.get(bundle);
|
||||
if to == absent {
|
||||
var ids: u32[32];
|
||||
var count := 0u;
|
||||
for const c in components {
|
||||
if count == 32 {
|
||||
fault("`spawn_with` takes at most 32 components.");
|
||||
}
|
||||
ids[count] = this.id_of(info_of_value(&c));
|
||||
count++;
|
||||
}
|
||||
to = this.table_of_unsorted(&mut ids, count);
|
||||
this.bundles.set(bundle, to);
|
||||
}
|
||||
val row := this.tables[to as u64].push(e);
|
||||
val r := &mut this.records[e.index as u64];
|
||||
r.table = to;
|
||||
r.row = row as u32;
|
||||
|
||||
val now := this.stamp();
|
||||
val t := &mut this.tables[to as u64];
|
||||
for const c in components {
|
||||
val slot := t.slot_of(this.find_id(info_of_value(&c)));
|
||||
if slot != tagged {
|
||||
place(t.at(slot, row), &mut c);
|
||||
t.columns[slot as u64].changed = now;
|
||||
}
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
# The table of a set of components, put in order first. `spawn_with` gives it
|
||||
# their ids rather than its pack, which, passed on, would move its values here.
|
||||
def world::table_of_unsorted(&mut this, ids: &mut u32[32], count: u64): u32 {
|
||||
for i in 1..count {
|
||||
var j := i;
|
||||
while j > 0 && ids[j - 1] > ids[j] {
|
||||
val swap := ids[j];
|
||||
ids[j] = ids[j - 1];
|
||||
ids[j - 1] = swap;
|
||||
j--;
|
||||
}
|
||||
if j > 0 && ids[j - 1] == ids[j] {
|
||||
fault($"`spawn_with` was given two of `{this.infos[ids[j] as u64][0].path}`.");
|
||||
}
|
||||
}
|
||||
val set: span<u32> = ids[0:count];
|
||||
return this.table_of(set);
|
||||
}
|
||||
|
||||
#! Despawns an entity, closing its components.
|
||||
#! @returns Whether it was alive.
|
||||
pub def world::despawn(&mut this, e: entity): bool {
|
||||
return false if !this.alive(e);
|
||||
if this.deferring > 0 {
|
||||
this.defer(op::despawn, e, null);
|
||||
} else {
|
||||
this.despawn_now(e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Whether an entity is alive: spawned by this world, and not despawned.
|
||||
pub def world::alive(&this, e: entity): bool {
|
||||
val index := e.index as u64;
|
||||
return index < this.records.length && this.records[index].generation == e.generation
|
||||
&& this.records[index].table != absent;
|
||||
}
|
||||
|
||||
# An entity's index and generation, in no table yet.
|
||||
def world::new_entity(&mut this): entity {
|
||||
if this.parallel {
|
||||
fault("A function `par_each` calls can't spawn entities: spawn them after.");
|
||||
}
|
||||
if this.sharing {
|
||||
this.refuse_while_shared("spawn entities");
|
||||
}
|
||||
this.living++;
|
||||
if this.free != absent {
|
||||
val index := this.free;
|
||||
val r := &mut this.records[index as u64];
|
||||
this.free = r.row;
|
||||
r.table = pending;
|
||||
r.row = 0;
|
||||
return entity::of(index, r.generation);
|
||||
}
|
||||
val index := this.records.length as u32;
|
||||
this.records.append(record{ table = pending, row = 0, generation = 1 });
|
||||
return entity::of(index, 1);
|
||||
}
|
||||
|
||||
# Puts an entity in the table of no components.
|
||||
def world::place(&mut this, e: entity): void {
|
||||
val row := this.tables[0].push(e);
|
||||
val r := &mut this.records[e.index as u64];
|
||||
r.table = 0;
|
||||
r.row = row as u32;
|
||||
}
|
||||
|
||||
def world::despawn_now(&mut this, e: entity): void {
|
||||
val r: record = this.records[e.index as u64];
|
||||
if r.table != pending {
|
||||
val t := &mut this.tables[r.table as u64];
|
||||
t.close_row(r.row as u64);
|
||||
val moved := t.take_out(r.row as u64);
|
||||
if moved != entity::none {
|
||||
this.records[moved.index as u64].row = r.row;
|
||||
}
|
||||
}
|
||||
val freed := &mut this.records[e.index as u64];
|
||||
freed.table = absent;
|
||||
freed.generation = freed.generation == 0xFFFFFFFF ? 1 : freed.generation + 1;
|
||||
freed.row = this.free;
|
||||
this.free = e.index;
|
||||
this.living--;
|
||||
}
|
||||
|
||||
# Components.
|
||||
|
||||
#! Gives an entity a component, or replaces the one it has. Where a query is
|
||||
#! passing over the world, a component the entity lacks is given as the pass
|
||||
#! ends.
|
||||
pub def world::set<T>(&mut this, e: entity, value: T): void {
|
||||
if !this.alive(e) {
|
||||
fault($"`set` was given {e.show()}, which isn't alive.");
|
||||
}
|
||||
val info := info_of::<T>();
|
||||
val r: record = this.records[e.index as u64];
|
||||
val id := this.find_id(info);
|
||||
if id != absent && r.table != pending {
|
||||
val t := &mut this.tables[r.table as u64];
|
||||
val slot := t.slot_of(id);
|
||||
if slot != absent {
|
||||
# It has one, which the value replaces where it is, closing it.
|
||||
if slot != tagged {
|
||||
through(t.at(slot, r.row as u64) as *mut T) = move(value);
|
||||
t.columns[slot as u64].changed = this.stamp();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if this.deferring > 0 {
|
||||
this.defer_put(e, info, &mut value as *mut u8);
|
||||
emptied(&mut value);
|
||||
return;
|
||||
}
|
||||
if r.table == pending {
|
||||
this.place(e);
|
||||
}
|
||||
val at := this.add_now(e, this.id_of(info));
|
||||
if at != null {
|
||||
place(at, &mut value);
|
||||
}
|
||||
}
|
||||
|
||||
#! Gives an entity a component's zero value where it lacks one, as a tag is
|
||||
#! given.
|
||||
pub def world::add<T>(&mut this, e: entity): void where T: zeroable {
|
||||
return if this.has::<T>(e);
|
||||
var zero: T;
|
||||
this.set(e, move(zero));
|
||||
}
|
||||
|
||||
#! Takes a component from an entity, closing it.
|
||||
#! @returns Whether the entity had it.
|
||||
pub def world::remove<T>(&mut this, e: entity): bool {
|
||||
val id := this.find_id(info_of::<T>());
|
||||
return false if !this.has_id(e, id);
|
||||
if this.deferring > 0 {
|
||||
this.defer(op::remove, e, info_of::<T>());
|
||||
} else {
|
||||
this.remove_now(e, id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Whether an entity has a component.
|
||||
pub def world::has<T>(&this, e: entity): bool {
|
||||
return this.has_id(e, this.find_id(info_of::<T>()));
|
||||
}
|
||||
|
||||
#! An entity's component, where it has one. A tag has nothing to lend, which
|
||||
#! `has` asks of instead.
|
||||
#! @remarks The reference lasts until the entity next moves, as it gains or
|
||||
#! loses a component, or another in its table is despawned.
|
||||
pub def world::get<T>(&mut this, e: entity): maybe<&mut T> {
|
||||
val at := this.value_of(e, this.find_id(info_of::<T>()));
|
||||
return nothing{} if at == null;
|
||||
return maybe::<&mut T>{ some = through(at as *mut T) };
|
||||
}
|
||||
|
||||
#! An entity's component, where it has one, to read.
|
||||
pub def world::get<T>(&this, e: entity): maybe<&T> {
|
||||
val at := this.value_of(e, this.find_id(info_of::<T>()));
|
||||
return nothing{} if at == null;
|
||||
return maybe::<&T>{ some = through(at as *T) };
|
||||
}
|
||||
|
||||
#! The names of an entity's components, in the order its table holds them, as
|
||||
#! `game::position, game::velocity`.
|
||||
pub def world::describe(&this, e: entity): string {
|
||||
var text := string::from("", nothing{});
|
||||
return text if !this.alive(e);
|
||||
val r: record = this.records[e.index as u64];
|
||||
return text if r.table == pending;
|
||||
val t := &this.tables[r.table as u64];
|
||||
for i in 0..t.ids.length {
|
||||
if i > 0 {
|
||||
text.append(", ");
|
||||
}
|
||||
text.append(this.infos[t.ids[i] as u64][0].path);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
def world::has_id(&this, e: entity, id: u32): bool {
|
||||
return false if id == absent || !this.alive(e);
|
||||
val r: record = this.records[e.index as u64];
|
||||
return r.table != pending && this.tables[r.table as u64].has(id);
|
||||
}
|
||||
|
||||
# Where an entity's value of a component is, or `null` where it has none, or
|
||||
# it's a tag.
|
||||
def world::value_of(&this, e: entity, id: u32): *mut u8 {
|
||||
return null if id == absent || !this.alive(e);
|
||||
val r: record = this.records[e.index as u64];
|
||||
return null if r.table == pending;
|
||||
val t := &this.tables[r.table as u64];
|
||||
val slot := t.slot_of(id);
|
||||
return null if slot >= tagged;
|
||||
return t.at(slot, r.row as u64);
|
||||
}
|
||||
|
||||
# Gives a living entity a component, or replaces the one it has, moving the
|
||||
# value's bytes in, which the caller lets go of.
|
||||
def world::set_bytes(&mut this, e: entity, info: *component_info, from: *mut u8): void {
|
||||
val id := this.id_of(info);
|
||||
val r: record = this.records[e.index as u64];
|
||||
if r.table != pending {
|
||||
val t := &mut this.tables[r.table as u64];
|
||||
val slot := t.slot_of(id);
|
||||
if slot != absent {
|
||||
if slot != tagged {
|
||||
val at := t.at(slot, r.row as u64);
|
||||
if info[0].closes {
|
||||
info[0].dispose(at);
|
||||
}
|
||||
memcpy(at, from, info[0].size);
|
||||
t.columns[slot as u64].changed = this.stamp();
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
this.place(e);
|
||||
}
|
||||
val at := this.add_now(e, id);
|
||||
if at != null {
|
||||
memcpy(at, from, info[0].size);
|
||||
}
|
||||
}
|
||||
|
||||
# Gives a living entity a component it lacks, moving it to the table having
|
||||
# it too, and gives where the value goes, which the caller writes, or `null`
|
||||
# for a tag.
|
||||
def world::add_now(&mut this, e: entity, id: u32): *mut u8 {
|
||||
val r: record = this.records[e.index as u64];
|
||||
val to := this.table_with(r.table, id);
|
||||
val row := this.move_row(e, r.table, r.row as u64, to);
|
||||
val t := &mut this.tables[to as u64];
|
||||
val slot := t.slot_of(id);
|
||||
return null if slot == tagged;
|
||||
t.columns[slot as u64].changed = this.stamp();
|
||||
return t.at(slot, row);
|
||||
}
|
||||
|
||||
# Takes a component a living entity has, closing it.
|
||||
def world::remove_now(&mut this, e: entity, id: u32): void {
|
||||
val r: record = this.records[e.index as u64];
|
||||
val t := &mut this.tables[r.table as u64];
|
||||
val slot := t.slot_of(id);
|
||||
return if slot == absent;
|
||||
if slot != tagged {
|
||||
val c := &t.columns[slot as u64];
|
||||
if c.info[0].closes {
|
||||
c.info[0].dispose(c.data + r.row as u64 * c.size);
|
||||
}
|
||||
}
|
||||
val to := this.table_without(r.table, id);
|
||||
_ = this.move_row(e, r.table, r.row as u64, to);
|
||||
}
|
||||
|
||||
# Moves an entity's row to another table, with the values the two tables share,
|
||||
# and gives its row there. What only the first has was closed already, and what
|
||||
# only the second has, the caller writes.
|
||||
def world::move_row(&mut this, e: entity, from: u32, row: u64, to: u32): u64 {
|
||||
val made := this.tables[to as u64].push(e);
|
||||
val source := &mut this.tables[from as u64];
|
||||
val target := &mut this.tables[to as u64];
|
||||
for i in 0..source.columns.length {
|
||||
val c := &source.columns[i];
|
||||
val slot := target.slot_of(c.id);
|
||||
if slot != absent && slot != tagged {
|
||||
memcpy(target.at(slot, made), c.data + row * c.size, c.size);
|
||||
}
|
||||
}
|
||||
val moved := source.take_out(row);
|
||||
if moved != entity::none {
|
||||
this.records[moved.index as u64].row = row as u32;
|
||||
}
|
||||
val r := &mut this.records[e.index as u64];
|
||||
r.table = to;
|
||||
r.row = made as u32;
|
||||
return made;
|
||||
}
|
||||
|
||||
# The tick a change is stamped with: a new one outside a pass, so a query that
|
||||
# ran before it sees it; within one, the pass's own, which every query that ran
|
||||
# before the pass is behind.
|
||||
def world::stamp(&mut this): u64 {
|
||||
if this.deferring == 0 {
|
||||
return this.next_tick();
|
||||
}
|
||||
return this.tick.load(order::relaxed);
|
||||
}
|
||||
|
||||
# Moves the tick on, and gives it: by one add of the threads sharing the
|
||||
# world, where they do, and as a plain count otherwise.
|
||||
def world::next_tick(&mut this): u64 {
|
||||
if this.sharing {
|
||||
return this.tick.fetch_add(1, order::relaxed) + 1;
|
||||
}
|
||||
val next := this.tick.load(order::relaxed) + 1;
|
||||
this.tick.store(next, order::relaxed);
|
||||
return next;
|
||||
}
|
||||
|
||||
# Types of components.
|
||||
|
||||
# A type's id, given it where it's new.
|
||||
def world::id_of(&mut this, info: *component_info): u32 {
|
||||
val found := this.by_key.get(info[0].key);
|
||||
if found != absent {
|
||||
val known := this.infos[found as u64];
|
||||
if known != info && (known[0].path != info[0].path || known[0].name != info[0].name) {
|
||||
fault($"`{known[0].path}` and `{info[0].path}` hash alike, so a world can't tell them apart.");
|
||||
}
|
||||
return found;
|
||||
}
|
||||
if this.parallel {
|
||||
fault($"`{info[0].path}` was first used within `par_each`: use it before.");
|
||||
}
|
||||
if this.sharing {
|
||||
fault($"`{info[0].path}` was first used while threads share the world: use it before.");
|
||||
}
|
||||
val id := this.infos.length as u32;
|
||||
this.infos.append(info);
|
||||
this.by_key.set(info[0].key, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
# A type's id, or `absent` where the world hasn't met it.
|
||||
def world::find_id(&this, info: *component_info): u32 {
|
||||
return this.by_key.get(info[0].key);
|
||||
}
|
||||
|
||||
# Tables.
|
||||
|
||||
def hash_ids(ids: span<u32>): u64 {
|
||||
var h := fnv_basis;
|
||||
for i in 0..ids.length {
|
||||
h = mixed(h ^ ids[i] as u64);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
# The table of a set of components, in order, made where it's new.
|
||||
def world::table_of(&mut this, ids: span<u32>): u32 {
|
||||
val h := hash_ids(ids);
|
||||
var at := this.by_hash.get(h);
|
||||
while at != absent {
|
||||
if this.tables[at as u64].ids.view() == ids {
|
||||
return at;
|
||||
}
|
||||
at = this.tables[at as u64].next;
|
||||
}
|
||||
return this.make_table(ids, h);
|
||||
}
|
||||
|
||||
def world::make_table(&mut this, ids: span<u32>, h: u64): u32 {
|
||||
var made := table{
|
||||
ids = vector::<u32>::new(),
|
||||
slots = vector::<u32>::new(),
|
||||
columns = vector::<column>::new(),
|
||||
hash = h,
|
||||
next = this.by_hash.get(h),
|
||||
edges = idmap::new(),
|
||||
};
|
||||
for i in 0..ids.length {
|
||||
val info := this.infos[ids[i] as u64];
|
||||
made.ids.append(ids[i]);
|
||||
if info[0].size == 0 {
|
||||
made.slots.append(tagged);
|
||||
} else {
|
||||
made.slots.append(made.columns.length as u32);
|
||||
made.columns.append(column{ size = info[0].size, id = ids[i], info = info });
|
||||
}
|
||||
}
|
||||
val index := this.tables.length as u32;
|
||||
this.tables.append(move(made));
|
||||
this.by_hash.set(h, index);
|
||||
return index;
|
||||
}
|
||||
|
||||
# The table an entity of one goes to as it gains a component.
|
||||
def world::table_with(&mut this, from: u32, id: u32): u32 {
|
||||
val key := (id as u64 << 1) + 1;
|
||||
val known := this.tables[from as u64].edges.get(key);
|
||||
return known if known != absent;
|
||||
var ids := vector::<u32>::new();
|
||||
val have := &this.tables[from as u64].ids;
|
||||
var placed := false;
|
||||
for i in 0..have.length {
|
||||
if !placed && id < have[i] {
|
||||
ids.append(id);
|
||||
placed = true;
|
||||
}
|
||||
ids.append(have[i]);
|
||||
}
|
||||
if !placed {
|
||||
ids.append(id);
|
||||
}
|
||||
val to := this.table_of(ids.view());
|
||||
this.tables[from as u64].edges.set(key, to);
|
||||
this.tables[to as u64].edges.set(key + 1, from);
|
||||
return to;
|
||||
}
|
||||
|
||||
# The table an entity of one goes to as it loses a component.
|
||||
def world::table_without(&mut this, from: u32, id: u32): u32 {
|
||||
val key := (id as u64 << 1) + 2;
|
||||
val known := this.tables[from as u64].edges.get(key);
|
||||
return known if known != absent;
|
||||
var ids := vector::<u32>::new();
|
||||
val have := &this.tables[from as u64].ids;
|
||||
for i in 0..have.length {
|
||||
if have[i] != id {
|
||||
ids.append(have[i]);
|
||||
}
|
||||
}
|
||||
val to := this.table_of(ids.view());
|
||||
this.tables[from as u64].edges.set(key, to);
|
||||
this.tables[to as u64].edges.set(key - 1, from);
|
||||
return to;
|
||||
}
|
||||
|
||||
# Deferring.
|
||||
|
||||
#! Makes the changes commands hold, in order, leaving them empty. Those of an
|
||||
#! entity no longer alive are dropped, their values closed.
|
||||
pub def world::apply(&mut this, changes: &mut commands): void {
|
||||
this.refuse_while_shared("make the changes commands hold");
|
||||
if this.deferring > 0 {
|
||||
fault("`apply` can't run while a query passes over the world: run it after.");
|
||||
}
|
||||
for i in 0..changes.list.length {
|
||||
val c: command = changes.list[i];
|
||||
val index := c.who.index as u64;
|
||||
val known := index < this.records.length && this.records[index].generation == c.who.generation;
|
||||
match c.what {
|
||||
op::place => {
|
||||
if known && this.records[index].table == pending {
|
||||
this.place(c.who);
|
||||
}
|
||||
}
|
||||
op::set => {
|
||||
if this.alive(c.who) {
|
||||
this.set_bytes(c.who, c.info, changes.data + c.at);
|
||||
} else if c.info[0].closes {
|
||||
c.info[0].dispose(changes.data + c.at);
|
||||
}
|
||||
}
|
||||
op::remove => {
|
||||
val id := this.find_id(c.info);
|
||||
if this.has_id(c.who, id) {
|
||||
this.remove_now(c.who, id);
|
||||
}
|
||||
}
|
||||
op::despawn => {
|
||||
if this.alive(c.who) {
|
||||
this.despawn_now(c.who);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
changes.forget();
|
||||
}
|
||||
|
||||
# Keeps a change, under the guard where threads may keep them at once.
|
||||
def world::defer(&mut this, what: op, e: entity, info: *component_info): void {
|
||||
this.lock();
|
||||
this.pending.list.append(command{ what = what, who = e, info = info });
|
||||
this.unlock();
|
||||
}
|
||||
|
||||
# Keeps a component given, its bytes copied, which the caller lets go of.
|
||||
def world::defer_put(&mut this, e: entity, info: *component_info, from: *mut u8): void {
|
||||
this.lock();
|
||||
this.pending.put(e, info, from);
|
||||
this.unlock();
|
||||
}
|
||||
|
||||
def world::lock(&mut this): void {
|
||||
return if !this.parallel && !this.sharing;
|
||||
while this.guard.exchange(1, order::acquire) != 0 {
|
||||
system::yield_now();
|
||||
}
|
||||
}
|
||||
|
||||
def world::unlock(&mut this): void {
|
||||
if this.parallel || this.sharing {
|
||||
this.guard.store(0, order::release);
|
||||
}
|
||||
}
|
||||
|
||||
# Makes what the passes deferred.
|
||||
def world::flush(&mut this): void {
|
||||
var queued := move(this.pending);
|
||||
this.apply(&mut queued);
|
||||
this.pending = move(queued);
|
||||
}
|
||||
|
||||
# Resources.
|
||||
|
||||
#! Gives the world a resource: the one value of its type the world holds, apart
|
||||
#! from any entity, as a clock or the settings of a game. One the world holds
|
||||
#! already it replaces.
|
||||
pub def world::set_resource<T>(&mut this, value: T): void {
|
||||
this.refuse_while_shared("be given resources");
|
||||
val info := info_of::<T>();
|
||||
var found := this.by_resource.get(info[0].key);
|
||||
if found == absent {
|
||||
found = this.resources.length as u32;
|
||||
this.resources.append(resource{ info = info });
|
||||
this.by_resource.set(info[0].key, found);
|
||||
}
|
||||
val held := &mut this.resources[found as u64];
|
||||
if held.data == null {
|
||||
held.data = raw_allocate(size_of::<T>() == 0 ? 1 : size_of::<T>());
|
||||
} else if info[0].closes {
|
||||
info[0].dispose(held.data);
|
||||
}
|
||||
memcpy(held.data, &mut value as *mut u8, size_of::<T>());
|
||||
emptied(&mut value);
|
||||
}
|
||||
|
||||
#! The world's resource of a type, where it holds one.
|
||||
pub def world::resource<T>(&mut this): maybe<&mut T> {
|
||||
val found := this.by_resource.get(info_of::<T>()[0].key);
|
||||
return nothing{} if found == absent || this.resources[found as u64].data == null;
|
||||
return maybe::<&mut T>{ some = through(this.resources[found as u64].data as *mut T) };
|
||||
}
|
||||
|
||||
#! Takes the world's resource of a type, closing it.
|
||||
#! @returns Whether it held one.
|
||||
pub def world::remove_resource<T>(&mut this): bool {
|
||||
this.refuse_while_shared("have resources taken");
|
||||
val found := this.by_resource.get(info_of::<T>()[0].key);
|
||||
return false if found == absent || this.resources[found as u64].data == null;
|
||||
val held := &mut this.resources[found as u64];
|
||||
if held.info[0].closes {
|
||||
held.info[0].dispose(held.data);
|
||||
}
|
||||
raw_release(held.data);
|
||||
held.data = null;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,689 @@
|
||||
#! 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, and entities written by a numbering.
|
||||
|
||||
import std::json;
|
||||
import std::serial;
|
||||
import std::testing;
|
||||
import std::thread;
|
||||
import 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.
|
||||
w.par_each(def(e: entity, h: &health) {
|
||||
if h.points % 4 == 0 {
|
||||
_ = w.despawn(e);
|
||||
}
|
||||
});
|
||||
t.expects(w.count == count - count / 4);
|
||||
}
|
||||
|
||||
# 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);
|
||||
}
|
||||
|
||||
# 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.view().find("watch: ").is_some && timings.view().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}".view());
|
||||
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.view() == naming(b.bits, ",\"gap\":2}").view());
|
||||
t.expects(json::to_text(&follows{ target = entity::none }).value.view() == "{\"target\":null,\"gap\":2}");
|
||||
t.expects(target_read(naming(b.bits, ",\"gap\":1}").view()) == 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.view() == "{\"target\":20,\"gap\":1.5}");
|
||||
t.expects(json::to_text(&follows{ target = w.spawn() }).value.view() == "{\"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);
|
||||
}
|
||||
|
||||
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,203 @@
|
||||
#! 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 `ecs.bench`, as an executable: the VM's times
|
||||
#! aren't the program's.
|
||||
|
||||
import std::io;
|
||||
import std::time;
|
||||
import 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);
|
||||
|
||||
println($"(sums {sum} {xs[n - 1].x}, {w.count} left)");
|
||||
}
|
||||
Reference in new issue
Block a user