ecs: move to github.com/hexops/mach-ecs

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
This commit is contained in:
Stephen Gutekanst 2023-04-28 15:50:38 -07:00
parent 1fbd36199a
commit aebfeb9b49
13 changed files with 0 additions and 1749 deletions

View file

@ -1,2 +0,0 @@
* text=auto eol=lf
upstream/** linguist-vendored

View file

@ -1 +0,0 @@
github: slimsag

View file

@ -1,5 +0,0 @@
Please send your change to [the main repository](https://github.com/hexops/mach/tree/main/libs/ecs) instead, sorry for the trouble!
This helps us avoid some complex merge conflicts we run into when changes are made to both repositories and history needs to be reconciled. Keeping PRs in just that repository enables us to use `git subtree` to trivially keep the two repositories in sync.
Once your PR is merged over there, it'll automatically sync to this repository.

18
libs/ecs/.gitignore vendored
View file

@ -1,18 +0,0 @@
# This file is for zig-specific build artifacts.
# If you have OS-specific or editor-specific files to ignore,
# such as *.swp or .DS_Store, put those in your global
# ~/.gitignore and put this in your ~/.gitconfig:
#
# [core]
# excludesfile = ~/.gitignore
#
# Cheers!
# -andrewrk
zig-cache/
zig-out/
/release/
/debug/
/build/
/build-*/
/docgen_tmp/

View file

@ -1,13 +0,0 @@
Copyright 2021, Hexops Contributors (given via the Git commit history).
All documentation, image, sound, font, and 2D/3D model files are CC-BY-4.0 licensed unless
otherwise noted. You may get a copy of this license at https://creativecommons.org/licenses/by/4.0
Files in a directory with a separate LICENSE file may contain files under different license terms,
described within that LICENSE file.
All other files are licensed under the Apache License, Version 2.0 (see LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
or the MIT license (see LICENSE-MIT or http://opensource.org/licenses/MIT), at your option.
All files in the project without exclusions may not be copied, modified, or distributed except
according to the terms above.

View file

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,25 +0,0 @@
Copyright (c) 2021 Hexops Contributors (given via the Git commit history).
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View file

@ -1,44 +0,0 @@
# mach/ecs, an Entity Component System for Zig <a href="https://hexops.com"><img align="right" alt="Hexops logo" src="https://raw.githubusercontent.com/hexops/media/master/readme.svg"></img></a>
`mach/ecs` is an Entity Component System for Zig built from first-principles.
## Experimental
This is an _experimental_ Mach library, according to our [stability guarantees](https://machengine.org/next/docs/libs/):
> Experimental libraries may have their APIs change without much notice, and you may have to look at recent changes in order to update your code.
[Why this library is not declared stable yet](https://machengine.org/next/docs/libs/experimental/#ecs)
## Design principles:
* Initially a 100% clean-room implementation, working from first-principles. Later informed by research into how other ECS work, with advice from e.g. Bevy and Flecs authors at different points (thank you!)
* Solve the problems ECS solves, in a way that is natural to Zig and leverages Zig comptime.
* Fast. Optimal for CPU caches, multi-threaded, leverage comptime as much as is reasonable.
* Simple. Small API footprint, should be natural and fun - not like you're writing boilerplate.
* Enable other libraries to provide tracing, editors, visualizers, profilers, etc.
## ⚠️ in-development ⚠️
Under heavy development, not ready for use!
As development continues, we're publishing a blog series ["Let's build an Entity Component System from scatch"](https://devlog.hexops.com/categories/build-an-ecs/).
Join us in developing it, give us advice, etc. [on Discord](https://discord.gg/XNG3NZgCqp) or [follow updates on Twitter](https://twitter.com/machengine).
## Known issues
There are plenty of known issues, and things that just aren't implemented yet. And certainly many unknown issues, too.
* Missing multi-threading!
* Currently only handles entity management, no world management or scheduling. No global data, etc.
* Lack of API documentation (see "example" test)
* Missing hooks that would enable visualizing memory usage, # of entities, components, etc. and otherwise enable integration of editors/visualizers/profilers/etc.
* We have dense and sparse data, but no shared data yet.
* If many entities are deleted, iteration becomes slower due to needing to skip over entities in the free_slots set, we should add a .compact() method that allows for remediating this.
* If *tons* of entities are deleted, even with .compact(), memory would not be free'd / returned to the OS by the underlying components arrays. We could add a .compactAndFree() method to correct this.
* It would be nicer if there were configuration options for performing .compactAndFree() automatically, e.g. if the number of free entity slots is particularly high or something.
* Currently we do not expose an API for pre-allocating entities (i.e. allocating capacity up front) but that's very important for perf and memory usage in the real world.
* When entity is deleted, maybe via systems / an event/callback, need a way to be notified of destruction. Same with updated maybe.
See also the numerous TODOs in main.zig.

View file

@ -1,37 +0,0 @@
const std = @import("std");
var _module: ?*std.build.Module = null;
pub fn module(b: *std.Build) *std.build.Module {
if (_module) |m| return m;
_module = b.createModule(.{
.source_file = .{ .path = sdkPath("/src/main.zig") },
});
return _module.?;
}
pub fn build(b: *std.Build) void {
const optimize = b.standardOptimizeOption(.{});
const target = b.standardTargetOptions(.{});
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&testStep(b, optimize, target).step);
}
pub fn testStep(b: *std.Build, optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget) *std.build.RunStep {
const main_tests = b.addTest(.{
.name = "ecs-tests",
.root_source_file = .{ .path = sdkPath("/src/main.zig") },
.target = target,
.optimize = optimize,
});
b.installArtifact(main_tests);
return b.addRunArtifact(main_tests);
}
fn sdkPath(comptime suffix: []const u8) []const u8 {
if (suffix[0] != '/') @compileError("suffix must be an absolute path");
return comptime blk: {
const root_dir = std.fs.path.dirname(@src().file) orelse ".";
break :blk root_dir ++ suffix;
};
}

View file

@ -1,859 +0,0 @@
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const testing = std.testing;
const builtin = @import("builtin");
const assert = std.debug.assert;
const query_mod = @import("query.zig");
const is_debug = builtin.mode == .Debug;
/// An entity ID uniquely identifies an entity globally within an Entities set.
pub const EntityID = u64;
const TypeId = enum(usize) { _ };
// typeId implementation by Felix "xq" Queißner
fn typeId(comptime T: type) TypeId {
_ = T;
return @intToEnum(TypeId, @ptrToInt(&struct {
var x: u8 = 0;
}.x));
}
const Column = struct {
name: []const u8,
type_id: TypeId,
size: u32,
alignment: u16,
values: []u8,
};
fn byTypeId(context: void, lhs: Column, rhs: Column) bool {
_ = context;
return @enumToInt(lhs.type_id) < @enumToInt(rhs.type_id);
}
/// Represents a single archetype, that is, entities which have the same exact set of component
/// types. When a component is added or removed from an entity, it's archetype changes.
///
/// Database equivalent: a table where rows are entities and columns are components (dense storage).
pub const ArchetypeStorage = struct {
/// The hash of every component name in this archetype, i.e. the name of this archetype.
hash: u64,
/// The length of the table (used number of rows.)
len: u32,
/// The capacity of the table (allocated number of rows.)
capacity: u32,
/// Describes the columns in this table. Each column stores its row values.
columns: []Column,
/// Calculates the storage.hash value. This is a hash of all the component names, and can
/// effectively be used to uniquely identify this table within the database.
pub fn calculateHash(storage: *ArchetypeStorage) void {
storage.hash = 0;
for (storage.columns) |column| {
storage.hash ^= std.hash_map.hashString(column.name);
}
}
pub fn deinit(storage: *ArchetypeStorage, gpa: Allocator) void {
if (storage.capacity > 0) {
for (storage.columns) |column| gpa.free(column.values);
}
gpa.free(storage.columns);
}
fn debugValidateRow(storage: *ArchetypeStorage, gpa: Allocator, row: anytype) void {
inline for (std.meta.fields(@TypeOf(row)), 0..) |field, index| {
const column = storage.columns[index];
if (typeId(field.type) != column.type_id) {
const msg = std.mem.concat(gpa, u8, &.{
"unexpected type: ",
@typeName(field.type),
" expected: ",
column.name,
}) catch |err| @panic(@errorName(err));
@panic(msg);
}
}
}
/// appends a new row to this table, with all undefined values.
pub fn appendUndefined(storage: *ArchetypeStorage, gpa: Allocator) !u32 {
try storage.ensureUnusedCapacity(gpa, 1);
assert(storage.len < storage.capacity);
const row_index = storage.len;
storage.len += 1;
return row_index;
}
pub fn append(storage: *ArchetypeStorage, gpa: Allocator, row: anytype) !u32 {
if (is_debug) storage.debugValidateRow(gpa, row);
try storage.ensureUnusedCapacity(gpa, 1);
assert(storage.len < storage.capacity);
storage.len += 1;
storage.setRow(gpa, storage.len - 1, row);
return storage.len;
}
pub fn undoAppend(storage: *ArchetypeStorage) void {
storage.len -= 1;
}
/// Ensures there is enough unused capacity to store `num_rows`.
pub fn ensureUnusedCapacity(storage: *ArchetypeStorage, gpa: Allocator, num_rows: usize) !void {
return storage.ensureTotalCapacity(gpa, storage.len + num_rows);
}
/// Ensures the total capacity is enough to store `new_capacity` rows total.
pub fn ensureTotalCapacity(storage: *ArchetypeStorage, gpa: Allocator, new_capacity: usize) !void {
var better_capacity = storage.capacity;
if (better_capacity >= new_capacity) return;
while (true) {
better_capacity +|= better_capacity / 2 + 8;
if (better_capacity >= new_capacity) break;
}
return storage.setCapacity(gpa, better_capacity);
}
/// Sets the capacity to exactly `new_capacity` rows total
///
/// Asserts `new_capacity >= storage.len`, if you want to shrink capacity then change the len
/// yourself first.
pub fn setCapacity(storage: *ArchetypeStorage, gpa: Allocator, new_capacity: usize) !void {
assert(new_capacity >= storage.len);
// TODO: ensure columns are sorted by type_id
for (storage.columns) |*column| {
const old_values = column.values;
const new_values = try gpa.alloc(u8, new_capacity * column.size);
if (storage.capacity > 0) {
mem.copy(u8, new_values[0..], old_values);
gpa.free(old_values);
}
column.values = new_values;
}
storage.capacity = @intCast(u32, new_capacity);
}
/// Sets the entire row's values in the table.
pub fn setRow(storage: *ArchetypeStorage, gpa: Allocator, row_index: u32, row: anytype) void {
if (is_debug) storage.debugValidateRow(gpa, row);
const fields = std.meta.fields(@TypeOf(row));
inline for (fields, 0..) |field, index| {
const ColumnType = field.type;
if (@sizeOf(ColumnType) == 0) continue;
var column = storage.columns[index];
const column_values = @ptrCast([*]ColumnType, @alignCast(@alignOf(ColumnType), column.values.ptr));
column_values[row_index] = @field(row, field.name);
}
}
/// Sets the value of the named components (columns) for the given row in the table.
pub fn set(storage: *ArchetypeStorage, gpa: Allocator, row_index: u32, name: []const u8, component: anytype) void {
assert(storage.len != 0 and storage.len >= row_index);
const ColumnType = @TypeOf(component);
if (@sizeOf(ColumnType) == 0) return;
const values = storage.getColumnValues(gpa, name, ColumnType) orelse @panic("no such component");
values[row_index] = component;
}
pub fn get(storage: *ArchetypeStorage, gpa: Allocator, row_index: u32, name: []const u8, comptime ColumnType: type) ?ColumnType {
if (@sizeOf(ColumnType) == 0) return {};
const values = storage.getColumnValues(gpa, name, ColumnType) orelse return null;
return values[row_index];
}
pub fn getRaw(storage: *ArchetypeStorage, row_index: u32, column: Column) []u8 {
const values = storage.getRawColumnValues(column.name) orelse @panic("getRaw(): no such component");
const start = column.size * row_index;
const end = start + column.size;
return values[start..end];
}
pub fn setRaw(storage: *ArchetypeStorage, row_index: u32, column: Column, component: []u8) !void {
const values = storage.getRawColumnValues(column.name) orelse @panic("setRaw(): no such component");
const start = column.size * row_index;
assert(component.len == column.size);
mem.copy(u8, values[start..], component);
}
/// Swap-removes the specified row with the last row in the table.
pub fn remove(storage: *ArchetypeStorage, row_index: u32) void {
if (storage.len > 1) {
for (storage.columns) |column| {
const dstStart = column.size * row_index;
const dst = column.values[dstStart .. dstStart + column.size];
const srcStart = column.size * (storage.len - 1);
const src = column.values[srcStart .. srcStart + column.size];
std.mem.copy(u8, dst, src);
}
}
storage.len -= 1;
}
/// Tells if this archetype has every one of the given components.
pub fn hasComponents(storage: *ArchetypeStorage, components: []const []const u8) bool {
for (components) |component_name| {
if (!storage.hasComponent(component_name)) return false;
}
return true;
}
/// Tells if this archetype has a component with the specified name.
pub fn hasComponent(storage: *ArchetypeStorage, component: []const u8) bool {
for (storage.columns) |column| {
if (std.mem.eql(u8, column.name, component)) return true;
}
return false;
}
pub fn getColumnValues(storage: *ArchetypeStorage, gpa: Allocator, name: []const u8, comptime ColumnType: type) ?[]ColumnType {
for (storage.columns) |*column| {
if (!std.mem.eql(u8, column.name, name)) continue;
if (is_debug) {
if (typeId(ColumnType) != column.type_id) {
const msg = std.mem.concat(gpa, u8, &.{
"unexpected type: ",
@typeName(ColumnType),
" expected: ",
column.name,
}) catch |err| @panic(@errorName(err));
@panic(msg);
}
}
var ptr = @ptrCast([*]ColumnType, @alignCast(@alignOf(ColumnType), column.values.ptr));
const column_values = ptr[0..storage.capacity];
return column_values;
}
return null;
}
pub fn getRawColumnValues(storage: *ArchetypeStorage, name: []const u8) ?[]u8 {
for (storage.columns) |column| {
if (!std.mem.eql(u8, column.name, name)) continue;
return column.values;
}
return null;
}
};
pub const void_archetype_hash = std.math.maxInt(u64);
/// A database of entities. For example, all player, monster, etc. entities in a game world.
///
/// ```
/// const world = Entities.init(allocator); // all entities in our world.
/// defer world.deinit();
///
/// const player1 = world.new(); // our first "player" entity
/// const player2 = world.new(); // our second "player" entity
/// ```
///
/// Entities are divided into archetypes for optimal, CPU cache efficient storage. For example, all
/// entities with two components `Location` and `Name` are stored in the same table dedicated to
/// densely storing `(Location, Name)` rows in contiguous memory. This not only ensures CPU cache
/// efficiency (leveraging data oriented design) which improves iteration speed over entities for
/// example, but makes queries like "find all entities with a Location component" ridiculously fast
/// because one need only find the tables which have a column for storing Location components and it
/// is then guaranteed every entity in the table has that component (entities do not need to be
/// checked one by one to determine if they have a Location component.)
///
/// Components can be added and removed to entities at runtime as you please:
///
/// ```
/// try player1.set("rotation", Rotation{ .degrees = 90 });
/// try player1.remove("rotation");
/// ```
///
/// When getting a component value, you must know it's type or undefined behavior will occur:
/// TODO: improve this!
///
/// ```
/// if (player1.get("rotation", Rotation)) |rotation| {
/// // player1 had a rotation component!
/// }
/// ```
///
/// When a component is added or removed from an entity, it's archetype is said to change. For
/// example player1 may have had the archetype `(Location, Name)` before, and after adding the
/// rotation component has the archetype `(Location, Name, Rotation)`. It will be automagically
/// "moved" from the table that stores entities with `(Location, Name)` components to the table that
/// stores `(Location, Name, Rotation)` components for you.
///
/// You can have 65,535 archetypes in total, and 4,294,967,295 entities total. Entities which are
/// deleted are merely marked as "unused" and recycled
///
/// Database equivalents:
/// * Entities is a database of tables, where each table represents a single archetype.
/// * ArchetypeStorage is a table, whose rows are entities and columns are components.
/// * EntityID is a mere 32-bit array index, pointing to a 16-bit archetype table index and 32-bit
/// row index, enabling entities to "move" from one archetype table to another seamlessly and
/// making lookup by entity ID a few cheap array indexing operations.
/// * ComponentStorage(T) is a column of data within a table for a single type of component `T`.
pub fn Entities(comptime all_components: anytype) type {
// TODO: validate all_components is a namespaced component set in the form we expect
return struct {
allocator: Allocator,
/// TODO!
counter: EntityID = 0,
/// A mapping of entity IDs (array indices) to where an entity's component values are actually
/// stored.
entities: std.AutoHashMapUnmanaged(EntityID, Pointer) = .{},
/// A mapping of archetype hash to their storage.
///
/// Database equivalent: table name -> tables representing entities.
archetypes: std.AutoArrayHashMapUnmanaged(u64, ArchetypeStorage) = .{},
const Self = @This();
/// Points to where an entity is stored, specifically in which archetype table and in which row
/// of that table. That is, the entity's component values are stored at:
///
/// ```
/// Entities.archetypes[ptr.archetype_index].rows[ptr.row_index]
/// ```
///
pub const Pointer = struct {
archetype_index: u16,
row_index: u32,
};
/// A complex query for entities matching a given criteria
pub const Query = query_mod.Query(all_components);
pub const QueryTag = query_mod.QueryTag;
pub fn init(allocator: Allocator) !Self {
var entities = Self{ .allocator = allocator };
const columns = try allocator.alloc(Column, 1);
columns[0] = .{
.name = "id",
.type_id = typeId(EntityID),
.size = @sizeOf(EntityID),
.alignment = @alignOf(EntityID),
.values = undefined,
};
try entities.archetypes.put(allocator, void_archetype_hash, ArchetypeStorage{
.len = 0,
.capacity = 0,
.columns = columns,
.hash = void_archetype_hash,
});
return entities;
}
pub fn deinit(entities: *Self) void {
entities.entities.deinit(entities.allocator);
var iter = entities.archetypes.iterator();
while (iter.next()) |entry| {
entry.value_ptr.deinit(entities.allocator);
}
entities.archetypes.deinit(entities.allocator);
}
/// Returns a new entity.
pub fn new(entities: *Self) !EntityID {
const new_id = entities.counter;
entities.counter += 1;
var void_archetype = entities.archetypes.getPtr(void_archetype_hash).?;
const new_row = try void_archetype.append(entities.allocator, .{ .id = new_id });
const void_pointer = Pointer{
.archetype_index = 0, // void archetype is guaranteed to be first index
.row_index = new_row,
};
entities.entities.put(entities.allocator, new_id, void_pointer) catch |err| {
void_archetype.undoAppend();
return err;
};
return new_id;
}
/// Removes an entity.
pub fn remove(entities: *Self, entity: EntityID) !void {
var archetype = entities.archetypeByID(entity);
const ptr = entities.entities.get(entity).?;
// A swap removal will be performed, update the entity stored in the last row of the
// archetype table to point to the row the entity we are removing is currently located.
if (archetype.len > 1) {
const last_row_entity_id = archetype.get(entities.allocator, archetype.len - 1, "id", EntityID).?;
try entities.entities.put(entities.allocator, last_row_entity_id, Pointer{
.archetype_index = ptr.archetype_index,
.row_index = ptr.row_index,
});
}
// Perform a swap removal to remove our entity from the archetype table.
archetype.remove(ptr.row_index);
_ = entities.entities.remove(entity);
}
/// Returns the archetype storage for the given entity.
pub inline fn archetypeByID(entities: *Self, entity: EntityID) *ArchetypeStorage {
const ptr = entities.entities.get(entity).?;
return &entities.archetypes.values()[ptr.archetype_index];
}
/// Sets the named component to the specified value for the given entity,
/// moving the entity from it's current archetype table to the new archetype
/// table if required.
pub fn setComponent(
entities: *Self,
entity: EntityID,
comptime namespace_name: std.meta.FieldEnum(@TypeOf(all_components)),
comptime component_name: std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(namespace_name)))),
component: @field(
@field(all_components, @tagName(namespace_name)),
@tagName(component_name),
),
) !void {
const name = @tagName(namespace_name) ++ "." ++ @tagName(component_name);
var archetype = entities.archetypeByID(entity);
// Determine the old hash for the archetype.
const old_hash = archetype.hash;
// Determine the new hash for the archetype + new component
var have_already = archetype.hasComponent(name);
var new_hash = if (have_already) old_hash else old_hash ^ std.hash_map.hashString(name);
// Find the archetype storage for this entity. Could be a new archetype storage table (if a
// new component was added), or the same archetype storage table (if just updating the
// value of a component.)
var archetype_entry = try entities.archetypes.getOrPut(entities.allocator, new_hash);
// getOrPut allocated, so the archetype we retrieved earlier may no longer be a valid
// pointer. Refresh it now:
archetype = entities.archetypeByID(entity);
if (!archetype_entry.found_existing) {
const columns = entities.allocator.alloc(Column, archetype.columns.len + 1) catch |err| {
// Note: this removal doesn't break index accesses performed by archetypeByID
// since our archetype is guaranteed to be the last index right now.
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
mem.copy(Column, columns, archetype.columns);
for (columns) |*column| {
column.values = undefined;
}
columns[columns.len - 1] = .{
.name = name,
.type_id = typeId(@TypeOf(component)),
.size = @sizeOf(@TypeOf(component)),
.alignment = if (@sizeOf(@TypeOf(component)) == 0) 1 else @alignOf(@TypeOf(component)),
.values = undefined,
};
std.sort.sort(Column, columns, {}, byTypeId);
archetype_entry.value_ptr.* = ArchetypeStorage{
.len = 0,
.capacity = 0,
.columns = columns,
.hash = undefined,
};
archetype_entry.value_ptr.calculateHash();
// TODO: because hashing approach is poor, and specifically because columns are sorted,
// new_hash can actually not equal the result of .calculateHash which means the archetypes
// hashmap entry is under the wrong key now!
const old_hash_2 = new_hash;
new_hash = archetype_entry.value_ptr.hash;
var new_entry = archetype_entry.value_ptr.*;
// We rely on entities.archetypes access by array index (archetypeByID); but since
// it is guaranteed the item we're replacing is the last item in the array it's fine.
_ = entities.archetypes.orderedRemove(old_hash_2);
archetype_entry = try entities.archetypes.getOrPut(entities.allocator, new_hash);
if (archetype_entry.found_existing) {
// oops! our bad hashing means we did extra work
new_entry.deinit(entities.allocator);
} else {
archetype_entry.value_ptr.* = new_entry;
}
}
// Either new storage (if the entity moved between storage tables due to having a new
// component) or the prior storage (if the entity already had the component and it's value
// is merely being updated.)
var current_archetype_storage = archetype_entry.value_ptr;
if (new_hash == old_hash) {
// Update the value of the existing component of the entity.
const ptr = entities.entities.get(entity).?;
current_archetype_storage.set(entities.allocator, ptr.row_index, name, component);
return;
}
// Copy to all component values for our entity from the old archetype storage (archetype)
// to the new one (current_archetype_storage).
const new_row = try current_archetype_storage.appendUndefined(entities.allocator);
const old_ptr = entities.entities.get(entity).?;
// Update the storage/columns for all of the existing components on the entity.
current_archetype_storage.set(entities.allocator, new_row, "id", entity);
for (archetype.columns) |column| {
if (std.mem.eql(u8, column.name, "id")) continue;
for (current_archetype_storage.columns) |corresponding| {
if (std.mem.eql(u8, column.name, corresponding.name)) {
const old_value_raw = archetype.getRaw(old_ptr.row_index, column);
current_archetype_storage.setRaw(new_row, corresponding, old_value_raw) catch |err| {
current_archetype_storage.undoAppend();
return err;
};
break;
}
}
}
// Update the storage/column for the new component.
current_archetype_storage.set(entities.allocator, new_row, name, component);
archetype.remove(old_ptr.row_index);
const swapped_entity_id = archetype.get(entities.allocator, old_ptr.row_index, "id", EntityID).?;
// TODO: try is wrong here and below?
// if we removed the last entry from archetype, then swapped_entity_id == entity
// so the second entities.put will clobber this one
try entities.entities.put(entities.allocator, swapped_entity_id, old_ptr);
try entities.entities.put(entities.allocator, entity, Pointer{
.archetype_index = @intCast(u16, archetype_entry.index),
.row_index = new_row,
});
return;
}
/// gets the named component of the given type (which must be correct, otherwise undefined
/// behavior will occur). Returns null if the component does not exist on the entity.
pub fn getComponent(
entities: *Self,
entity: EntityID,
comptime namespace_name: std.meta.FieldEnum(@TypeOf(all_components)),
comptime component_name: std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(namespace_name)))),
) ?@field(
@field(all_components, @tagName(namespace_name)),
@tagName(component_name),
) {
const Component = comptime @field(
@field(all_components, @tagName(namespace_name)),
@tagName(component_name),
);
const name = @tagName(namespace_name) ++ "." ++ @tagName(component_name);
var archetype = entities.archetypeByID(entity);
const ptr = entities.entities.get(entity).?;
return archetype.get(entities.allocator, ptr.row_index, name, Component);
}
/// Removes the named component from the entity, or noop if it doesn't have such a component.
pub fn removeComponent(
entities: *Self,
entity: EntityID,
comptime namespace_name: std.meta.FieldEnum(@TypeOf(all_components)),
comptime component_name: std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(namespace_name)))),
) !void {
const name = @tagName(namespace_name) ++ "." ++ @tagName(component_name);
var archetype = entities.archetypeByID(entity);
if (!archetype.hasComponent(name)) return;
// Determine the old hash for the archetype.
const old_hash = archetype.hash;
// Determine the new hash for the archetype with the component removed
var new_hash: u64 = 0;
for (archetype.columns) |column| {
if (!std.mem.eql(u8, column.name, name)) new_hash ^= std.hash_map.hashString(column.name);
}
assert(new_hash != old_hash);
// Find the archetype storage this entity will move to. Note that although an entity with
// (A, B, C) components implies archetypes ((A), (A, B), (A, B, C)) exist there is no
// guarantee that archetype (A, C) exists - and so removing a component sometimes does
// require creating a new archetype table!
var archetype_entry = try entities.archetypes.getOrPut(entities.allocator, new_hash);
// getOrPut allocated, so the archetype we retrieved earlier may no longer be a valid
// pointer. Refresh it now:
archetype = entities.archetypeByID(entity);
if (!archetype_entry.found_existing) {
const columns = entities.allocator.alloc(Column, archetype.columns.len - 1) catch |err| {
// Note: this removal doesn't break index accesses performed by archetypeByID
// since our archetype is guaranteed to be the last index right now.
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
var i: usize = 0;
for (archetype.columns) |old_column| {
if (std.mem.eql(u8, old_column.name, name)) continue;
columns[i] = old_column;
columns[i].values = undefined;
i += 1;
}
archetype_entry.value_ptr.* = ArchetypeStorage{
.len = 0,
.capacity = 0,
.columns = columns,
.hash = undefined,
};
const new_archetype = archetype_entry.value_ptr;
new_archetype.calculateHash();
}
var current_archetype_storage = archetype_entry.value_ptr;
// Copy to all component values for our entity from the old archetype storage (archetype)
// to the new one (current_archetype_storage).
const new_row = try current_archetype_storage.appendUndefined(entities.allocator);
const old_ptr = entities.entities.get(entity).?;
// Update the storage/columns for all of the existing components on the entity that exist in
// the new archetype table (i.e. excluding the component to remove.)
current_archetype_storage.set(entities.allocator, new_row, "id", entity);
for (current_archetype_storage.columns) |column| {
if (std.mem.eql(u8, column.name, "id")) continue;
for (archetype.columns) |corresponding| {
if (std.mem.eql(u8, column.name, corresponding.name)) {
const old_value_raw = archetype.getRaw(old_ptr.row_index, column);
current_archetype_storage.setRaw(new_row, column, old_value_raw) catch |err| {
current_archetype_storage.undoAppend();
return err;
};
break;
}
}
}
archetype.remove(old_ptr.row_index);
const swapped_entity_id = archetype.get(entities.allocator, old_ptr.row_index, "id", EntityID).?;
// TODO: try is wrong here and below?
// if we removed the last entry from archetype, then swapped_entity_id == entity
// so the second entities.put will clobber this one
try entities.entities.put(entities.allocator, swapped_entity_id, old_ptr);
try entities.entities.put(entities.allocator, entity, Pointer{
.archetype_index = @intCast(u16, archetype_entry.index),
.row_index = new_row,
});
}
// Queries for archetypes matching the given query.
pub fn query(
entities: *Self,
q: Query,
) ArchetypeIterator(all_components) {
return ArchetypeIterator(all_components).init(entities, q);
}
// TODO: iteration over all entities
// TODO: iteration over all entities with components (U, V, ...)
// TODO: iteration over all entities with type T
// TODO: iteration over all entities with type T and components (U, V, ...)
// TODO: "indexes" - a few ideas we could express:
//
// * Graph relations index: e.g. parent-child entity relations for a DOM / UI / scene graph.
// * Spatial index: "give me all entities within 5 units distance from (x, y, z)"
// * Generic index: "give me all entities where arbitraryFunction(e) returns true"
//
// TODO: ability to remove archetype entirely, deleting all entities in it
// TODO: ability to remove archetypes with no entities (garbage collection)
};
}
// TODO: move this type somewhere else
pub fn ArchetypeIterator(comptime all_components: anytype) type {
const EntitiesT = Entities(all_components);
return struct {
entities: *EntitiesT,
query: EntitiesT.Query,
index: usize,
const Self = @This();
pub fn init(entities: *EntitiesT, query: EntitiesT.Query) Self {
return Self{
.entities = entities,
.query = query,
.index = 0,
};
}
pub fn next(iter: *Self) ?*ArchetypeStorage {
var archetypes = iter.entities.archetypes.entries.items(.value);
while (true) {
if (iter.index == archetypes.len - 1) return null;
iter.index += 1;
var consideration = &archetypes[iter.index];
if (iter.match(consideration)) return consideration;
}
}
pub fn match(iter: *Self, consideration: *ArchetypeStorage) bool {
if (consideration.len == 0) return false;
switch (iter.query) {
.all => {
for (iter.query.all) |namespace| {
switch (namespace) {
inline else => |components| {
for (components) |component| {
const name = switch (component) {
inline else => |c| @tagName(namespace) ++ "." ++ @tagName(c),
};
var has_column = false;
for (consideration.columns) |column| {
if (std.mem.eql(u8, name, column.name)) {
has_column = true;
break;
}
}
if (!has_column) return false;
}
},
}
}
return true;
},
.any => @panic("TODO"),
}
}
};
}
test "entity ID size" {
try testing.expectEqual(8, @sizeOf(EntityID));
}
test "example" {
const allocator = testing.allocator;
const Location = struct {
x: f32 = 0,
y: f32 = 0,
z: f32 = 0,
};
const Rotation = struct { degrees: f32 };
const all_components = .{
.game = .{
.location = Location,
.name = []const u8,
.rotation = Rotation,
},
};
//-------------------------------------------------------------------------
// Create a world.
var world = try Entities(all_components).init(allocator);
defer world.deinit();
//-------------------------------------------------------------------------
// Create first player entity.
var player1 = try world.new();
try world.setComponent(player1, .game, .name, "jane"); // add .name component
try world.setComponent(player1, .game, .name, "joe"); // update .name component
try world.setComponent(player1, .game, .location, .{}); // add .location component
// Create second player entity.
var player2 = try world.new();
try testing.expect(world.getComponent(player2, .game, .location) == null);
try testing.expect(world.getComponent(player2, .game, .name) == null);
//-------------------------------------------------------------------------
// We can add new components at will.
try world.setComponent(player2, .game, .rotation, .{ .degrees = 90 });
try world.setComponent(player2, .game, .rotation, .{ .degrees = 91 }); // update .rotation component
try testing.expect(world.getComponent(player1, .game, .rotation) == null); // player1 has no rotation
//-------------------------------------------------------------------------
// Remove a component from any entity at will.
// TODO: add a way to "cleanup" truly unused archetypes
try world.removeComponent(player1, .game, .name);
try world.removeComponent(player1, .game, .location);
try world.removeComponent(player1, .game, .location); // doesn't exist? no problem.
//-------------------------------------------------------------------------
// Introspect things.
//
// Archetype IDs, these are our "table names" - they're just hashes of all the component names
// within the archetype table.
var archetypes = world.archetypes.keys();
try testing.expectEqual(@as(usize, 6), archetypes.len);
try testing.expectEqual(@as(u64, void_archetype_hash), archetypes[0]);
try testing.expectEqual(@as(u64, 5804575476291452713), archetypes[1]);
try testing.expectEqual(@as(u64, 14072552683119202344), archetypes[2]);
try testing.expectEqual(@as(u64, 4263961864502127795), archetypes[3]);
try testing.expectEqual(@as(u64, 12546098194442238762), archetypes[4]);
try testing.expectEqual(@as(u64, 4457032469566706731), archetypes[5]);
// Number of (living) entities stored in an archetype table.
try testing.expectEqual(@as(usize, 0), world.archetypes.get(archetypes[0]).?.len);
try testing.expectEqual(@as(usize, 0), world.archetypes.get(archetypes[1]).?.len);
try testing.expectEqual(@as(usize, 0), world.archetypes.get(archetypes[2]).?.len);
try testing.expectEqual(@as(usize, 1), world.archetypes.get(archetypes[3]).?.len);
try testing.expectEqual(@as(usize, 0), world.archetypes.get(archetypes[4]).?.len);
try testing.expectEqual(@as(usize, 1), world.archetypes.get(archetypes[5]).?.len);
// Components for a given archetype.
var columns = world.archetypes.get(archetypes[2]).?.columns;
try testing.expectEqual(@as(usize, 3), columns.len);
try testing.expectEqualStrings("id", columns[0].name);
try testing.expectEqualStrings("game.name", columns[1].name);
try testing.expectEqualStrings("game.location", columns[2].name);
// Archetype resolved via entity ID
var player2_archetype = world.archetypeByID(player2);
try testing.expectEqual(@as(u64, 4263961864502127795), player2_archetype.hash);
//-------------------------------------------------------------------------
// Query for archetypes that have all of the given components
var iter = world.query(.{ .all = &.{
.{ .game = &.{.rotation} },
} });
while (iter.next()) |archetype| {
var entities = archetype.getColumnValues(allocator, "id", EntityID).?[0..archetype.len];
try testing.expectEqual(@as(usize, 1), entities.len);
try testing.expectEqual(player2, entities[0]);
}
// TODO: iterating components an entity has not currently supported.
//-------------------------------------------------------------------------
// Remove an entity whenever you wish. Just be sure not to try and use it later!
try world.remove(player1);
}
test "empty_world" {
const allocator = testing.allocator;
//-------------------------------------------------------------------------
var world = try Entities(.{}).init(allocator);
// Create a world.
defer world.deinit();
}

View file

@ -1,94 +0,0 @@
//! mach/ecs is an Entity component system implementation.
//!
//! ## Design principles:
//!
//! * Initially a 100% clean-room implementation, working from first-principles. Later informed by
//! research into how other ECS work, with advice from e.g. Bevy and Flecs authors at different
//! points (thank you!)
//! * Solve the problems ECS solves, in a way that is natural to Zig and leverages Zig comptime.
//! * Fast. Optimal for CPU caches, multi-threaded, leverage comptime as much as is reasonable.
//! * Simple. Small API footprint, should be natural and fun - not like you're writing boilerplate.
//! * Enable other libraries to provide tracing, editors, visualizers, profilers, etc.
//!
const std = @import("std");
const testing = std.testing;
pub const EntityID = @import("entities.zig").EntityID;
pub const Entities = @import("entities.zig").Entities;
pub const Module = @import("systems.zig").Module;
pub const Modules = @import("systems.zig").Modules;
pub const Messages = @import("systems.zig").Messages;
pub const MessagesTag = @import("systems.zig").MessagesTag;
pub const World = @import("systems.zig").World;
// TODO:
// * Iteration
// * Querying
// * Multi threading
// * Multiple entities having one value
// * Sparse storage?
test "inclusion" {
std.testing.refAllDeclsRecursive(@This());
std.testing.refAllDeclsRecursive(@import("query.zig"));
}
test "example" {
const allocator = testing.allocator;
const Physics2D = Module(struct {
pointer: u8,
pub const name = .physics;
pub const components = .{
.id = u32,
};
pub const Message = .{
.tick = void,
};
pub fn update(msg: Message) void {
switch (msg) {
.tick => std.debug.print("\nphysics tick!\n", .{}),
}
}
});
const Renderer = Module(struct {
pub const name = .renderer;
pub const components = .{
.id = u16,
};
});
const modules = Modules(.{
Physics2D,
Renderer,
});
//-------------------------------------------------------------------------
// Create a world.
var world = try World(modules).init(allocator);
defer world.deinit();
// Initialize module state.
var physics = world.mod(.physics);
var renderer = world.mod(.renderer);
physics.initState(.{ .pointer = 123 });
_ = physics.state().pointer; // == 123
const player1 = try world.newEntity();
const player2 = try world.newEntity();
const player3 = try world.newEntity();
try physics.set(player1, .id, 1234);
try renderer.set(player1, .id, 1234);
try physics.set(player2, .id, 1234);
try physics.set(player3, .id, 1234);
//-------------------------------------------------------------------------
// Send events to modules
try world.send(.tick);
}

View file

@ -1,113 +0,0 @@
const std = @import("std");
const testing = std.testing;
pub const QueryTag = enum {
any,
all,
};
/// A complex query for entities matching a given criteria
pub fn Query(comptime all_components: anytype) type {
return union(QueryTag) {
/// Enum matching a namespace. e.g. `.game` or `.physics2d`
pub const Namespace = std.meta.FieldEnum(@TypeOf(all_components));
/// Enum matching a component within a namespace
/// e.g. `var a: Component(.physics2d) = .location`
pub fn Component(comptime namespace: Namespace) type {
return std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(namespace))));
}
/// Slice of enums matching a component within a namespace
/// e.g. `&.{.location, .rotation}`
pub fn ComponentList(comptime namespace: Namespace) type {
return []const Component(namespace);
}
/// Tagged union of namespaces matching lists of components
/// e.g. `.physics2d = &.{ .location, .rotation }`
pub const NamespaceComponent = T: {
const namespaces = std.meta.fields(Namespace);
var fields: [namespaces.len]std.builtin.Type.UnionField = undefined;
inline for (namespaces, 0..) |namespace, i| {
const ns = std.meta.stringToEnum(Namespace, namespace.name).?;
fields[i] = .{
.name = namespace.name,
.type = ComponentList(ns),
.alignment = @alignOf(ComponentList(ns)),
};
}
break :T @Type(.{ .Union = .{
.layout = .Auto,
.tag_type = Namespace,
.fields = &fields,
.decls = &.{},
} });
};
/// Matches any of these components
any: []const NamespaceComponent,
/// Matches all of these components
all: []const NamespaceComponent,
};
}
test "query" {
const Location = struct {
x: f32 = 0,
y: f32 = 0,
z: f32 = 0,
};
const Rotation = struct { degrees: f32 };
const all_components = .{
.game = .{
.name = []const u8,
},
.physics = .{
.location = Location,
.rotation = Rotation,
},
};
const Q = Query(all_components);
// Namespace type lets us select a single namespace.
try testing.expectEqual(@as(Q.Namespace, .game), .game);
try testing.expectEqual(@as(Q.Namespace, .physics), .physics);
// Component type lets us select a single component within a namespace.
try testing.expectEqual(@as(Q.Component(.physics), .location), .location);
try testing.expectEqual(@as(Q.Component(.game), .name), .name);
// ComponentList type lets us select multiple components within a namespace.
var x: Q.ComponentList(.physics) = &.{
.location,
.rotation,
};
_ = x;
// NamespaceComponent lets us select multiple components within multiple namespaces.
var y: []const Q.NamespaceComponent = &.{
.{ .physics = &.{ .location, .rotation } },
.{ .game = &.{.name} },
};
_ = y;
// Query matching entities with *any* of these components
var z: Q = .{ .any = &.{
.{ .physics = &.{ .location, .rotation } },
.{ .game = &.{.name} },
} };
_ = z;
// Query matching entities with *all* of these components.
var w: Q = .{ .all = &.{
.{ .physics = &.{ .location, .rotation } },
.{ .game = &.{.name} },
} };
_ = w;
}

View file

@ -1,336 +0,0 @@
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const testing = std.testing;
const math = std.math;
const StructField = std.builtin.Type.StructField;
const EnumField = std.builtin.Type.EnumField;
const UnionField = std.builtin.Type.UnionField;
const Entities = @import("entities.zig").Entities;
const EntityID = @import("entities.zig").EntityID;
/// Validates that a module matches the expected type layout.
///
/// An ECS module has components, systems, state & more.
pub fn Module(comptime M: anytype) type {
if (@hasDecl(M, "name")) {
_ = @tagName(M.name);
} else @compileError("Module missing `pub const name = .foobar;`");
if (@hasDecl(M, "Message")) _ = Messages(M.Message);
// TODO(ecs): validate M.components decl signature, if present.
// TODO(ecs): validate M.update method signature, if present.
return M;
}
/// Validates that a list of module matches the expected type layout.
///
/// ECS modules have components, systems, state & more.
pub fn Modules(comptime modules: anytype) @TypeOf(modules) {
inline for (modules) |m| _ = Module(m);
return modules;
}
/// Returns a tagged union representing the messages, turning this:
///
/// ```
/// .{ .tick = void, .foo = i32 }
/// ```
///
/// Into `T`:
///
/// ```
/// const T = union(MessagesTag(messages)) {
/// .tick = void,
/// .foo = i32,
/// };
/// ```
pub fn Messages(comptime messages: anytype) type {
var fields: []const UnionField = &[0]UnionField{};
const message_fields = std.meta.fields(@TypeOf(messages));
inline for (message_fields) |message_field| {
const message_type = @field(messages, message_field.name);
fields = fields ++ [_]std.builtin.Type.UnionField{.{
.name = message_field.name,
.type = message_type,
.alignment = if (message_type == void) 0 else @alignOf(message_type),
}};
}
return @Type(.{
.Union = .{
.layout = .Auto,
.tag_type = MessagesTag(messages),
.fields = fields,
.decls = &[_]std.builtin.Type.Declaration{},
},
});
}
/// Returns the tag enum for a tagged union representing the messages, turning this:
///
/// ```
/// .{ .tick = void, .foo = i32 }
/// ```
///
/// Into this:
///
/// ```
/// enum { .tick, .foo };
/// ```
pub fn MessagesTag(comptime messages: anytype) type {
var fields: []const EnumField = &[0]EnumField{};
const message_fields = std.meta.fields(@TypeOf(messages));
inline for (message_fields, 0..) |message_field, index| {
fields = fields ++ [_]std.builtin.Type.EnumField{.{
.name = message_field.name,
.value = index,
}};
}
return @Type(.{
.Enum = .{
.tag_type = std.meta.Int(.unsigned, @floatToInt(u16, math.ceil(math.log2(@intToFloat(f64, message_fields.len))))),
.fields = fields,
.decls = &[_]std.builtin.Type.Declaration{},
.is_exhaustive = true,
},
});
}
const NoComponents = @TypeOf(.{ .none = void });
const NoState = @TypeOf(.{});
/// Returns the namespaced components struct **type**.
//
/// Consult `namespacedComponents` for how a value of this type looks.
fn NamespacedComponents(comptime modules: anytype) type {
var fields: []const StructField = &[0]StructField{};
inline for (std.meta.fields(@TypeOf(modules))) |module_field| {
const module = @field(modules, module_field.name);
const module_name = @tagName(@field(module, "name"));
if (@hasDecl(module, "components")) {
fields = fields ++ [_]std.builtin.Type.StructField{.{
.name = module_name,
.type = @TypeOf(module.components),
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(@TypeOf(module.components)),
}};
} else {
fields = fields ++ [_]std.builtin.Type.StructField{.{
.name = module_name,
.type = NoComponents,
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(NoComponents),
}};
}
}
return @Type(.{
.Struct = .{
.layout = .Auto,
.is_tuple = false,
.fields = fields,
.decls = &[_]std.builtin.Type.Declaration{},
},
});
}
/// Extracts namespaces components from modules like this. A module is said to have components if
/// the struct has a `pub const components`. This function returns a namespaced components value
/// like e.g.:
///
/// ```
/// .{
/// .renderer = .{
/// .location = Vec3,
/// .rotation = Vec3,
/// },
/// .physics2d = .{
/// .location = Vec2
/// .velocity = Vec2,
/// },
/// }
/// ```
///
fn namespacedComponents(comptime modules: anytype) NamespacedComponents(modules) {
var x: NamespacedComponents(modules) = undefined;
inline for (std.meta.fields(@TypeOf(modules))) |module_field| {
const module = @field(modules, module_field.name);
const module_name = @tagName(@field(module, "name"));
if (@hasDecl(module, "components")) {
@field(x, module_name) = module.components;
} else {
@field(x, module_name) = .{};
}
}
return x;
}
/// Extracts namespaced state from modules (a module is said to have state if the struct has
/// any fields), returning a type like e.g.:
///
/// ```
/// struct{
/// renderer: struct{
/// foo: *Bar,
/// baz: Bam,
/// },
/// physics2d: struct{
/// foo: *Instance,
/// },
/// }
/// ```
///
fn NamespacedState(comptime modules: anytype) type {
var fields: []const StructField = &[0]StructField{};
inline for (std.meta.fields(@TypeOf(modules))) |module_field| {
const module = @field(modules, module_field.name);
const module_name = @tagName(@field(module, "name"));
const state_fields = std.meta.fields(module);
const State = if (state_fields.len > 0) @Type(.{
.Struct = .{
.layout = .Auto,
.is_tuple = false,
.fields = state_fields,
.decls = &[_]std.builtin.Type.Declaration{},
},
}) else NoState;
fields = fields ++ [_]std.builtin.Type.StructField{.{
.name = module_name,
.type = State,
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(State),
}};
}
return @Type(.{
.Struct = .{
.layout = .Auto,
.is_tuple = false,
.fields = fields,
.decls = &[_]std.builtin.Type.Declaration{},
},
});
}
/// Returns the type of the named field in the given struct.
fn FieldType(comptime Struct: type, comptime field_name: []const u8) type {
inline for (@typeInfo(Struct).Struct.fields) |f| {
if (std.mem.eql(u8, f.name, field_name)) return f.type;
}
@panic("no such struct field '" ++ field_name ++ "' in type: " ++ @typeName(Struct));
}
pub fn World(comptime modules: anytype) type {
const all_components = namespacedComponents(modules);
return struct {
allocator: Allocator,
entities: Entities(all_components),
state: NamespacedState(modules),
const Self = @This();
pub fn Module(comptime module_tag: anytype, comptime NSState: type) type {
return struct {
world: *Self,
const State = FieldType(NSState, @tagName(module_tag));
/// Returns a pointer to the state struct of this module.
pub inline fn state(m: @This()) *State {
return &@field(m.world.state, @tagName(module_tag));
}
/// Returns a pointer to the state struct of this module.
pub inline fn initState(m: @This(), s: State) void {
m.state().* = s;
}
/// Sets the named component to the specified value for the given entity,
/// moving the entity from it's current archetype table to the new archetype
/// table if required.
pub inline fn set(
m: *@This(),
entity: EntityID,
comptime component_name: std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(module_tag)))),
component: @field(
@field(all_components, @tagName(module_tag)),
@tagName(component_name),
),
) !void {
try m.world.entities.setComponent(entity, module_tag, component_name, component);
}
/// gets the named component of the given type (which must be correct, otherwise undefined
/// behavior will occur). Returns null if the component does not exist on the entity.
pub inline fn get(
m: *@This(),
entity: EntityID,
comptime component_name: std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(module_tag)))),
) ?@field(
@field(all_components, @tagName(module_tag)),
@tagName(component_name),
) {
return m.world.entities.getComponent(entity, module_tag, component_name);
}
/// Removes the named component from the entity, or noop if it doesn't have such a component.
pub inline fn remove(
m: *@This(),
entity: EntityID,
comptime component_name: std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(module_tag)))),
) !void {
try m.world.entities.removeComponent(entity, module_tag, component_name);
}
};
}
pub inline fn mod(world: *Self, comptime module_tag: anytype) Self.Module(module_tag, NamespacedState(modules)) {
return .{ .world = world };
}
pub fn init(allocator: Allocator) !Self {
return Self{
.allocator = allocator,
.entities = try Entities(all_components).init(allocator),
.state = undefined,
};
}
pub fn deinit(world: *Self) void {
world.entities.deinit();
}
/// Broadcasts an event to all modules that are subscribed to it.
///
/// The message tag corresponds with the handler method name to be invoked. For example,
/// if `send(.tick)` is invoked, all modules which declare a `pub fn init` will be invoked.
///
/// Events sent by Mach itself, or the application itself, may be single words. To prevent
/// name conflicts, events sent by modules provided by a library should prefix their events
/// with their module name. For example, a module named `.ziglibs_imgui` should use event
/// names like `.ziglibsImguiClick`, `.ziglibsImguiFoobar`.
pub fn send(world: *Self, comptime msg_tag: anytype) !void {
inline for (std.meta.fields(@TypeOf(modules))) |module_field| {
const module = @field(modules, module_field.name);
if (@hasDecl(module, @tagName(msg_tag))) {
const handler = @field(module, @tagName(msg_tag));
try handler(world);
}
}
}
/// Returns a new entity.
pub inline fn newEntity(world: *Self) !EntityID {
return try world.entities.new();
}
/// Removes an entity.
pub inline fn removeEntity(world: *Self, entity: EntityID) !void {
try world.entities.removeEntity(entity);
}
};
}