mirror of
https://github.com/Ukendio/jecs.git
synced 2025-06-19 15:59:18 +00:00
Docs chernoboyl
This commit is contained in:
parent
6a5832db20
commit
00e7d87a1c
18 changed files with 853 additions and 1175 deletions
|
@ -8,83 +8,42 @@ export default defineConfig({
|
|||
themeConfig: {
|
||||
// https://vitepress.dev/reference/default-theme-config
|
||||
nav: [
|
||||
{ text: "Learn", link: "/" },
|
||||
{ text: "Learn", link: "/learn/overview.md" },
|
||||
{ text: "API", link: "/api/jecs.md" },
|
||||
{ text: "Examples", link: "https://github.com/Ukendio/jecs/tree/main/examples" },
|
||||
{ text: "Resources", link: "/resources" },
|
||||
],
|
||||
|
||||
sidebar: {
|
||||
"/api/": [
|
||||
{
|
||||
text: "Introduction",
|
||||
items: [
|
||||
{ text: "Getting Started", link: "/learn/overview/get-started" },
|
||||
{ text: "First Jecs Project", link: "/learn/overview/first-jecs-project" },
|
||||
]
|
||||
},
|
||||
{
|
||||
text: "API reference",
|
||||
text: "Namespaces",
|
||||
items: [
|
||||
{ text: "jecs", link: "/api/jecs" },
|
||||
{ text: "World", link: "/api/world" },
|
||||
{ text: "Query", link: "/api/query" },
|
||||
],
|
||||
}
|
||||
},
|
||||
],
|
||||
"/learn/": [
|
||||
{
|
||||
text: "Introduction",
|
||||
items: [
|
||||
{ text: "Getting Started", link: "/learn/overview/get-started" },
|
||||
{ text: "First Jecs Project", link: "/learn/overview/first-jecs-project" },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Concepts",
|
||||
items: [
|
||||
{ text: "Entities and Components", link: "/learn/concepts/entities-and-components" },
|
||||
{ text: "Queries", link: "/learn/concepts/queries" },
|
||||
{ text: "Relationships", link: "/learn/concepts/relationships" },
|
||||
{ text: "Component Traits", link: "learn/concepts/component-traits" },
|
||||
{ text: "Addons", link: "/learn/concepts/addons" },
|
||||
],
|
||||
text: "Overview",
|
||||
items: [{ text: "Overview", link: "/learn/overview" }],
|
||||
},
|
||||
{
|
||||
text: "API Reference",
|
||||
items: [
|
||||
{ text: "jecs", link: "/api/jecs"},
|
||||
{ text: "World", link: "/api/world"},
|
||||
{ text: "Query", link: "/api/query"}
|
||||
]
|
||||
},
|
||||
{
|
||||
text: "Resources",
|
||||
items: [
|
||||
{ text: "Guides", link: "/learn/resources/guides" }
|
||||
]
|
||||
},
|
||||
{
|
||||
text: "Contribute",
|
||||
items: [
|
||||
{ text: "How Can I Contribute?", link: "/contributing/guidelines" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"/contributing/": [
|
||||
{
|
||||
text: "Introduction",
|
||||
items: [
|
||||
{ text: "Getting Started", link: "/learn/overview/get-started" },
|
||||
{ text: "First Jecs Project", link: "/learn/overview/first-jecs-project" },
|
||||
{ text: "jecs", link: "/api/jecs" },
|
||||
{ text: "World", link: "/api/world" },
|
||||
{ text: "Query", link: "/api/query" },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Contributing",
|
||||
items: [
|
||||
{ text: "Contribution Guidelines", link: "/contributing/guidelines" },
|
||||
{ text: "Submitting Issues", link: "/contributing/issues" },
|
||||
{ text: "Submitting Pull Requests", link: "/contributing/pull-requests" },
|
||||
{ text: "Code Coverage", link: "/contributing/coverage" },
|
||||
{ text: "Contribution Guidelines", link: "/learn/contributing/guidelines" },
|
||||
{ text: "Submitting Issues", link: "/learn/contributing/issues" },
|
||||
{ text: "Submitting Pull Requests", link: "/learn/contributing/pull-requests" },
|
||||
{ text: "Code Coverage", link: "/learn/contributing/coverage" },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
|
|
@ -10,8 +10,8 @@ hero:
|
|||
alt: Jecs logo
|
||||
actions:
|
||||
- theme: brand
|
||||
text: Get Started
|
||||
link: learn/overview/get-started.md
|
||||
text: Overview
|
||||
link: learn/overview.md
|
||||
- theme: alt
|
||||
text: API References
|
||||
link: /api/jecs.md
|
||||
|
@ -19,7 +19,7 @@ hero:
|
|||
features:
|
||||
- title: Stupidly Fast
|
||||
icon: 🔥
|
||||
details: Iterates 500,000 entities at 60 frames per second.
|
||||
details: Iterates 800,000 entities at 60 frames per second.
|
||||
- title: Strictly Typed API
|
||||
icon: 🔒
|
||||
details: Has typings for both Luau and Typescript.
|
||||
|
|
|
@ -1,56 +0,0 @@
|
|||
# Addons
|
||||
|
||||
A collection of third-party jecs addons made by the community. If you would like to share what you're working on, [submit a pull request](/contributing/pull-requests#addons)!
|
||||
|
||||
# Development tools
|
||||
|
||||
## [jabby](https://github.com/alicesaidhi/jabby)
|
||||
|
||||
A jecs debugger with a string-based query language and entity editing capabilities.
|
||||
|
||||
## [jecs_entity_visualiser](https://github.com/Ukendio/jecs/blob/main/addons/entity_visualiser.luau)
|
||||
|
||||
A simple entity and component visualiser in the output
|
||||
|
||||
## [jecs_lifetime_tracker](https://github.com/Ukendio/jecs/blob/main/addons/lifetime_tracker.luau)
|
||||
|
||||
A tool for inspecting entity lifetimes
|
||||
|
||||
# Helpers
|
||||
|
||||
## [jecs_observers](https://github.com/Ukendio/jecs/blob/main/addons/observers.luau)
|
||||
|
||||
Observers for queries and signals for components
|
||||
|
||||
# Schedulers
|
||||
|
||||
## [lockstep scheduler](https://gist.github.com/1Axen/6d4f78b3454cf455e93794505588354b)
|
||||
|
||||
A simple fixed step system scheduler.
|
||||
|
||||
## [rubine](https://github.com/Mark-Marks/rubine)
|
||||
|
||||
An ergonomic, runtime agnostic scheduler for Jecs
|
||||
|
||||
## [jam](https://github.com/revvy02/Jam)
|
||||
|
||||
Provides hooks and a scheduler that implements jabby and a topographical runtime
|
||||
|
||||
## [planck](https://github.com/YetAnotherClown/planck)
|
||||
|
||||
An agnostic scheduler inspired by Bevy and Flecs, with core features including phases, pipelines, run conditions, and startup systems.
|
||||
Planck also provides plugins for Jabby, Matter Hooks, and more.
|
||||
|
||||
# Replication
|
||||
|
||||
## [feces](https://github.com/NeonD00m/feces)
|
||||
|
||||
A generalized replication system for jecs
|
||||
|
||||
# Input
|
||||
|
||||
## [Axis](https://github.com/NeonD00m/axis)
|
||||
|
||||
An agnostic, simple and versatile input library for ECS
|
||||
|
||||
# Observers
|
|
@ -1,191 +0,0 @@
|
|||
# Component Traits
|
||||
|
||||
Component traits are IDs and pairs that can be added to components to modify their behavior. Although it is possible to create custom traits, this manual only contains an overview of all builtin component traits supported by Jecs.
|
||||
|
||||
# Component
|
||||
|
||||
Every (component) ID comes with a `Component` which helps with the distinction between normal entities and component IDs.
|
||||
|
||||
# Tag
|
||||
|
||||
A (component) ID can be marked with `Tag´ in which the component will never contain any data. This allows for zero-cost components which improves performance for structural changes.
|
||||
|
||||
# Hooks
|
||||
|
||||
Hooks are part of the "interface" of a component. You could consider hooks as the counterpart to OOP methods in ECS. They define the behavior of a component, but can only be invoked through mutations on the component data. You can only configure a single `OnAdd`, `OnRemove` and `OnSet` hook per component, just like you can only have a single constructor and destructor.
|
||||
|
||||
::: warning
|
||||
Hooks, added to a component that has already been added to other entities/components, will not be called.
|
||||
:::
|
||||
|
||||
## Examples
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local Transform= world:component()
|
||||
world:set(Transform, OnAdd, function(entity)
|
||||
-- A transform component has been added to an entity
|
||||
end)
|
||||
world:set(Transform, OnRemove, function(entity)
|
||||
-- A transform component has been removed from the entity
|
||||
end)
|
||||
world:set(Transform, OnSet, function(entity, value)
|
||||
-- A transform component has been assigned/changed to value on the entity
|
||||
end)
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Transform = world.component();
|
||||
world.set(Transform, OnAdd, (entity) => {
|
||||
// A transform component has been added to an entity
|
||||
});
|
||||
world.set(Transform, OnRemove, (entity) => {
|
||||
// A transform component has been removed from the entity
|
||||
});
|
||||
world.set(Transform, OnSet, (entity, value) => {
|
||||
// A transform component has been assigned/changed to value on the entity
|
||||
});
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
# Cleanup Traits
|
||||
|
||||
When entities that are used as tags, components, relationships or relationship targets are deleted, cleanup traits ensure that the store does not contain any dangling references. Any cleanup policy provides this guarantee, so while they are configurable, games cannot configure traits that allows for dangling references.
|
||||
|
||||
We also want to specify this per relationship. If an entity has `(Likes, parent)` we may not want to delete that entity, meaning the cleanup we want to perform for `Likes` and `ChildOf` may not be the same.
|
||||
|
||||
This is what cleanup traits are for: to specify which action needs to be executed under which condition. They are applied to entities that have a reference to the entity being deleted: if I delete the `Archer` tag I remove the tag from all entities that have it.
|
||||
|
||||
To configure a cleanup policy for an entity, a `(Condition, Action)` pair can be added to it. If no policy is specified, the default cleanup action (`Remove`) is performed.
|
||||
|
||||
There are two cleanup actions:
|
||||
|
||||
- `Remove`: removes instances of the specified (component) id from all entities (default)
|
||||
- `Delete`: deletes all entities with specified id
|
||||
|
||||
There are two cleanup conditions:
|
||||
|
||||
- `OnDelete`: the component, tag or relationship is deleted
|
||||
- `OnDeleteTarget`: a target used with the relationship is deleted
|
||||
|
||||
## Examples
|
||||
|
||||
The following examples show how to use cleanup traits
|
||||
|
||||
### (OnDelete, Remove)
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local Archer = world:component()
|
||||
world:add(Archer, pair(jecs.OnDelete, jecs.Remove))
|
||||
|
||||
local e = world:entity()
|
||||
world:add(e, Archer)
|
||||
|
||||
-- This will remove Archer from e
|
||||
world:delete(Archer)
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Archer = world.component();
|
||||
world.add(Archer, pair(jecs.OnDelete, jecs.Remove));
|
||||
|
||||
const e = world.entity();
|
||||
world.add(e, Archer);
|
||||
|
||||
// This will remove Archer from e
|
||||
world.delete(Archer);
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### (OnDelete, Delete)
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local Archer = world:component()
|
||||
world:add(Archer, pair(jecs.OnDelete, jecs.Delete))
|
||||
|
||||
local e = world:entity()
|
||||
world:add(e, Archer)
|
||||
|
||||
-- This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait
|
||||
world:delete(Archer)
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Archer = world.component();
|
||||
world.add(Archer, pair(jecs.OnDelete, jecs.Delete));
|
||||
|
||||
const e = world.entity();
|
||||
world.add(e, Archer);
|
||||
|
||||
// This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait
|
||||
world.delete(Archer);
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### (OnDeleteTarget, Remove)
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local OwnedBy = world:component()
|
||||
world:add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove))
|
||||
local loot = world:entity()
|
||||
local player = world:entity()
|
||||
world:add(loot, pair(OwnedBy, player))
|
||||
|
||||
-- This will remove (OwnedBy, player) from loot
|
||||
world:delete(player)
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const OwnedBy = world.component();
|
||||
world.add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove));
|
||||
const loot = world.entity();
|
||||
const player = world.entity();
|
||||
world.add(loot, pair(OwnedBy, player));
|
||||
|
||||
// This will remove (OwnedBy, player) from loot
|
||||
world.delete(player);
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### (OnDeleteTarget, Delete)
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local ChildOf = world:component()
|
||||
world:add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete))
|
||||
|
||||
local parent = world:entity()
|
||||
local child = world:entity()
|
||||
world:add(child, pair(ChildOf, parent))
|
||||
|
||||
-- This will delete both parent and child
|
||||
world:delete(parent)
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const ChildOf = world.component();
|
||||
world.add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete));
|
||||
|
||||
const parent = world.entity();
|
||||
const child = world.entity();
|
||||
world.add(child, pair(ChildOf, parent));
|
||||
|
||||
// This will delete both parent and child
|
||||
world.delete(parent);
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
This page takes wording and terminology directly from Flecs [documentation](https://www.flecs.dev/flecs/md_docs_2ComponentTraits.html)
|
|
@ -1,140 +0,0 @@
|
|||
# Entities and Components
|
||||
|
||||
## Entities
|
||||
|
||||
Entities represent things in a game. In a game there may be entities of characters, buildings, projectiles, particle effects etc.
|
||||
|
||||
By itself, an entity is just an unique identifier without any data
|
||||
|
||||
## Components
|
||||
|
||||
A component is something that is added to an entity. Components can simply tag an entity ("this entity is an `Npc`"), attach data to an entity ("this entity is at `Position` `Vector3.new(10, 20, 30)`") and create relationships between entities ("bob `Likes` alice") that may also contain data ("bob `Eats` `10` apples").
|
||||
|
||||
## Operations
|
||||
|
||||
| Operation | Description |
|
||||
| --------- | ---------------------------------------------------------------------------------------------- |
|
||||
| `get` | Get a specific component or set of components from an entity. |
|
||||
| `add` | Adds component to an entity. If entity already has the component, `add` does nothing. |
|
||||
| `set` | Sets the value of a component for an entity. `set` behaves as a combination of `add` and `get` |
|
||||
| `remove` | Removes component from entity. If entity doesn't have the component, `remove` does nothing. |
|
||||
| `clear` | Remove all components from an entity. Clearing is more efficient than removing one by one. |
|
||||
|
||||
## Components are entities
|
||||
|
||||
In an ECS, components need to be uniquely identified. In Jecs this is done by making each component its own unique entity. If a game has a component Position and Velocity, there will be two entities, one for each component. Component entities can be distinguished from "regular" entities as they have a `Component` component. An example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local Position = world:component() :: jecs.Entity<Vector3>
|
||||
print(world:has(Position, jecs.Component))
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Position = world.component<Vector3>();
|
||||
print(world.has(Position, jecs.Component));
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
All of the APIs that apply to regular entities also apply to component entities. This means it is possible to contexualize components with logic by adding traits to components
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local Networked = world:component()
|
||||
local Type = world:component()
|
||||
local Name = world:component()
|
||||
local Position = world:component() :: jecs.Entity<Vector3>
|
||||
world:add(Position, Networked)
|
||||
world:set(Position, Name, "Position")
|
||||
world:set(Position, Type, { size = 12, type = "Vector3" } ) -- 12 bytes to represent a Vector3
|
||||
|
||||
for id, ty, name in world:query(Type, Name, Networked) do
|
||||
local batch = {}
|
||||
for entity, data in world:query(id) do
|
||||
table.insert(batch, { entity = entity, data = data })
|
||||
end
|
||||
-- entities are sized f64
|
||||
local packet = buffer.create(#batch * (8 + ty.size))
|
||||
local offset = 0
|
||||
for _, entityData in batch do
|
||||
offset+=8
|
||||
buffer.writef64(packet, offset, entityData.entity)
|
||||
if ty.type == "Vector3" then
|
||||
local vec3 = entity.data :: Vector3
|
||||
offset += 4
|
||||
buffer.writei32(packet, offset, vec3.X)
|
||||
offset += 4
|
||||
buffer.writei32(packet, offset, vec3.Y)
|
||||
offset += 4
|
||||
buffer.writei32(packet, offset, vec3.Z)
|
||||
end
|
||||
end
|
||||
|
||||
updatePositions:FireServer(packet)
|
||||
end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Networked = world.component();
|
||||
const Type = world.component();
|
||||
const Name = world.component();
|
||||
const Position = world.component<Vector3>();
|
||||
world.add(Position, Networked);
|
||||
world.set(Position, Name, "Position");
|
||||
world.set(Position, Type, { size: 12, type: "Vector3" }); // 12 bytes to represent a Vector3
|
||||
|
||||
for (const [id, ty, name] of world.query(Type, Name, Networked)) {
|
||||
const batch = new Array<{ entity: Entity; data: unknown }>();
|
||||
|
||||
for (const [entity, data] of world.query(id)) {
|
||||
batch.push({ entity, data });
|
||||
}
|
||||
// entities are sized f64
|
||||
const packet = buffer.create(batch.size() * (8 + ty.size));
|
||||
const offset = 0;
|
||||
for (const [_, entityData] of batch) {
|
||||
offset += 8;
|
||||
buffer.writef64(packet, offset, entityData.entity);
|
||||
if (ty.type == "Vector3") {
|
||||
const vec3 = entity.data as Vector3;
|
||||
offset += 4;
|
||||
buffer.writei32(packet, offsetm, vec3.X);
|
||||
offset += 4;
|
||||
buffer.writei32(packet, offset, vec3.Y);
|
||||
offset += 4;
|
||||
buffer.writei32(packet, offset, vec3.Z);
|
||||
}
|
||||
}
|
||||
|
||||
updatePositions.FireServer(packet);
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Singletons
|
||||
|
||||
Singletons are components for which only a single instance
|
||||
exists on the world. They can be accessed on the
|
||||
world directly and do not require providing an entity.
|
||||
Singletons are useful for global game resources, such as
|
||||
game state, a handle to a physics engine or a network socket. An example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local TimeOfDay = world:component() :: jecs.Entity<number>
|
||||
world:set(TimeOfDay, TimeOfDay, 0.5)
|
||||
local t = world:get(TimeOfDay, TimeOfDay)
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const TimeOfDay = world.component<number>();
|
||||
world.set(TimeOfDay, TimeOfDay, 0.5);
|
||||
const t = world.get(TimeOfDay, TimeOfDay);
|
||||
```
|
||||
|
||||
:::
|
|
@ -1,186 +0,0 @@
|
|||
# Queries
|
||||
|
||||
## Introduction
|
||||
|
||||
Queries enable games to quickly find entities that satifies provided conditions.
|
||||
|
||||
Jecs queries can do anything from returning entities that match a simple list of components, to matching against entity graphs.
|
||||
|
||||
This manual contains a full overview of the query features available in Jecs. Some of the features of Jecs queries are:
|
||||
|
||||
- Queries have support for relationships pairs which allow for matching against entity graphs without having to build complex data structures for it.
|
||||
- Queries support filters such as [`query:with(...)`](../../api/query.md#with) if entities are required to have the components but you don’t actually care about components value. And [`query:without(...)`](../../api/query.md#without) which selects entities without the components.
|
||||
- Queries can be drained or reset on when called, which lets you choose iterator behaviour.
|
||||
- Queries can be called with any ID, including entities created dynamically, this is useful for pairs.
|
||||
- Queries are already fast but can be futher inlined via [`query:archetypes()`](../../api/query.md#archetypes) for maximum performance to eliminate function call overhead which is roughly 70-80% of the cost for iteration.
|
||||
|
||||
## Performance and Caching
|
||||
|
||||
Understanding the basic architecture of queries helps to make the right tradeoffs when using queries in games.
|
||||
The biggest impact on query performance is whether a query is cached or not.
|
||||
This section goes over what caching is, how it can be used and when it makes sense to use it.
|
||||
|
||||
### Caching: what is it?
|
||||
|
||||
Jecs is an archetype ECS, which means that entities with exactly the same components are
|
||||
grouped together in an "archetype". Archetypes are created on the fly
|
||||
whenever a new component combination is created in the ECS. For example:
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
local e1 = world:entity()
|
||||
world:set(e1, Position, Vector3.new(10, 20, 30)) -- create archetype [Position]
|
||||
world:set(e1, Velocity, Vector3.new(1, 2, 3)) -- create archetype [Position, Velocity]
|
||||
|
||||
local e2 = world:entity()
|
||||
world:set(e2, Position, Vector3.new(10, 20, 30)) -- archetype [Position] already exists
|
||||
world:set(e2, Velocity, Vector3.new(1, 2, 3)) -- archetype [Position, Velocity] already exists
|
||||
world:set(e3, Mass, 100) -- create archetype [Position, Velocity, Mass]
|
||||
|
||||
-- e1 is now in archetype [Position, Velocity]
|
||||
-- e2 is now in archetype [Position, Velocity, Mass]
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const e1 = world.entity();
|
||||
world.set(e1, Position, new Vector3(10, 20, 30)); // create archetype [Position]
|
||||
world.set(e1, Velocity, new Vector3(1, 2, 3)); // create archetype [Position, Velocity]
|
||||
|
||||
const e2 = world.entity();
|
||||
world.set(e2, Position, new Vector3(10, 20, 30)); // archetype [Position] already exists
|
||||
world.set(e2, Velocity, new Vector3(1, 2, 3)); // archetype [Position, Velocity] already exists
|
||||
world.set(e3, Mass, 100); // create archetype [Position, Velocity, Mass]
|
||||
|
||||
// e1 is now in archetype [Position, Velocity]
|
||||
// e2 is now in archetype [Position, Velocity, Mass]
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Archetypes are important for queries. Since all entities in an archetype have the same components, and a query matches entities with specific components, a query can often match entire archetypes instead of individual entities. This is one of the main reasons why queries in an archetype ECS are fast.
|
||||
|
||||
The second reason that queries in an archetype ECS are fast is that they are cheap to cache. While an archetype is created for each unique component combination, games typically only use a finite set of component combinations which are created quickly after game assets are loaded.
|
||||
|
||||
This means that instead of searching for archetypes each time a query is evaluated, a query can instead cache the list of matching archetypes. This is a cheap cache to maintain: even though entities can move in and out of archetypes, the archetypes themselves are often stable.
|
||||
|
||||
If none of that made sense, the main thing to remember is that a cached query does not actually have to search for entities. Iterating a cached query just means iterating a list of prematched results, and this is really, really fast.
|
||||
|
||||
### Tradeoffs
|
||||
|
||||
Jecs has both cached and uncached queries. If cached queries are so fast, why even bother with uncached queries? There are four main reasons:
|
||||
|
||||
- Cached queries are really fast to iterate, but take more time to create because the cache must be initialized first.
|
||||
- Cached queries have a higher RAM utilization, whereas uncached queries have very little overhead and are stateless.
|
||||
- Cached queries add overhead to archetype creation/deletion, as these changes have to get propagated to caches.
|
||||
- While caching archetypes is fast, some query features require matching individual entities, which are not efficient to cache (and aren't cached).
|
||||
|
||||
As a rule of thumb, if you have a query that is evaluated each frame (as is typically the case with systems), they will benefit from being cached. If you need to create a query ad-hoc, an uncached query makes more sense.
|
||||
|
||||
Ad-hoc queries are often necessary when a game needs to find entities that match a condition that is only known at runtime, for example to find all child entities for a specific parent.
|
||||
|
||||
## Creating Queries
|
||||
|
||||
This section explains how to create queries in the different language bindings.
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
for _ in world:query(Position, Velocity) do end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
for (const [_] of world.query(Position, Velocity)) {
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Components
|
||||
|
||||
A component is any single ID that can be added to an entity. This includes tags and regular entities, which are IDs that do not have the builtin `Component` component. To match a query, an entity must have all the requested components. An example:
|
||||
|
||||
```luau
|
||||
local e1 = world:entity()
|
||||
world:add(e1, Position)
|
||||
|
||||
local e2 = world:entity()
|
||||
world:add(e2, Position)
|
||||
world:add(e2, Velocity)
|
||||
|
||||
local e3 = world:entity()
|
||||
world:add(e3, Position)
|
||||
world:add(e3, Velocity)
|
||||
world:add(e3, Mass)
|
||||
|
||||
```
|
||||
|
||||
Only entities `e2` and `e3` match the query Position, Velocity.
|
||||
|
||||
### Wildcards
|
||||
|
||||
Jecs currently only supports the `Any` type of wildcards which a single result for the first component that it matches.
|
||||
|
||||
When using the `Any` type wildcard it is undefined which component will be matched, as this can be influenced by other parts of the query. It is guaranteed that iterating the same query twice on the same dataset will produce the same result.
|
||||
|
||||
If you want to iterate multiple targets for the same relation on a pair, then use [`world:target`](../../api/world.md#target)
|
||||
|
||||
Wildcards are particularly useful when used in combination with pairs (next section).
|
||||
|
||||
### Pairs
|
||||
|
||||
A pair is an ID that encodes two elements. Pairs, like components, can be added to entities and are the foundation for [Relationships](relationships.md).
|
||||
|
||||
The elements of a pair are allowed to be wildcards. When a query pair returns an `Any` type wildcard, the query returns at most a single matching pair on an entity.
|
||||
|
||||
The following sections describe how to create queries for pairs in the different language bindings.
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
local Likes = world:entity()
|
||||
local bob = world:entity()
|
||||
for _ in world:query(pair(Likes, bob)) do end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Likes = world.entity();
|
||||
const bob = world.entity();
|
||||
for (const [_] of world.query(pair(Likes, bob))) {
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
When a query pair contains a wildcard, the `world:target()` function can be used to determine the target of the pair element that matched the query:
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
for id in world:query(pair(Likes, jecs.Wildcard)) do
|
||||
print(`entity {getName(id)} likes {getName(world, world:target(id, Likes))}`)
|
||||
end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Likes = world.entity();
|
||||
const bob = world.entity();
|
||||
for (const [_] of world.query(pair(Likes, jecs.Wildcard))) {
|
||||
print(`entity ${getName(id)} likes ${getName(world.target(id, Likes))}`);
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Filters
|
||||
|
||||
Filters are extensions to queries which allow you to select entities from a more complex pattern but you don't actually care about the component values.
|
||||
|
||||
The following filters are supported by queries:
|
||||
|
||||
| Identifier | Description |
|
||||
| ---------- | ----------------------------------- |
|
||||
| With | Must match with all terms. |
|
||||
| Without | Must not match with provided terms. |
|
||||
|
||||
This page takes wording and terminology directly from Flecs [documentation](https://www.flecs.dev/flecs/md_docs_2Queries.html)
|
|
@ -1,198 +0,0 @@
|
|||
# Relationships
|
||||
Relationships makes it possible to describe entity graphs natively in ECS.
|
||||
|
||||
Adding/removing relationships is similar to adding/removing regular components, with as difference that instead of a single component id, a relationship adds a pair of two things to an entity. In this pair, the first element represents the relationship (e.g. "Eats"), and the second element represents the relationship target (e.g. "Apples").
|
||||
|
||||
Relationships can be used to describe many things, from hierarchies to inventory systems to trade relationships between players in a game. The following sections go over how to use relationships, and what features they support.
|
||||
|
||||
## Definitions
|
||||
|
||||
Name | Description
|
||||
----------|------------
|
||||
Id | An id that can be added and removed
|
||||
Component | Id with a single element (same as an entity id)
|
||||
Relationship | Used to refer to first element of a pair
|
||||
Target | Used to refer to second element of a pair
|
||||
Source | Entity to which an id is added
|
||||
|
||||
## Relationship queries
|
||||
There are a number of ways a game can query for relationships. The following kinds of queries are available for all (unidirectional) relationships, and are all constant time:
|
||||
|
||||
Test if entity has a relationship pair
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
world:has(bob, pair(Eats, Apples))
|
||||
```
|
||||
```typescript [typescript]
|
||||
world.has(bob, pair(Eats, Apples))
|
||||
```
|
||||
:::
|
||||
|
||||
Test if entity has a relationship wildcard
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
world:has(bob, pair(Eats, jecs.Wildcard)
|
||||
```
|
||||
```typescript [typescript]
|
||||
world.has(bob, pair(Eats, jecs.Wildcard)
|
||||
```
|
||||
:::
|
||||
|
||||
Get parent for entity
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
world:parent(bob)
|
||||
```
|
||||
```typescript [typescript]
|
||||
world.parent(bob)
|
||||
```
|
||||
:::
|
||||
|
||||
Find first target of a relationship for entity
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
world:target(bob, Eats)
|
||||
```
|
||||
```typescript [typescript]
|
||||
world.target(bob, Eats)
|
||||
```
|
||||
:::
|
||||
|
||||
Find all entities with a pair
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
for id in world:query(pair(Eats, Apples)) do
|
||||
-- ...
|
||||
end
|
||||
```
|
||||
```typescript [typescript]
|
||||
for (const [id] of world.query(pair(Eats, Apples)) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
:::
|
||||
|
||||
Find all entities with a pair wildcard
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
for id in world:query(pair(Eats, jecs.Wildcard)) do
|
||||
local food = world:target(id, Eats) -- Apples, ...
|
||||
end
|
||||
```
|
||||
```typescript [typescript]
|
||||
for (const [id] of world.query(pair(Eats, jecs.Wildcard)) {
|
||||
const food = world.target(id, Eats) // Apples, ...
|
||||
}
|
||||
```
|
||||
:::
|
||||
|
||||
Iterate all children for a parent
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
for child in world:query(pair(jecs.ChildOf, parent)) do
|
||||
-- ...
|
||||
end
|
||||
```
|
||||
```typescript [typescript]
|
||||
for (const [child] of world.query(pair(jecs.ChildOf, parent)) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
:::
|
||||
|
||||
Relationship components
|
||||
|
||||
Relationship pairs, just like regular component, can be associated with data.
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
local Position = world:component()
|
||||
local Eats = world:component()
|
||||
local Apples = world:entity()
|
||||
local Begin = world:entity()
|
||||
local End = world:entity()
|
||||
|
||||
local e = world:entity()
|
||||
world:set(e, pair(Eats, Apples), { amount = 1 })
|
||||
|
||||
world:set(e, pair(Begin, Position), Vector3.new(0, 0, 0))
|
||||
world:set(e, pair(End, Position), Vector3.new(10, 20, 30))
|
||||
|
||||
world:add(e, jecs.ChildOf, Position)
|
||||
|
||||
```
|
||||
```typescript [typescript]
|
||||
const Position = world.component()
|
||||
const Eats = world.component()
|
||||
const Apples = world.entity()
|
||||
const Begin = world.entity()
|
||||
const End = world.entity()
|
||||
|
||||
const e = world.entity()
|
||||
world.set(e, pair(Eats, Apples), { amount: 1 })
|
||||
|
||||
world.set(e, pair(Begin, Position), new Vector3(0, 0, 0))
|
||||
world.set(e, pair(End, Position), new Vector3(10, 20, 30))
|
||||
|
||||
world.add(e, jecs.ChildOf, Position)
|
||||
```
|
||||
:::
|
||||
|
||||
## Relationship wildcards
|
||||
|
||||
When querying for relationship pairs, it is often useful to be able to find all instances for a given relationship or target. To accomplish this, an game can use wildcard expressions.
|
||||
|
||||
Wildcards may used for the relationship or target part of a pair
|
||||
|
||||
```luau
|
||||
pair(Likes, jecs.Wildcard) -- Matches all Likes relationships
|
||||
pair(jecs.Wildcard, Alice) -- Matches all relationships with Alice as target
|
||||
```
|
||||
|
||||
## Relationship performance
|
||||
This section goes over the performance implications of using relationships.
|
||||
|
||||
### Introduction
|
||||
The ECS storage needs to know two things in order to store components for entities:
|
||||
- Which IDs are associated with an entity
|
||||
- Which types are associated with those ids
|
||||
Ids represent anything that can be added to an entity. An ID that is not associated with a type is called a tag. An ID associated with a type is a component. For regular components, the ID is a regular entity that has the builtin `Component` component.
|
||||
|
||||
### Storing relationships
|
||||
Relationships do not fundamentally change or extend the capabilities of the storage. Relationship pairs are two elements encoded into a single 53-bit ID, which means that on the storage level they are treated the same way as regular component IDs. What changes is the function that determines which type is associated with an id. For regular components this is simply a check on whether an entity has `Component`. To support relationships, new rules are added to determine the type of an id.
|
||||
|
||||
Because of this, adding/removing relationships to entities has the same performance as adding/removing regular components. This becomes more obvious when looking more closely at a function that adds a relationship pair.
|
||||
|
||||
### Id ranges
|
||||
Jecs reserves entity ids under a threshold (HI_COMPONENT_ID, default is 256) for components. This low id range is used by the storage to more efficiently encode graph edges between archetypes. Graph edges for components with low ids use direct array indexing, whereas graph edges for high ids use a hashmap. Graph edges are used to find the next archetype when adding/removing component ids, and are a contributing factor to the performance overhead of add/remove operations.
|
||||
|
||||
Because of the way pair IDs are encoded, a pair will never be in the low id range. This means that adding/removing a pair ID always uses a hashmap to find the next archetype. This introduces a small overhead.
|
||||
|
||||
### Fragmentation
|
||||
Fragmentation is a property of archetype-based ECS implementations where entities are spread out over more archetypes as the number of different component combinations increases. The overhead of fragmentation is visible in two areas:
|
||||
- Archetype creation
|
||||
- Queries (queries have to match & iterate more archetypes)
|
||||
Games that make extensive use of relationships might observe high levels of fragmentation, as relationships can introduce many different combinations of components. While the Jecs storage is optimized for supporting large amounts (hundreds of thousands) of archetypes, fragmentation is a factor to consider when using relationships.
|
||||
|
||||
Union relationships are planned along with other improvements to decrease the overhead of fragmentation introduced by relationships.
|
||||
|
||||
### Archetype Creation
|
||||
|
||||
When an ID added to an entity is deleted, all references to that ID are deleted from the storage. For example, when the component Position is deleted it is removed from all entities, and all archetypes with the Position component are deleted. While not unique to relationships, it is more common for relationships to trigger cleanup actions, as relationship pairs contain regular entities.
|
||||
|
||||
The opposite is also true. Because relationship pairs can contain regular entities which can be created on the fly, archetype creation is more common than in games that do not use relationships. While Jecs is optimized for fast archetypes creation, creating and cleaning up archetypes is inherently more expensive than creating/deleting an entity. Therefore archetypes creation is a factor to consider, especially for games that make extensive use of relationships.
|
||||
|
||||
### Indexing
|
||||
|
||||
To improve the speed of evaluating queries, Jecs has indices that store all archetypes for a given component ID. Whenever a new archetype is created, it is registered with the indices for the IDs the archetype has, including IDs for relationship pairs.
|
||||
|
||||
While registering an archetype for a relationship index is not more expensive than registering an archetype for a regular index, an archetype with relationships has to also register itself with the appropriate wildcard indices for its relationships. For example, an archetype with relationship `pair(Likes, Apples)` registers itself with the `pair(Likes, Apples)`, `pair(Likes, jecs.Wildcard)` and `pair(jecs.Wildcard, Apples)` indices. For this reason, creating new archetypes with relationships has a higher overhead than an archetype without relationships.
|
||||
|
||||
This page takes wording and terminology directly from Flecs, the first ECS with full support for [Entity Relationships](https://www.flecs.dev/flecs/md_docs_2Relationships.html).
|
|
@ -1,21 +1,21 @@
|
|||
# Contribution Guidelines
|
||||
|
||||
Whether you found an issue, or want to make a change to jecs, we'd love to hear back from the community on what features you want or bugs you've run into.
|
||||
|
||||
There's a few different ways you can go about this.
|
||||
|
||||
## Creating an Issue
|
||||
|
||||
This is what you should be filing if you have a bug you want to report.
|
||||
|
||||
[Click here](https://github.com/Ukendio/jecs/issues/new/choose) to file a bug report. We have a few templates ready for the most common issue types.
|
||||
|
||||
Additionally, see the [Submitting Issues](/contributing/issues) page for more information.
|
||||
|
||||
## Creating a Pull Request
|
||||
|
||||
This is what you should be filing if you have a change you want to merge into the main project.
|
||||
|
||||
[Click here](https://github.com/Ukendio/jecs/compare) to select the branch you want to merge from.
|
||||
|
||||
Additionally, see the [Submitting Pull Requests](/contributing/pull-requests) page for more information.
|
||||
# Contribution Guidelines
|
||||
|
||||
Whether you found an issue, or want to make a change to jecs, we'd love to hear back from the community on what features you want or bugs you've run into.
|
||||
|
||||
There's a few different ways you can go about this.
|
||||
|
||||
## Creating an Issue
|
||||
|
||||
This is what you should be filing if you have a bug you want to report.
|
||||
|
||||
[Click here](https://github.com/Ukendio/jecs/issues/new/choose) to file a bug report. We have a few templates ready for the most common issue types.
|
||||
|
||||
Additionally, see the [Submitting Issues](../contributing/issues) page for more information.
|
||||
|
||||
## Creating a Pull Request
|
||||
|
||||
This is what you should be filing if you have a change you want to merge into the main project.
|
||||
|
||||
[Click here](https://github.com/Ukendio/jecs/compare) to select the branch you want to merge from.
|
||||
|
||||
Additionally, see the [Submitting Pull Requests](../contributing/pull-requests) page for more information.
|
|
@ -1,25 +1,24 @@
|
|||
# Submitting Issues
|
||||
|
||||
When you're submitting an issue, generally they fall into a few categories:
|
||||
|
||||
## Bug
|
||||
|
||||
We need some information to figure out what's going wrong. At a minimum, you need to tell us:
|
||||
|
||||
(1) What's supposed to happen
|
||||
|
||||
(2) What actually happened
|
||||
|
||||
(3) Steps to reproduce
|
||||
|
||||
|
||||
Stack traces and other useful information that you find make a bug report more likely to be fixed.
|
||||
|
||||
Consult the template for a bug report if you don't know or have questions about how to format this.
|
||||
|
||||
## Documentation
|
||||
|
||||
Depending on how you go about it, this can be done as a [Pull Request](/contributing/pull-requests) instead of an issue. Generally, we need to know what was wrong, what you changed, and how it improved the documentation if it isn't obvious.
|
||||
|
||||
We just need to know what's wrong. You should fill out a [PR](/contributing/pull-requests) if you know what should be there instead.
|
||||
|
||||
# Submitting Issues
|
||||
|
||||
When you're submitting an issue, generally they fall into a few categories:
|
||||
|
||||
## Bug
|
||||
|
||||
We need some information to figure out what's going wrong. At a minimum, you need to tell us:
|
||||
|
||||
(1) What's supposed to happen
|
||||
|
||||
(2) What actually happened
|
||||
|
||||
(3) Steps to reproduce
|
||||
|
||||
|
||||
Stack traces and other useful information that you find make a bug report more likely to be fixed.
|
||||
|
||||
Consult the template for a bug report if you don't know or have questions about how to format this.
|
||||
|
||||
## Documentation
|
||||
|
||||
Depending on how you go about it, this can be done as a [Pull Request](../contributing/pull-requests) instead of an issue. Generally, we need to know what was wrong, what you changed, and how it improved the documentation if it isn't obvious.
|
||||
|
||||
We just need to know what's wrong. You should fill out a [PR](../contributing/pull-requests) if you know what should be there instead.
|
|
@ -1,77 +1,77 @@
|
|||
# Submitting Pull Requests
|
||||
|
||||
When submitting a Pull Request, there's a few reasons to do so:
|
||||
|
||||
|
||||
## Documentation
|
||||
|
||||
If there's something to change with the documentation, you should follow a similar format to this example:
|
||||
|
||||
An example of an appropriate typo-fixing PR would be:
|
||||
|
||||
>**Brief Description of your Changes**
|
||||
>
|
||||
>I fixed a couple of typos found in the /contributing/issues.md file.
|
||||
>
|
||||
>**Impact of your Changes**
|
||||
>
|
||||
>- Documentation is more clear and readable for the users.
|
||||
>
|
||||
>**Tests Performed**
|
||||
>
|
||||
>Ran `vitepress dev docs` and verified it was built successfully.
|
||||
>
|
||||
>**Additional Comments**
|
||||
>
|
||||
>[At Discretion]
|
||||
|
||||
## Change in Behavior
|
||||
|
||||
An example of an appropriate PR that adds a new feature would be:
|
||||
|
||||
>
|
||||
>**Brief Description of your Changes**
|
||||
>
|
||||
>I added `jecs.best_function`, which gives everyone who uses the module an immediate boost in concurrent player counts. (this is a joke)
|
||||
>
|
||||
>**Impact of your Changes**
|
||||
>
|
||||
>- jecs functionality is extended to better fit the needs of the community [explain why].
|
||||
>
|
||||
>**Tests Performed**
|
||||
>
|
||||
>Added a few test cases to ensure the function runs as expected [link to changes].
|
||||
>
|
||||
>**Additional Comments**
|
||||
>
|
||||
>[At Discretion]
|
||||
|
||||
## Addons
|
||||
|
||||
If you made something you think should be included into the [addons page](/learn/concepts/addons), let us know!
|
||||
|
||||
We have tons of examples of libraries and other tools which can be used in conjunction with jecs on this page.
|
||||
|
||||
One example of a PR that would be accepted is:
|
||||
|
||||
>**Brief Description of your Changes**
|
||||
>
|
||||
>I added [jecs observers](/learn/concepts/addons#jecs_observers) to the addons page.
|
||||
>
|
||||
>**Impact of your Changes**
|
||||
>
|
||||
>- jecs observers are a different and important way of handling queries which benefit the users of jecs by [explain why your tool benefits users here]
|
||||
>
|
||||
>- [talk about why you went with this design instead of maybe an alternative]
|
||||
>
|
||||
>**Tests Performed**
|
||||
>
|
||||
> I used this tool in conjunction with jecs and ensured it works as expected.
|
||||
>
|
||||
> [If you wrote unit tests for your tool, mention it here.]
|
||||
>
|
||||
>**Additional Comments**
|
||||
>
|
||||
>[At Discretion]
|
||||
|
||||
Keep in mind the list on the addons page is *not* exhaustive. If you came up with a tool that doesn't fit into any of the categories listed, we still want to hear from you!
|
||||
# Submitting Pull Requests
|
||||
|
||||
When submitting a Pull Request, there's a few reasons to do so:
|
||||
|
||||
|
||||
## Documentation
|
||||
|
||||
If there's something to change with the documentation, you should follow a similar format to this example:
|
||||
|
||||
An example of an appropriate typo-fixing PR would be:
|
||||
|
||||
>**Brief Description of your Changes**
|
||||
>
|
||||
>I fixed a couple of typos found in the /contributing/issues.md file.
|
||||
>
|
||||
>**Impact of your Changes**
|
||||
>
|
||||
>- Documentation is more clear and readable for the users.
|
||||
>
|
||||
>**Tests Performed**
|
||||
>
|
||||
>Ran `vitepress dev docs` and verified it was built successfully.
|
||||
>
|
||||
>**Additional Comments**
|
||||
>
|
||||
>[At Discretion]
|
||||
|
||||
## Change in Behavior
|
||||
|
||||
An example of an appropriate PR that adds a new feature would be:
|
||||
|
||||
>
|
||||
>**Brief Description of your Changes**
|
||||
>
|
||||
>I added `jecs.best_function`, which gives everyone who uses the module an immediate boost in concurrent player counts. (this is a joke)
|
||||
>
|
||||
>**Impact of your Changes**
|
||||
>
|
||||
>- jecs functionality is extended to better fit the needs of the community [explain why].
|
||||
>
|
||||
>**Tests Performed**
|
||||
>
|
||||
>Added a few test cases to ensure the function runs as expected [link to changes].
|
||||
>
|
||||
>**Additional Comments**
|
||||
>
|
||||
>[At Discretion]
|
||||
|
||||
## Addons
|
||||
|
||||
If you made something you think should be included into the [resources page](../../resources), let us know!
|
||||
|
||||
We have tons of examples of libraries and other tools which can be used in conjunction with jecs on this page.
|
||||
|
||||
One example of a PR that would be accepted is:
|
||||
|
||||
>**Brief Description of your Changes**
|
||||
>
|
||||
>I added `jecs observers` to the addons page.
|
||||
>
|
||||
>**Impact of your Changes**
|
||||
>
|
||||
>- jecs observers are a different and important way of handling queries which benefit the users of jecs by [explain why your tool benefits users here]
|
||||
>
|
||||
>- [talk about why you went with this design instead of maybe an alternative]
|
||||
>
|
||||
>**Tests Performed**
|
||||
>
|
||||
> I used this tool in conjunction with jecs and ensured it works as expected.
|
||||
>
|
||||
> [If you wrote unit tests for your tool, mention it here.]
|
||||
>
|
||||
>**Additional Comments**
|
||||
>
|
||||
>[At Discretion]
|
||||
|
||||
Keep in mind the list on the addons page is *not* exhaustive. If you came up with a tool that doesn't fit into any of the categories listed, we still want to hear from you!
|
|
@ -1,3 +0,0 @@
|
|||
## TODO
|
||||
|
||||
This is a TODO stub.
|
664
docs/learn/overview.md
Normal file
664
docs/learn/overview.md
Normal file
|
@ -0,0 +1,664 @@
|
|||
# Introduction
|
||||
Jecs is a standalone entity-component-system module written in Luau.
|
||||
ECS ("entity-component-system") describes one way to write games in a more data oriented design.
|
||||
|
||||
# Hello World, Entity and Component
|
||||
It all has to start somewhere. A world stores entities and their components, and manages them. This tour will reference it for every operation.
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
local jecs = require(path/to/jecs)
|
||||
local world = jecs.world()
|
||||
```
|
||||
```typescript [typescript]
|
||||
import { World } from "@rbxts/jecs"
|
||||
const world = new World()
|
||||
// creates a new entity with no components and returns its identifier
|
||||
const entity = world.entity()
|
||||
|
||||
// deletes an entity and all its components
|
||||
world.delete(entity)
|
||||
```
|
||||
:::
|
||||
|
||||
## Entities
|
||||
|
||||
Entities represent things in a game. In a game there may be entities of characters, buildings, projectiles, particle effects etc.
|
||||
|
||||
By itself, an entity is just an unique entity identifier without any data. An entity identifier contains information about the entity itself and its generation.
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
-- creates a new entity with no components and returns its identifier
|
||||
local entity = world:entity()
|
||||
|
||||
-- deletes an entity and all its components
|
||||
world:delete(entity)
|
||||
```
|
||||
```typescript [typescript]
|
||||
// creates a new entity with no components and returns its identifier
|
||||
const entity = world.entity()
|
||||
|
||||
// deletes an entity and all its components
|
||||
world.delete(entity)
|
||||
```
|
||||
:::
|
||||
|
||||
The `entity` member function also accepts an overload that allows you to create an entity with a desired id which bypasses the [`entity range`](#Entity-Ranges).
|
||||
|
||||
## Components
|
||||
|
||||
A component is something that is added to an entity. Components can simply tag an entity ("this entity is an `Npc`"), attach data to an entity ("this entity is at `Position` `Vector3.new(10, 20, 30)`") and create relationships between entities ("bob `Likes` alice") that may also contain data ("bob `Eats` `10` apples").
|
||||
|
||||
## Operations
|
||||
|
||||
| Operation | Description |
|
||||
| --------- | ---------------------------------------------------------------------------------------------- |
|
||||
| `get` | Get a specific component or set of components from an entity. |
|
||||
| `add` | Adds component to an entity. If entity already has the component, `add` does nothing. |
|
||||
| `set` | Sets the value of a component for an entity. `set` behaves as a combination of `add` and `get` |
|
||||
| `remove` | Removes component from entity. If entity doesn't have the component, `remove` does nothing. |
|
||||
| `clear` | Remove all components from an entity. Clearing is more efficient than removing one by one. |
|
||||
|
||||
## Components are entities
|
||||
|
||||
In an ECS, components need to be uniquely identified. In Jecs this is done by making each component its own unique entity. This means that everything is customizable. Components are no exception
|
||||
and all of the APIs that apply to regular entities also apply to component entities.
|
||||
|
||||
If a game has a component Position and Velocity, there will be two entities, one for each component. Component entities can be distinguished from "regular" entities as they have a `Component` component trait.
|
||||
|
||||
::: code-group
|
||||
```luau [luau]
|
||||
local Position = world:component() :: jecs.Entity<Vector3>
|
||||
world:set(Position, jecs.Name, "Position") -- Using regular apis to set metadata on component entities!
|
||||
|
||||
print(`{world:get(Position, jecs.Name)} is a Component: {world:has(Position, jecs.Component)}`);
|
||||
|
||||
-- Output:
|
||||
-- Position is a Component: true
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Position = world.component<Vector3>();
|
||||
world.set(Position, jecs.Name, "Position") // Using regular apis to set metadata on component entities!
|
||||
|
||||
print(`${world.get(Position, jecs.Name)} is a Component: ${world.has(Position, jecs.Component)}`);
|
||||
// Output:
|
||||
// Position is a Component: true
|
||||
```
|
||||
:::
|
||||
|
||||
### Hooks
|
||||
|
||||
Component data generally need to adhere to a specific interface, and sometimes requires side effects to run upon certain lifetime cycles. In `jecs`, there are hooks which are `component traits`, that can define the behaviour of a component and enforce invariants, but can only be invoked through mutations on the component data. You can only configure a single `OnAdd`, `OnRemove` and `OnChange` hook per component, just like you can only have a single constructor and destructor.
|
||||
|
||||
::: code-group
|
||||
```luau [luau]
|
||||
local Transform = world:component()
|
||||
world:set(Transform, OnAdd, function(entity)
|
||||
-- A transform component has been added to an entity
|
||||
end)
|
||||
world:set(Transform, OnRemove, function(entity)
|
||||
-- A transform component has been removed from the entity
|
||||
end)
|
||||
world:set(Transform, OnChange, function(entity, value)
|
||||
-- A transform component has been changed to value on the entity
|
||||
end)
|
||||
```
|
||||
```typescript [typescript]
|
||||
const Transform = world.component();
|
||||
world.set(Transform, OnAdd, (entity) => {
|
||||
// A transform component has been added to an entity
|
||||
});
|
||||
world.set(Transform, OnRemove, (entity) => {
|
||||
// A transform component has been removed from the entity
|
||||
});
|
||||
world.set(Transform, OnChange, (entity, value) => {
|
||||
// A transform component has been changed to value on the entity
|
||||
});
|
||||
```
|
||||
:::
|
||||
|
||||
### Cleanup Traits
|
||||
|
||||
When entities that are used as tags, components, relationships or relationship targets are deleted, cleanup traits ensure that the store does not contain any dangling references. Any cleanup policy provides this guarantee, so while they are configurable, games cannot configure traits that allows for dangling references.
|
||||
|
||||
We also want to specify this per relationship. If an entity has `(Likes, parent)` we may not want to delete that entity, meaning the cleanup we want to perform for `Likes` and `ChildOf` may not be the same.
|
||||
|
||||
This is what cleanup traits are for: to specify which action needs to be executed under which condition. They are applied to entities that have a reference to the entity being deleted: if I delete the `Archer` tag I remove the tag from all entities that have it.
|
||||
|
||||
To configure a cleanup policy for an entity, a `(Condition, Action)` pair can be added to it. If no policy is specified, the default cleanup action (`Remove`) is performed.
|
||||
|
||||
There are two cleanup actions:
|
||||
|
||||
- `Remove`: removes instances of the specified (component) id from all entities (default)
|
||||
- `Delete`: deletes all entities with specified id
|
||||
|
||||
There are two cleanup conditions:
|
||||
|
||||
- `OnDelete`: the component, tag or relationship is deleted
|
||||
- `OnDeleteTarget`: a target used with the relationship is deleted
|
||||
|
||||
#### (OnDelete, Remove)
|
||||
::: code-group
|
||||
```luau [luau]
|
||||
local Archer = world:component()
|
||||
world:add(Archer, pair(jecs.OnDelete, jecs.Remove))
|
||||
|
||||
local e = world:entity()
|
||||
world:add(e, Archer)
|
||||
|
||||
-- This will remove Archer from e
|
||||
world:delete(Archer)
|
||||
```
|
||||
```typescript [typescript]
|
||||
const Archer = world.component();
|
||||
world.add(Archer, pair(jecs.OnDelete, jecs.Remove));
|
||||
|
||||
const e = world.entity();
|
||||
world.add(e, Archer);
|
||||
|
||||
// This will remove Archer from e
|
||||
world.delete(Archer);
|
||||
```
|
||||
:::
|
||||
|
||||
#### (OnDelete, Delete)
|
||||
::: code-group
|
||||
```luau [luau]
|
||||
local Archer = world:component()
|
||||
world:add(Archer, pair(jecs.OnDelete, jecs.Delete))
|
||||
|
||||
local e = world:entity()
|
||||
world:add(e, Archer)
|
||||
|
||||
-- This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait
|
||||
world:delete(Archer)
|
||||
```
|
||||
```typescript [typescript]
|
||||
const Archer = world.component();
|
||||
world.add(Archer, pair(jecs.OnDelete, jecs.Delete));
|
||||
|
||||
const e = world.entity();
|
||||
world.add(e, Archer);
|
||||
|
||||
// This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait
|
||||
world.delete(Archer);
|
||||
```
|
||||
:::
|
||||
|
||||
#### (OnDeleteTarget, Remove)
|
||||
::: code-group
|
||||
```luau [luau]
|
||||
local OwnedBy = world:component()
|
||||
world:add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove))
|
||||
local loot = world:entity()
|
||||
local player = world:entity()
|
||||
world:add(loot, pair(OwnedBy, player))
|
||||
|
||||
-- This will remove (OwnedBy, player) from loot
|
||||
world:delete(player)
|
||||
```
|
||||
```typescript [typescript]
|
||||
const OwnedBy = world.component();
|
||||
world.add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove));
|
||||
const loot = world.entity();
|
||||
const player = world.entity();
|
||||
world.add(loot, pair(OwnedBy, player));
|
||||
|
||||
// This will remove (OwnedBy, player) from loot
|
||||
world.delete(player);
|
||||
```
|
||||
:::
|
||||
#### (OnDeleteTarget, Delete)
|
||||
::: code-group
|
||||
```luau [luau]
|
||||
local ChildOf = world:component()
|
||||
world:add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete))
|
||||
|
||||
local parent = world:entity()
|
||||
local child = world:entity()
|
||||
world:add(child, pair(ChildOf, parent))
|
||||
|
||||
-- This will delete both parent and child
|
||||
world:delete(parent)
|
||||
```
|
||||
```typescript [typescript]
|
||||
const ChildOf = world.component();
|
||||
world.add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete));
|
||||
|
||||
const parent = world.entity();
|
||||
const child = world.entity();
|
||||
world.add(child, pair(ChildOf, parent));
|
||||
|
||||
// This will delete both parent and child
|
||||
world.delete(parent);
|
||||
```
|
||||
:::
|
||||
|
||||
## Preregistration
|
||||
|
||||
By default, components being registered on runtime is useful for how dynamic it can be. But, sometimes being able to register components without having the world instance is useful.
|
||||
|
||||
::: code-group
|
||||
```luau [luau]
|
||||
local Position = jecs.component() :: jecs.Entity<Vector3>
|
||||
|
||||
jecs.world() -- Position gets registered here
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Position = jecs.component<Vector3>();
|
||||
|
||||
new World() // Position gets registered here
|
||||
```
|
||||
:::
|
||||
|
||||
However, if you try to set metadata, you will find that this doesn't work without the world instance. Instead, jecs offers a `meta` member function that can forward declare its metadata.
|
||||
|
||||
::: code-group
|
||||
```luau [luau]
|
||||
jecs.meta(Position, jecs.Name, "Position")
|
||||
|
||||
jecs.world() -- Position gets registered here with its name "Position"
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
jecs.meta(Position, jecs.Name, "Position")
|
||||
|
||||
new World() // Position gets registered here with its name "Position"
|
||||
```
|
||||
:::
|
||||
|
||||
### Singletons
|
||||
|
||||
Singletons are components for which only a single instance
|
||||
exists on the world. They can be accessed on the
|
||||
world directly and do not require providing an entity.
|
||||
Singletons are useful for global game resources, such as
|
||||
game state, a handle to a physics engine or a network socket. An example:
|
||||
|
||||
::: code-group
|
||||
```luau [luau]
|
||||
local TimeOfDay = world:component() :: jecs.Entity<number>
|
||||
world:set(TimeOfDay, TimeOfDay, 0.5)
|
||||
local t = world:get(TimeOfDay, TimeOfDay)
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const TimeOfDay = world.component<number>();
|
||||
world.set(TimeOfDay, TimeOfDay, 0.5);
|
||||
const t = world.get(TimeOfDay, TimeOfDay);
|
||||
```
|
||||
:::
|
||||
|
||||
# Queries
|
||||
|
||||
Queries enable games to quickly find entities that satifies provided conditions.
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
for _ in world:query(Position, Velocity) do end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
for (const [_] of world.query(Position, Velocity)) {
|
||||
}
|
||||
```
|
||||
:::
|
||||
|
||||
In `jecs`, queries can do anything from returning entities that match a simple list of components, to matching against entity graphs.
|
||||
|
||||
This manual contains a full overview of the query features available in Jecs. Some of the features of Jecs queries are:
|
||||
|
||||
- Queries have support for relationships pairs which allow for matching against entity graphs without having to build complex data structures for it.
|
||||
- Queries support filters such as [`query:with(...)`](../api/query.md#with) if entities are required to have the components but you don’t actually care about components value. And [`query:without(...)`](../api/query.md#without) which selects entities without the components.
|
||||
- Queries can be drained or reset on when called, which lets you choose iterator behaviour.
|
||||
- Queries can be called with any ID, including entities created dynamically, this is useful for pairs.
|
||||
- Queries are already fast but can be futher inlined via [`query:archetypes()`](../api/query.md#archetypes) for maximum performance to eliminate function call overhead which is roughly 60-80% of the cost for iteration.
|
||||
|
||||
## Performance and Caching
|
||||
|
||||
Understanding the basic architecture of queries helps to make the right tradeoffs when using queries in games.
|
||||
The biggest impact on query performance is whether a query is cached or not.
|
||||
This section goes over what caching is, how it can be used and when it makes sense to use it.
|
||||
|
||||
### Caching: what is it?
|
||||
|
||||
Jecs is an archetype ECS, which means that entities with exactly the same components are
|
||||
grouped together in an "archetype". Archetypes are created on the fly
|
||||
whenever a new component combination is created in the ECS. For example:
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
local e1 = world:entity()
|
||||
world:set(e1, Position, Vector3.new(10, 20, 30)) -- create archetype [Position]
|
||||
world:set(e1, Velocity, Vector3.new(1, 2, 3)) -- create archetype [Position, Velocity]
|
||||
|
||||
local e2 = world:entity()
|
||||
world:set(e2, Position, Vector3.new(10, 20, 30)) -- archetype [Position] already exists
|
||||
world:set(e2, Velocity, Vector3.new(1, 2, 3)) -- archetype [Position, Velocity] already exists
|
||||
world:set(e3, Mass, 100) -- create archetype [Position, Velocity, Mass]
|
||||
|
||||
-- e1 is now in archetype [Position, Velocity]
|
||||
-- e2 is now in archetype [Position, Velocity, Mass]
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const e1 = world.entity();
|
||||
world.set(e1, Position, new Vector3(10, 20, 30)); // create archetype [Position]
|
||||
world.set(e1, Velocity, new Vector3(1, 2, 3)); // create archetype [Position, Velocity]
|
||||
|
||||
const e2 = world.entity();
|
||||
world.set(e2, Position, new Vector3(10, 20, 30)); // archetype [Position] already exists
|
||||
world.set(e2, Velocity, new Vector3(1, 2, 3)); // archetype [Position, Velocity] already exists
|
||||
world.set(e3, Mass, 100); // create archetype [Position, Velocity, Mass]
|
||||
|
||||
// e1 is now in archetype [Position, Velocity]
|
||||
// e2 is now in archetype [Position, Velocity, Mass]
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Archetypes are important for queries. Since all entities in an archetype have the same components, and a query matches entities with specific components, a query can often match entire archetypes instead of individual entities. This is one of the main reasons why queries in an archetype ECS are fast.
|
||||
|
||||
The second reason that queries in an archetype ECS are fast is that they are cheap to cache. While an archetype is created for each unique component combination, games typically only use a finite set of component combinations which are created quickly after game assets are loaded.
|
||||
|
||||
This means that instead of searching for archetypes each time a query is evaluated, a query can instead cache the list of matching archetypes. This is a cheap cache to maintain: even though entities can move in and out of archetypes, the archetypes themselves are often stable.
|
||||
|
||||
If none of that made sense, the main thing to remember is that a cached query does not actually have to search for entities. Iterating a cached query just means iterating a list of prematched results, and this is really, really fast.
|
||||
|
||||
### Tradeoffs
|
||||
|
||||
Jecs has both cached and uncached queries. If cached queries are so fast, why even bother with uncached queries? There are four main reasons:
|
||||
|
||||
- Cached queries are really fast to iterate, but take more time to create because the cache must be initialized first.
|
||||
- Cached queries add overhead to archetype creation/deletion, as these changes have to get propagated to caches.
|
||||
- While caching archetypes is fast, some query features require matching individual entities, which are not efficient to cache (and aren't cached).
|
||||
|
||||
As a rule of thumb, if you have a query that is evaluated each frame (as is typically the case with systems), they will benefit from being cached. If you need to create a query ad-hoc, an uncached query makes more sense.
|
||||
|
||||
Ad-hoc queries are often necessary when a game needs to find entities that match a condition that is only known at runtime, for example to find all child entities for a specific parent.
|
||||
|
||||
### Components
|
||||
|
||||
A component is any single ID that can be added to an entity. This includes tags and regular entities, which are IDs that do not have the builtin `Component` component. To match a query, an entity must have all the requested components. An example:
|
||||
|
||||
```luau
|
||||
local e1 = world:entity()
|
||||
world:add(e1, Position)
|
||||
|
||||
local e2 = world:entity()
|
||||
world:add(e2, Position)
|
||||
world:add(e2, Velocity)
|
||||
|
||||
local e3 = world:entity()
|
||||
world:add(e3, Position)
|
||||
world:add(e3, Velocity)
|
||||
world:add(e3, Mass)
|
||||
|
||||
```
|
||||
|
||||
Only entities `e2` and `e3` match the query Position, Velocity.
|
||||
|
||||
### Wildcards
|
||||
|
||||
Jecs currently only supports the `Any` type of wildcards which a single result for the first component that it matches.
|
||||
|
||||
When using the `Any` type wildcard it is undefined which component will be matched, as this can be influenced by other parts of the query. It is guaranteed that iterating the same query twice on the same dataset will produce the same result.
|
||||
|
||||
If you want to iterate multiple targets for the same relation on a pair, then use [`world:target`](../api/world.md#target)
|
||||
|
||||
Wildcards are particularly useful when used in combination with pairs (next section).
|
||||
|
||||
### Pairs
|
||||
|
||||
A pair is an ID that encodes two elements. Pairs, like components, can be added to entities and are the foundation for [`Relationships`](#relationships).
|
||||
|
||||
The elements of a pair are allowed to be wildcards. When a query pair returns an `Any` type wildcard, the query returns at most a single matching pair on an entity.
|
||||
|
||||
The following sections describe how to create queries for pairs in the different language bindings.
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
local Likes = world:entity()
|
||||
local bob = world:entity()
|
||||
for _ in world:query(pair(Likes, bob)) do end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Likes = world.entity();
|
||||
const bob = world.entity();
|
||||
for (const [_] of world.query(pair(Likes, bob))) {
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
When a query pair contains a wildcard, the `world:target()` function can be used to determine the target of the pair element that matched the query:
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
for id in world:query(pair(Likes, jecs.Wildcard)) do
|
||||
print(`entity {getName(id)} likes {getName(world, world:target(id, Likes))}`)
|
||||
end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Likes = world.entity();
|
||||
const bob = world.entity();
|
||||
for (const [_] of world.query(pair(Likes, jecs.Wildcard))) {
|
||||
print(`entity ${getName(id)} likes ${getName(world.target(id, Likes))}`);
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Filters
|
||||
|
||||
Filters are extensions to queries which allow you to select entities from a more complex pattern but you don't actually care about the component values.
|
||||
|
||||
The following filters are supported by queries:
|
||||
|
||||
| Identifier | Description |
|
||||
| ---------- | ----------------------------------- |
|
||||
| With | Must match with all terms. |
|
||||
| Without | Must not match with provided terms. |
|
||||
|
||||
## Relationships
|
||||
Relationships makes it possible to describe entity graphs natively in ECS.
|
||||
|
||||
Adding/removing relationships is similar to adding/removing regular components, with as difference that instead of a single component id, a relationship adds a pair of two things to an entity. In this pair, the first element represents the relationship (e.g. "Eats"), and the second element represents the relationship target (e.g. "Apples").
|
||||
|
||||
Relationships can be used to describe many things, from hierarchies to inventory systems to trade relationships between players in a game. The following sections go over how to use relationships, and what features they support.
|
||||
|
||||
### Definitions
|
||||
|
||||
Name | Description
|
||||
----------|------------
|
||||
Id | An id that can be added and removed
|
||||
Component | Id with a single element (same as an entity id)
|
||||
Relationship | Used to refer to first element of a pair
|
||||
Target | Used to refer to second element of a pair
|
||||
Source | Entity to which an id is added
|
||||
|
||||
### Relationship queries
|
||||
There are a number of ways a game can query for relationships. The following kinds of queries are available for all (unidirectional) relationships, and are all constant time:
|
||||
|
||||
Test if entity has a relationship pair
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
world:has(bob, pair(Eats, Apples))
|
||||
```
|
||||
```typescript [typescript]
|
||||
world.has(bob, pair(Eats, Apples))
|
||||
```
|
||||
:::
|
||||
|
||||
Test if entity has a relationship wildcard
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
world:has(bob, pair(Eats, jecs.Wildcard)
|
||||
```
|
||||
```typescript [typescript]
|
||||
world.has(bob, pair(Eats, jecs.Wildcard)
|
||||
```
|
||||
:::
|
||||
|
||||
Get parent for entity
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
world:parent(bob)
|
||||
```
|
||||
```typescript [typescript]
|
||||
world.parent(bob)
|
||||
```
|
||||
:::
|
||||
|
||||
Find first target of a relationship for entity
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
world:target(bob, Eats)
|
||||
```
|
||||
```typescript [typescript]
|
||||
world.target(bob, Eats)
|
||||
```
|
||||
:::
|
||||
|
||||
Find all entities with a pair
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
for id in world:query(pair(Eats, Apples)) do
|
||||
-- ...
|
||||
end
|
||||
```
|
||||
```typescript [typescript]
|
||||
for (const [id] of world.query(pair(Eats, Apples)) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
:::
|
||||
|
||||
Find all entities with a pair wildcard
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
for id in world:query(pair(Eats, jecs.Wildcard)) do
|
||||
local food = world:target(id, Eats) -- Apples, ...
|
||||
end
|
||||
```
|
||||
```typescript [typescript]
|
||||
for (const [id] of world.query(pair(Eats, jecs.Wildcard)) {
|
||||
const food = world.target(id, Eats) // Apples, ...
|
||||
}
|
||||
```
|
||||
:::
|
||||
|
||||
Iterate all children for a parent
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
for child in world:query(pair(jecs.ChildOf, parent)) do
|
||||
-- ...
|
||||
end
|
||||
```
|
||||
```typescript [typescript]
|
||||
for (const [child] of world.query(pair(jecs.ChildOf, parent)) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
:::
|
||||
|
||||
### Relationship components
|
||||
|
||||
Relationship pairs, just like regular component, can be associated with data.
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
local Position = world:component()
|
||||
local Eats = world:component()
|
||||
local Apples = world:entity()
|
||||
local Begin = world:entity()
|
||||
local End = world:entity()
|
||||
|
||||
local e = world:entity()
|
||||
world:set(e, pair(Eats, Apples), { amount = 1 })
|
||||
|
||||
world:set(e, pair(Begin, Position), Vector3.new(0, 0, 0))
|
||||
world:set(e, pair(End, Position), Vector3.new(10, 20, 30))
|
||||
|
||||
world:add(e, jecs.ChildOf, Position)
|
||||
|
||||
```
|
||||
```typescript [typescript]
|
||||
const Position = world.component()
|
||||
const Eats = world.component()
|
||||
const Apples = world.entity()
|
||||
const Begin = world.entity()
|
||||
const End = world.entity()
|
||||
|
||||
const e = world.entity()
|
||||
world.set(e, pair(Eats, Apples), { amount: 1 })
|
||||
|
||||
world.set(e, pair(Begin, Position), new Vector3(0, 0, 0))
|
||||
world.set(e, pair(End, Position), new Vector3(10, 20, 30))
|
||||
|
||||
world.add(e, jecs.ChildOf, Position)
|
||||
```
|
||||
:::
|
||||
|
||||
### Relationship wildcards
|
||||
|
||||
When querying for relationship pairs, it is often useful to be able to find all instances for a given relationship or target. To accomplish this, an game can use wildcard expressions.
|
||||
|
||||
Wildcards may used for the relationship or target part of a pair
|
||||
|
||||
```luau
|
||||
pair(Likes, jecs.Wildcard) -- Matches all Likes relationships
|
||||
pair(jecs.Wildcard, Alice) -- Matches all relationships with Alice as target
|
||||
```
|
||||
|
||||
### Relationship performance
|
||||
The ECS storage needs to know two things in order to store components for entities:
|
||||
- Which IDs are associated with an entity
|
||||
- Which types are associated with those ids
|
||||
Ids represent anything that can be added to an entity. An ID that is not associated with a type is called a tag. An ID associated with a type is a component. For regular components, the ID is a regular entity that has the builtin `Component` component.
|
||||
|
||||
### Storing relationships
|
||||
Relationships do not fundamentally change or extend the capabilities of the storage. Relationship pairs are two elements encoded into a single 53-bit ID, which means that on the storage level they are treated the same way as regular component IDs. What changes is the function that determines which type is associated with an id. For regular components this is simply a check on whether an entity has `Component`. To support relationships, new rules are added to determine the type of an id.
|
||||
|
||||
Because of this, adding/removing relationships to entities has the same performance as adding/removing regular components. This becomes more obvious when looking more closely at a function that adds a relationship pair.
|
||||
|
||||
### Id ranges
|
||||
Jecs reserves entity ids under a threshold (HI_COMPONENT_ID, default is 256) for components. This low id range is used by the storage to more efficiently encode graph edges between archetypes. Graph edges for components with low ids use direct array indexing, whereas graph edges for high ids use a hashmap. Graph edges are used to find the next archetype when adding/removing component ids, and are a contributing factor to the performance overhead of add/remove operations.
|
||||
|
||||
Because of the way pair IDs are encoded, a pair will never be in the low id range. This means that adding/removing a pair ID always uses a hashmap to find the next archetype. This introduces a small overhead.
|
||||
|
||||
### Fragmentation
|
||||
Fragmentation is a property of archetype-based ECS implementations where entities are spread out over more archetypes as the number of different component combinations increases. The overhead of fragmentation is visible in two areas:
|
||||
- Archetype creation
|
||||
- Queries (queries have to match & iterate more archetypes)
|
||||
Games that make extensive use of relationships might observe high levels of fragmentation, as relationships can introduce many different combinations of components. While the Jecs storage is optimized for supporting large amounts (hundreds of thousands) of archetypes, fragmentation is a factor to consider when using relationships.
|
||||
|
||||
Union relationships are planned along with other improvements to decrease the overhead of fragmentation introduced by relationships.
|
||||
|
||||
### Archetype Creation
|
||||
|
||||
When an ID added to an entity is deleted, all references to that ID are deleted from the storage. For example, when the component Position is deleted it is removed from all entities, and all archetypes with the Position component are deleted. While not unique to relationships, it is more common for relationships to trigger cleanup actions, as relationship pairs contain regular entities.
|
||||
|
||||
The opposite is also true. Because relationship pairs can contain regular entities which can be created on the fly, archetype creation is more common than in games that do not use relationships. While Jecs is optimized for fast archetypes creation, creating and cleaning up archetypes is inherently more expensive than creating/deleting an entity. Therefore archetypes creation is a factor to consider, especially for games that make extensive use of relationships.
|
||||
|
||||
### Indexing
|
||||
|
||||
To improve the speed of evaluating queries, Jecs has indices that store all archetypes for a given component ID. Whenever a new archetype is created, it is registered with the indices for the IDs the archetype has, including IDs for relationship pairs.
|
||||
|
||||
While registering an archetype for a relationship index is not more expensive than registering an archetype for a regular index, an archetype with relationships has to also register itself with the appropriate wildcard indices for its relationships. For example, an archetype with relationship `pair(Likes, Apples)` registers itself with the `pair(Likes, Apples)`, `pair(Likes, jecs.Wildcard)` and `pair(jecs.Wildcard, Apples)` indices. For this reason, creating new archetypes with relationships has a higher overhead than an archetype without relationships.
|
||||
|
||||
This page takes wording and terminology directly from Flecs, the first ECS with full support for [Entity Relationships](https://www.flecs.dev/flecs/md_docs_2Relationships.html).
|
|
@ -1,71 +0,0 @@
|
|||
# First Jecs project
|
||||
|
||||
Now that you have installed Jecs, you can create your [World](https://ukendio.github.io/jecs/api/world.html).
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
local jecs = require(path/to/jecs)
|
||||
local world = jecs.World.new()
|
||||
```
|
||||
```typescript [typescript]
|
||||
import { World } from "@rbxts/jecs"
|
||||
const world = new World()
|
||||
```
|
||||
:::
|
||||
|
||||
Let's create a couple components.
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
local jecs = require(path/to/jecs)
|
||||
local world = jecs.World.new()
|
||||
|
||||
local Position = world:component()
|
||||
local Velocity = world:component()
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
import { World } from "@rbxts/jecs"
|
||||
const world = new World()
|
||||
|
||||
const Position = world.component()
|
||||
const Velocity = world.component()
|
||||
```
|
||||
:::
|
||||
|
||||
Systems can be as simple as a query in a function or a more contextualized construct. Let's make a system that moves an entity and decelerates over time.
|
||||
|
||||
:::code-group
|
||||
```luau [luau]
|
||||
local jecs = require(path/to/jecs)
|
||||
local world = jecs.World.new()
|
||||
|
||||
local Position = world:component()
|
||||
local Velocity = world:component()
|
||||
|
||||
for id, position, velocity in world:query(Position, Velocity) do
|
||||
world:set(id, Position, position + velocity)
|
||||
world:set(id, Velocity, velocity * 0.9)
|
||||
end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
import { World } from "@rbxts/jecs"
|
||||
const world = new World()
|
||||
|
||||
const Position = world.component()
|
||||
const Velocity = world.component()
|
||||
|
||||
for (const [id, position, velocity] of world.query(Position, Velocity)) {
|
||||
world.set(id, Position, position.add(velocity))
|
||||
world.set(id, Velocity, velocity.mul(0.9))
|
||||
}
|
||||
```
|
||||
:::
|
||||
|
||||
## Where To Get Help
|
||||
|
||||
If you are encountering problems, there are resources for you to get help:
|
||||
- [Roblox OSS Discord server](https://discord.gg/h2NV8PqhAD) has a [#jecs](https://discord.com/channels/385151591524597761/1248734074940559511) thread under the [#projects](https://discord.com/channels/385151591524597761/1019724676265676930) channel
|
||||
- [Open an issue](https://github.com/ukendio/jecs/issues) if you run into bugs or have feature requests
|
||||
- Dive into the nitty gritty in the [thesis paper](https://raw.githubusercontent.com/Ukendio/jecs/main/thesis/drafts/1/paper.pdf)
|
|
@ -1,130 +0,0 @@
|
|||
# Getting Started
|
||||
|
||||
## Installation
|
||||
|
||||
### Installing Standalone
|
||||
|
||||
Navigate to the [releases page](https://github.com/Ukendio/jecs/releases) and download `jecs.rbxm` from the assets.
|
||||
|
||||

|
||||
|
||||
### Using Wally
|
||||
|
||||
Add the following to your wally configuration:
|
||||
|
||||
::: code-group
|
||||
|
||||
```toml [wally.toml]
|
||||
jecs = "ukendio/jecs@0.5.3"
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Using npm (roblox-ts)
|
||||
|
||||
Use one of the following commands on your root project directory:
|
||||
|
||||
::: code-group
|
||||
```bash [npm]
|
||||
npm i https://github.com/Ukendio/jecs.git
|
||||
```
|
||||
```bash [yarn]
|
||||
yarn add https://github.com/Ukendio/jecs.git
|
||||
```
|
||||
```bash [pnpm]
|
||||
pnpm add https://github.com/Ukendio/jecs.git
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Example Usage
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [Luau]
|
||||
local world = jecs.World.new()
|
||||
local pair = jecs.pair
|
||||
local Wildcard = jecs.Wildcard
|
||||
|
||||
local Name = world:component()
|
||||
|
||||
local function getName(e)
|
||||
return world:get(e, Name)
|
||||
end
|
||||
|
||||
local Eats = world:component()
|
||||
|
||||
-- Relationship objects
|
||||
local Apples = world:component()
|
||||
-- components are entities, so you can add components to components
|
||||
world:set(Apples, Name, "apples")
|
||||
local Oranges = world:component()
|
||||
world:set(Oranges, Name, "oranges")
|
||||
|
||||
local bob = world:entity()
|
||||
-- Pairs can be constructed from two entities
|
||||
|
||||
world:set(bob, pair(Eats, Apples), 10)
|
||||
world:set(bob, pair(Eats, Oranges), 5)
|
||||
world:set(bob, Name, "bob")
|
||||
|
||||
local alice = world:entity()
|
||||
world:set(alice, pair(Eats, Apples), 4)
|
||||
world:set(alice, Name, "alice")
|
||||
|
||||
for id, amount in world:query(pair(Eats, Wildcard)) do
|
||||
-- get the second target of the pair
|
||||
local food = world:target(id, Eats)
|
||||
print(string.format("%s eats %d %s", getName(id), amount, getName(food)))
|
||||
end
|
||||
|
||||
-- Output:
|
||||
-- bob eats 10 apples
|
||||
-- bob eats 5 pears
|
||||
-- alice eats 4 apples
|
||||
```
|
||||
|
||||
|
||||
```ts [Typescript]
|
||||
import { Wildcard, pair, World } from "@rbxts/jecs"
|
||||
|
||||
|
||||
const world = new World()
|
||||
const Name = world.component()
|
||||
function getName(e) {
|
||||
return world.get(e, Name)
|
||||
}
|
||||
|
||||
const Eats = world.component()
|
||||
|
||||
// Relationship objects
|
||||
const Apples = world.component()
|
||||
// components are entities, so you can add components to components
|
||||
world.set(Apples, Name, "apples")
|
||||
const Oranges = world.component()
|
||||
world.set(Oranges, Name, "oranges")
|
||||
|
||||
const bob = world.entity()
|
||||
// Pairs can be constructed from two entities
|
||||
|
||||
world.set(bob, pair(Eats, Apples), 10)
|
||||
world.set(bob, pair(Eats, Oranges), 5)
|
||||
world.set(bob, Name, "bob")
|
||||
|
||||
const alice = world.entity()
|
||||
world.set(alice, pair(Eats, Apples), 4)
|
||||
world.set(alice, Name, "alice")
|
||||
|
||||
for (const [id, amount] of world.query(pair(Eats, Wildcard))) {
|
||||
// get the second target of the pair
|
||||
const food = world:target(id, Eats)
|
||||
print(string.format("%s eats %d %s", getName(id), amount, getName(food)))
|
||||
}
|
||||
|
||||
// Output:
|
||||
// bob eats 10 apples
|
||||
// bob eats 5 pears
|
||||
// alice eats 4 apples
|
||||
|
||||
```
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 34 KiB |
|
@ -1,11 +1,7 @@
|
|||
# Guides
|
||||
|
||||
ECS is a very foreign concept. Here's a few resources that the community has compiled about how to use ECS and some of its design choices.
|
||||
|
||||
See something missing? [Let us know.](/contributing/pull-requests)
|
||||
|
||||
## Blogs
|
||||
## Learning
|
||||
|
||||
- [Jecs Demo](https://github.com/Ukendio/jecs/tree/main/demo)
|
||||
- [Jecs Examples](https://github.com/Ukendio/jecs/tree/main/examples)
|
||||
- [An Introduction to ECS for Robloxians - @Ukendio](https://devforum.roblox.com/t/all-about-entity-component-system/1664447)
|
||||
- [Entities, Components and Systems - Mark Jordan](https://medium.com/ingeniouslysimple/entities-components-and-systems-89c31464240d)
|
||||
- [Why Vanilla ECS is not enough - Sander Mertens](https://ajmmertens.medium.com/why-vanilla-ecs-is-not-enough-d7ed4e3bebe5)
|
||||
|
@ -21,9 +17,6 @@ See something missing? [Let us know.](/contributing/pull-requests)
|
|||
- [Why Storing State Machines in ECS is a Bad Idea - Sander Mertens](https://ajmmertens.medium.com/why-storing-state-machines-in-ecs-is-a-bad-idea-742de7a18e59)
|
||||
- [ECS back & forth - Michele Caini](https://skypjack.github.io/2019-02-14-ecs-baf-part-1/)
|
||||
- [Sparse Set - Geeks for Geeks](https://www.geeksforgeeks.org/sparse-set/)
|
||||
|
||||
## Videos
|
||||
|
||||
- [Taking the Entity-Component-System Architecture Seriously - @alice-i-cecile](https://www.youtube.com/watch?v=VpiprNBEZsk)
|
||||
- [Overwatch Gameplay Architecture and Netcode - Blizzard, GDC](https://www.youtube.com/watch?v=W3aieHjyNvw)
|
||||
- [Data-Oriented Design and C++ - Mike Acton, CppCon](https://www.youtube.com/watch?v=rX0ItVEVjHc)
|
||||
|
@ -33,17 +26,55 @@ See something missing? [Let us know.](/contributing/pull-requests)
|
|||
- [Culling the Battlefield: Data Oriented Design in Practice - DICE, GDC](https://www.gdcvault.com/play/1014491/Culling-the-Battlefield-Data-Oriented)
|
||||
- [Game Engine Entity/Object Systems - Bobby Anguelov](https://www.youtube.com/watch?v=jjEsB611kxs)
|
||||
- [Understanding Data Oriented Design for Entity Component Systems - Unity GDC](https://www.youtube.com/watch?v=0_Byw9UMn9g)
|
||||
|
||||
## Tutorials
|
||||
|
||||
- [Understanding Data Oriented Design - Unity](https://learn.unity.com/tutorial/part-1-understand-data-oriented-design?courseId=60132919edbc2a56f9d439c3&signup=true&uv=2020.1)
|
||||
|
||||
## Books
|
||||
|
||||
- [Data Oriented Design - Richard Fabian](https://www.dataorienteddesign.com/dodbook/dodmain.html)
|
||||
|
||||
## Other
|
||||
|
||||
- [Interactive app for browsing systems of City Skylines 2 - @Captain-Of-Coit](https://captain-of-coit.github.io/cs2-ecs-explorer/)
|
||||
- [Awesome Entity Component System (link collection related to ECS) - Jeongseok Lee](https://github.com/jslee02/awesome-entity-component-system)
|
||||
- [Hibitset - DOCS.RS](https://docs.rs/hibitset/0.6.3/hibitset/)
|
||||
|
||||
------------------
|
||||
|
||||
## Addons
|
||||
|
||||
A collection of third-party jecs addons made by the community. If you would like to share what you're working on, [submit a pull request](/learn/contributing/pull-requests#addons)!
|
||||
|
||||
### Development tools
|
||||
|
||||
#### [jabby](https://github.com/alicesaidhi/jabby)
|
||||
A jecs debugger with a string-based query language and entity editing capabilities.
|
||||
|
||||
#### [jecs_entity_visualiser](https://github.com/Ukendio/jecs/blob/main/addons/entity_visualiser.luau)
|
||||
A simple entity and component visualiser in the output
|
||||
|
||||
#### [jecs_lifetime_tracker](https://github.com/Ukendio/jecs/blob/main/addons/lifetime_tracker.luau)
|
||||
A tool for inspecting entity lifetimes
|
||||
|
||||
### Helpers
|
||||
|
||||
#### [jecs_observers](https://github.com/Ukendio/jecs/blob/main/addons/observers.luau)
|
||||
Observers for queries and signals for components
|
||||
|
||||
### Schedulers
|
||||
|
||||
#### [lockstep scheduler](https://gist.github.com/1Axen/6d4f78b3454cf455e93794505588354b)
|
||||
A simple fixed step system scheduler.
|
||||
|
||||
#### [rubine](https://github.com/Mark-Marks/rubine)
|
||||
An ergonomic, runtime agnostic scheduler for Jecs
|
||||
|
||||
#### [jam](https://github.com/revvy02/Jam)
|
||||
Provides hooks and a scheduler that implements jabby and a topographical runtime
|
||||
|
||||
#### [planck](https://github.com/YetAnotherClown/planck)
|
||||
An agnostic scheduler inspired by Bevy and Flecs, with core features including phases, pipelines, run conditions, and startup systems.
|
||||
Planck also provides plugins for Jabby, Matter Hooks, and more.
|
||||
|
||||
### Networking
|
||||
|
||||
#### [feces](https://github.com/NeonD00m/feces)
|
||||
A generalized replication system for jecs
|
||||
|
||||
### Input
|
||||
|
||||
#### [Axis](https://github.com/NeonD00m/axis)
|
||||
An agnostic, simple and versatile input library for ECS
|
|
@ -2650,7 +2650,7 @@ return {
|
|||
tag = (ECS_TAG :: any) :: <T>() -> Entity<T>,
|
||||
meta = (ECS_META :: any) :: <T>(id: Entity, id: Id<T>, value: T) -> Entity<T>,
|
||||
is_tag = (ecs_is_tag :: any) :: <T>(World, Id<T>) -> boolean,
|
||||
|
||||
|
||||
OnAdd = EcsOnAdd :: Entity<<T>(entity: Entity, id: Id<T>, data: T) -> ()>,
|
||||
OnRemove = EcsOnRemove :: Entity<(entity: Entity, id: Id) -> ()>,
|
||||
OnChange = EcsOnChange :: Entity<<T>(entity: Entity, id: Id<T>, data: T) -> ()>,
|
||||
|
|
Loading…
Reference in a new issue