Compare commits

...

54 commits
v0.6.0 ... main

Author SHA1 Message Date
dai
993d57741f
Re-add ECS_PAIR_* to typings (#241)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
* Add ECS_PAIR_* functions to typings

* Return simple numbers
2025-06-16 15:12:14 +02:00
dai
150fccd2ce
Fix regression with set (#242) 2025-06-16 15:12:01 +02:00
Marcus
8420d8832b
period
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-13 01:33:54 +02:00
Marcus
01c12fccaa
Update release.yaml 2025-06-13 01:32:44 +02:00
Marcus
29512d4351
Bump upload-artifact ver 2025-06-13 01:30:18 +02:00
Ukendio
582a1c25ba Bump
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-10 19:42:52 +02:00
Ukendio
6f6cc3b514 Fix overloads 2025-06-10 16:35:09 +02:00
Ukendio
90c963c55d 0.6.1 2025-06-10 16:16:04 +02:00
Ukendio
3174e8d80b Handle removal of (*, R) pairs 2025-06-10 16:16:04 +02:00
Ukendio
0fea5a259d Union entity types with number 2025-06-10 16:10:41 +02:00
Ukendio
46d363ad5f Initial commit with union 2025-06-10 16:10:41 +02:00
Ukendio
dab260f733 Cast numbers to Entity
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-07 02:36:34 +02:00
Ukendio
56b52286b8 Rework observers addon interface 2025-06-07 02:11:38 +02:00
dai
35b5f04a7c
Hook typing improvements (#236)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
* Fix hook callback typings

* Update docs

* Add specialization

* Simplify overloads

* Remove generic
2025-06-06 15:14:23 +02:00
dai
6ce796e7fd
Fix missing parens (#235) 2025-06-06 15:13:54 +02:00
Ukendio
8490dfd294 Prevent partial matching of destroyed archetype
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-06-06 00:38:58 +02:00
Luka
d505a0a38d
fix line endings (#234) 2025-06-05 22:48:13 +02:00
Marcus
e74924ec07
Fix line endings (#233) 2025-06-05 22:00:29 +02:00
Marcus
803616a005
Fix line endings on demo (#232)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-01 16:19:48 +02:00
Ukendio
3be946db0c Merge 2025-06-01 16:15:16 +02:00
Ukendio
0308367964 Merge branch 'main' of https://github.com/Ukendio/jecs 2025-06-01 16:15:01 +02:00
Ukendio
5b4f104dd4 Fix line endings 2025-06-01 16:11:32 +02:00
Ukendio
b73bb0daee Fix line endings 2025-06-01 16:11:32 +02:00
EncodedVenom
b669196a98
Change types for tag and is_tag fns
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-05-28 13:31:03 -04:00
EncodedVenom
c62db9f8c3
Cleanup README links and headers
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-27 14:39:48 -04:00
EncodedVenom
3b0ce599ef
Merge pull request #230 from Tazmondo/main
Fix typo in observers addon
2025-05-27 14:37:14 -04:00
Taran McVay
077030738a
fix typo, queyr -> query 2025-05-27 18:05:59 +01:00
EncodedVenom
740647104b
Merge pull request #229 from Ukendio/installation-guide
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
Add installation methods
2025-05-24 22:17:53 -04:00
EncodedVenom
93cbd2d287 Add installation methods 2025-05-24 16:38:53 -04:00
Ukendio
bb03e88d3d Fix contrived bug with observer
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-05-20 00:33:16 +02:00
Ukendio
5dba6e7bac Fix typescript example
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-18 23:05:26 +02:00
Ukendio
0541f80b5d Fix hyperlinks 2025-05-18 23:02:16 +02:00
Ukendio
fd685537ea Fix docs issues 2025-05-18 22:59:07 +02:00
Ukendio
8194b7db24 Update docs with new API
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-18 15:28:19 +02:00
Ukendio
457e4a270f Merge branch 'main' of https://github.com/Ukendio/jecs 2025-05-18 15:05:55 +02:00
Ukendio
00e7d87a1c Docs chernoboyl 2025-05-18 15:05:46 +02:00
EncodedVenom
f6f6cb569a
Link to workflow
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-17 20:30:52 -04:00
EncodedVenom
10110ac71c
Add unit test workflow status 2025-05-17 20:29:17 -04:00
EncodedVenom
6a5832db20
Merge pull request #228 from Ukendio/documentation-update
Add Guides
2025-05-17 20:07:02 -04:00
EncodedVenom
a9b45f13e5
Merge branch 'main' into documentation-update
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
2025-05-17 20:01:49 -04:00
EncodedVenom
8b8d5f715e ECS is foreign to everyone 2025-05-17 19:59:09 -04:00
EncodedVenom
27a00280fd The children yearn for the guides 2025-05-17 19:56:37 -04:00
Junjie
22877f3fc5
Allow world.add() to accept component, add world.entity overload (#225)
* fix: allow components for world.add in typescript

* fix: add overload for world.entity

* build: downgrade deps to v0.6.0

* fix: world.entity accepts entity instead of number

* fix: allow union undefined union to be passed in .add
2025-05-18 01:44:22 +02:00
EncodedVenom
c030d396af
docs: cleanup todo stubs, add code coverage reports, add examples, and pin introduction section (#227)
* Allow pre existing hooks for observer

* Cleanup some todo stubs

* move coverage reports

* use better link for addons

* code coverage page

* make Introduction sidebar visible on all pages and add a few relevant sections

---------

Co-authored-by: Ukendio <ukendio@gmail.com>
2025-05-17 22:35:00 +02:00
EncodedVenom
3866e1413f make Introduction sidebar visible on all pages and add a few relevant sections 2025-05-17 14:00:30 -04:00
EncodedVenom
296fe80987 code coverage page 2025-05-17 14:00:08 -04:00
EncodedVenom
39946609c7 use better link for addons 2025-05-17 13:59:58 -04:00
EncodedVenom
94a5c6f5e2 move coverage reports 2025-05-17 13:59:35 -04:00
EncodedVenom
ac4d9ade17 Cleanup some todo stubs 2025-05-17 13:59:19 -04:00
EncodedVenom
cbb4b84dc6 Merge branch 'main' of https://github.com/Ukendio/jecs 2025-05-16 18:57:55 -04:00
PepeElToro41
378a9a45ff
Fix hooks types (#226)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
* fix hooks types

* add generic types
2025-05-16 19:22:08 +02:00
Ukendio
a31db7b17b Cleanup changelog
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-05-10 23:27:35 +02:00
EncodedVenom
d37d0041d6 Merge branch 'main' of https://github.com/Ukendio/jecs 2025-05-08 17:03:20 -04:00
Ukendio
150afd784a Allow pre existing hooks for observer 2025-05-08 17:00:45 -04:00
56 changed files with 2443 additions and 3126 deletions

View file

@ -2,7 +2,7 @@ name: release
on:
push:
tags: ["v*"]
tags: ["v*", "workflow_dispatch"]
jobs:
build:
@ -22,7 +22,7 @@ jobs:
run: rojo build --output build.rbxm default.project.json
- name: Upload Build Artifact
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: build
path: build.rbxm
@ -38,7 +38,7 @@ jobs:
uses: actions/checkout@v4
- name: Download Jecs Build
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: build
path: build

View file

@ -1,228 +1,177 @@
# Jecs Changelog
# Changelog
All notable changes to this project will be documented in this file.
## Unreleased
The format is based on [Keep a Changelog][kac], and this project adheres to
[Semantic Versioning][semver].
[kac]: https://keepachangelog.com/en/1.1.0/
[semver]: https://semver.org/spec/v2.0.0.html
## [Unreleased]
## [0.6.0] - 2025-05-10
- `[world]`:
- Added `world:range` to restrict entity range
- Changed `world:entity` to accept the overload to create an entity at the desired id
- Changed `world:clear` to also look through the component record for the cleared `ID`
- Removes the cleared ID from every entity that has it
- Changed entity ID layouts by putting the index in the lower bits, which should make every world function 1-5 nanoseconds faster
- Fixed `world:delete` not removing every pair with an unalive target
- Specifically happened when you had at least two pairs of different relations with multiple targets each
- `[hooks]`:
- Replaced `OnSet` with `OnChange`
- The former was used to detect emplace/move actions. Now the behaviour for `OnChange` is that it will run only when the value has changed
- Changed `OnAdd` to specifically run after the data has been set for non-zero-sized components. Also returns the value that the component was set to
- This should allow a more lenient window for modifying data
- Changed `OnRemove` to lazily lookup which archetype the entity will move to
- Can now have interior structural changes within `OnRemove` hooks
- Optimized `world:has` for both single component and multiple component presence.
- This comes at the cost that it cannot check the component presence for more than 4 components at a time. If this is important, consider calling to this function multiple times.
## [0.5.0] - 2024-12-26
- `[world]`:
- Fixed `world:target` not giving adjacent pairs
- Added `world:each` to find entities with a specific Tag
- Added `world:children` to find children of entity
- `[query]`:
- Added `query:cached`
- Adds query cache that updates itself when an archetype matching the query gets created or deleted.
- `[luau]`:
- Changed how entities' types are inferred with user-defined type functions
- Changed `Pair<First, Second>` to return `Second` if `First` is a `Tag`; otherwise, returns `First`.
## [0.4.0] - 2024-11-17
- `[world]`:
- Added recycling to `world:entity`
- If you see much larger entity ids, that is because its generation has been incremented
- `[query]`:
- Removed `query:drain`
- The default behaviour is simply to drain the iterator
- Removed `query:next`
- Just call the iterator function returned by `query:iter` directly if you want to get the next results
- Removed `query:replace`
- `[luau]`:
- Fixed `query:archetypes` not taking `self`
- Changed so that the `jecs.Pair` type now returns the first element's type so you won't need to typecast anymore.
## [0.3.2] - 2024-10-01
- `[world]`:
- Changed `world:cleanup` to traverse a header type for graph edges. (Edit)
- Fixed a regression that occurred when you call `world:set` following a `world:remove` using the same component
- Remove explicit error in JECS_DEBUG for `world:target` when not applying an index parameter
- `[typescript]` :
- Fixed `world.set` with NoInfer<T>
## [0.3.1] - 2024-10-01
- `[world]`:
- Added an index parameter to `world:target`
- Added a way to change the components limit via `_G.JECS_HI_COMPONENT_ID`
- Set it to whatever number you want but try to make it as close to the number of components you will use as possible
- Make sure to set this before importing jecs or else it will not work
- Added debug mode, enable via setting `_G.JECS_DEBUG` to true
- Make sure to set this before importing jecs or else it will not work
- Added `world:cleanup` which is called to cleanup empty archetypes manually
- Changed `world:delete` to delete archetypes that are dependent on the passed entity
- Changed `world:delete` to delete entity's children before the entity to prevent cycles
- `[query]`:
- Fixed the iterator to not drain by default
- `[typescript]`
- Fixed entry point of the package.json file to be `src` rather than `src/init`
- Fixed `query.next` returning a query object whereas it would be expected to return a tuple containing the entity and the corresponding component values
- Exported `query.archetypes`
- Changed `pair` to return a number instead of an entity
- Preventing direct usage of a pair as an entity while still allowing it to be used as a component
- Exported built-in components `ChildOf` and `Name`
- Exported `world.parent`
## [0.2.10] - 2024-09-07
- `[world]`:
- Improved performance for hooks
- Changed `world:set` to be idempotent when setting tags
- `[traits]`:
- Added cleanup condition `jecs.OnDelete` for when the entity or component is deleted
- Added cleanup action `jecs.Remove` which removes instances of the specified (component) id from all entities
- This is the default cleanup action
- Added component trait `jecs.Tag` which allows for zero-cost components used as tags
- Setting data to a component with this trait will do nothing
- `[luau]`:
- Exported `world:contains()`
- Exported `query:drain()`
- Exported `Query`
- Improved types for the hook `OnAdd`, `OnSet`, `OnRemove`
- Changed functions to accept any ID including pairs in type parameters
- Applies to `world:add()`, `world:set()`, `world:remove()`, `world:get()`, `world:has()` and `world:query()`
- New exported type `Id<T = nil> = Entity<T> | Pair`
- Changed `world:contains()` to return a `boolean` instead of an entity which may or may not exist
- Fixed `world:has()` to take the correct parameters
## [0.2.2] - 2024-07-07
### Added
- Added `query:replace(function(...T) return ...U end)` for replacing components in place
- Method is fast pathed to replace the data to the components for each corresponding entity
## 0.6.1
### Changed
- Iterator now goes backwards instead to prevent common cases of iterator invalidation
## [0.2.1] - 2024-07-06
### Added
- Added `jecs.Component` built-in component which will be added to ids created with `world:component()`.
- Used to find every component id with `query(jecs.Component)
## [0.2.0] - 2024-07-03
### Added
- Added `world:parent(entity)` and `jecs.ChildOf` respectively as first class citizen for building parent-child relationships.
- Give a parent to an entity with `world:add($source, pair(ChildOf, $target))`
- Use `world:parent(entity)` to find the target of the relationship
- Added user-facing Luau types
### Changed
- Improved iteration speeds 20-40% by manually indexing rather than using `next()` :scream:
## [0.1.1] - 2024-05-19
### Added
- Added `world:clear(entity)` for removing the components to the corresponding entity
- Added Typescript Types
## [0.1.0] - 2024-05-13
### Changed
- Optimized iterator
## [0.1.0-rc.6] - 2024-05-13
### Added
- Added a `jecs.Wildcard` term
- it lets you query any partially matched pairs
## [0.1.0-rc.5] - 2024-05-10
### Added
- Added Entity relationships for creating logical connections between entities
- Added `world:__iter method` which allows for iteration over the whole world to get every entity
- used for reconciling whole worlds such as via replication, saving/loading, etc
- Added `world:add(entity, component)` which adds a component to the entity
- it is an idempotent function, so calling it twice and in any order should be fine
- Entity types now unions with numbers should allow for easier time casting while not causing regressing previous behaviours
### Fixed
- Fixed a critical bug with `(*, R)` pairs not being removed when `R` is deleted
- Fixed component overriding when in disorder
- Previously setting the components in different order results in it overriding component data because it incorrectly mapped the index of the column. So it took the index from the source archetype rather than the destination archetype
## [0.0.0-prototype.rc.3] - 2024-05-01
## 0.6.0
### Added
- Added observers
- Added an arm to query `query:without()` for chaining invariants.
- `World:range` to restrict entity range to allow for e.g. reserving ids `1000..5000` for clients and everything above that (5000+) for entities from the server. This makes it possible to receive ids from a server that don't have to be mapped to local ids.
- `jecs.component`, `jecs.tag` and `jecs.meta` for preregistering ids and their metadata before a world
- Overload to `World:entity` to create an entity at the desired id.
### Changed
- `World:clear` to remove the `ID` from every entity instead of the previous behaviour of removing all of the components on the entity. You should prefer deleting the entity instead for the previous behaviour.
- Entity ID layouts by putting the index in the lower bits, which should make every world function 15 nanoseconds faster.
- Hooks now pass the full component ID which is useful for pairs when you need both the relation and the target.
- Replaced `OnSet` with `OnChange`, which now only runs when the component ID was previously present on the entity.
- `OnAdd` now runs after the value has been set and also passes the component ID and the value.
- `OnRemove` now lazily looks up which archetype the entity will move to. This is meant to support interior structural changes within every hook.
- Optimized `world:has` for both single and multiple component presence. This comes at the cost that it cannot check the component presence for more than 4 components at a time. If this is important, consider calling this function multiple times.
- Separates ranges for components and entity IDs.
### Fixed
- `World:delete` not removing every pair with an unalive target. Specifically happened when you had at least two pairs of different relations with multiple targets each.
- IDs created with `world:component()` will promote array lookups rather than map lookups in the `component_index` which is a significant boost
## 0.5.0
- No longer caches the column pointers directly and instead the column indices which stay persistent even when data is reallocated during swap-removals
- This was an issue with the iterator being invalidated when you move an entity to a different archetype.
### Fixedhttps://github.com/Ukendio/jecs/releases/tag/v0.0.0-prototype.rc.3
- Fixed a bug where changing an existing component would be slow because it was always appending changing the row of the entity record
- The fix dramatically improves times where it is basically down to just the speed of setting a field in a table
## [0.0.0-prototype.rc.2] - 2024-04-26
### Added
- `World:each` to find entities with a specific Tag.
- `World:children` to find children of an entity.
- `Query:cached` to add a query cache that updates itself when an archetype matching the query gets created or deleted.
### Changed
- Inference of entities' types using user-defined type functions.
- `Pair<First, Second>` to return `Second` if `First` is a `Tag`; otherwise, returns `First`.
- Optimized the creation of the query
- It will now finds the smallest archetype map to iterate over
- Optimized the query iterator
### Fixed
- `World:target` not giving adjacent pairs.
- It will now populates iterator with columns for faster indexing
## 0.4.0
- Renamed the insertion method from world:add to world:set to better reflect what it does.
### Added
- Recycling support to `world:entity` so reused entity IDs now increment generation.
## [0.0.0-prototype.rc.2] - 2024-04-23
### Removed
- `Query:drain`
- `Query:next`
- `Query:replace`
- Initial release
### Changed
- `jecs.Pair` type in Luau now returns the first element's type to avoid manual typecasting.
[unreleased]: https://github.com/ukendio/jecs/compare/v0.0.0.0-prototype.rc.2...HEAD
[0.2.2]: https://github.com/ukendio/jecs/releases/tag/v0.2.2
[0.2.1]: https://github.com/ukendio/jecs/releases/tag/v0.2.1
[0.2.0]: https://github.com/ukendio/jecs/releases/tag/v0.2.0
[0.1.1]: https://github.com/ukendio/jecs/releases/tag/v0.1.1
[0.1.0]: https://github.com/ukendio/jecs/releases/tag/v0.1.0
[0.1.0-rc.6]: https://github.com/ukendio/jecs/releases/tag/v0.1.0-rc.6
[0.1.0-rc.5]: https://github.com/ukendio/jecs/releases/tag/v0.1.0-rc.5
[0.0.0-prototype-rc.3]: https://github.com/ukendio/jecs/releases/tag/v0.0.0-prototype.rc.3
[0.0.0-prototype.rc.2]: https://github.com/ukendio/jecs/releases/tag/v0.0.0-prototype.rc.2
[0.0.0-prototype-rc.1]: https://github.com/ukendio/jecs/releases/tag/v0.0.0-prototype.rc.1
### Fixed
- `Query:archetypes` now correctly takes `self`.
## 0.3.2 - 2024-10-01
### Changed
- `World:cleanup` to traverse a header type for graph edges.
### Fixed
- Regression when calling `World:set` after `World:remove` on the same component.
- Removed explicit error in `JECS_DEBUG` for `World:target` missing index.
- `World.set` type inference with `NoInfer<T>` in TypeScript.
## 0.3.1 - 2024-10-01
### Added
- Index parameter to `World:target`.
- Global config `_G.JECS_HI_COMPONENT_ID` to change component ID limit (must be set before importing JECS).
- Debug mode via `_G.JECS_DEBUG` (must be set before importing JECS).
- `world:cleanup` to manually clean up empty archetypes.
### Changed
- `world:delete` now also deletes dependent archetypes and child entities.
### Fixed
- `Query` iterator to not drain by default.
- TypeScript package entry to `src` instead of `src/init`.
- `Query.next` now returns expected result tuple in typescript.
- `pair` returns a number instead of entity to prevent misuse.
- Exported built-in components `ChildOf`, `Name`, and `world.parent`.
## 0.2.10
### Added
- Trait `jecs.Tag` for zero-cost tag components.
- Cleanup conditions: `jecs.OnDelete`, `jecs.Remove`.
### Changed
- `world:set` is now idempotent when setting tags.
### Fixed
- Improved performance for hooks.
- Exported types and functions: `world:contains()`, `query:drain()`, `Query`.
- Hook types: `OnAdd`, `OnSet`, `OnRemove`.
- ID flexibility for `add`, `set`, `remove`, `get`, `has`, `query`.
- `world:contains()` now returns `boolean`.
- `world:has()` parameters now correct.
## 0.2.2
### Added
- `query:replace(fn)` for in-place replacement of component values.
### Changed
- Iterator now goes backwards to avoid invalidation during iteration.
## 0.2.1
### Added
- Built-in `jecs.Component` used to find all component IDs.
## 0.2.0
### Added
- `world:parent(entity)` and `jecs.ChildOf` for parent-child relationships.
### Changed
- Iteration performance improved by 2040% through manual indexing.
## 0.1.1
### Added
- `world:clear(entity)` for removing all components from an entity.
- TypeScript types.
## 0.1.0
### Changed
- Optimized iterator.
## 0.1.0-rc.6
### Added
- `jecs.Wildcard` term to query partially matched pairs.
## 0.1.0-rc.5
### Added
- Entity relationships.
- `world:__iter()` for full world iteration.
- `world:add(entity, component)` (idempotent).
### Fixed
- Component overriding when set out of order.
## 0.0.0-prototype.rc.3
### Added
- Observers.
- `query:without()` for invariant queries.
### Changed
- Separate ID ranges for entities and components.
- Avoid caching pointers; cache stable column indices instead.
### Fixed
- Slow component updates due to unnecessary row changes.
## 0.0.0-prototype.rc.2 - 2024-04-26
### Changed
- Query now uses smallest archetype map.
- Optimized query iterator.
- Renamed `world:add` to `world:set`.
## 0.0.0-prototype.rc.1
### Added
- Initial release.

View file

@ -2,7 +2,7 @@
<img src="assets/image-5.png" width=35%/>
</p>
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge)](LICENSE) [![Wally](https://img.shields.io/github/v/tag/ukendio/jecs?&style=for-the-badge)](https://wally.run/package/ukendio/jecs)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge)](LICENSE) [![Wally](https://img.shields.io/github/v/tag/ukendio/jecs?&style=for-the-badge)](https://wally.run/package/ukendio/jecs) [![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/ukendio/jecs/unit-testing.yaml?&style=for-the-badge)](https://github.com/Ukendio/jecs/actions/workflows/unit-testing.yaml)
Just a stupidly fast Entity Component System
@ -12,7 +12,22 @@ Just a stupidly fast Entity Component System
- Zero-dependency package
- Optimized for column-major operations
- Cache friendly [archetype/SoA](https://ajmmertens.medium.com/building-an-ecs-2-archetypes-and-vectorization-fe21690805f9) storage
- Rigorously [unit tested](https://github.com/Ukendio/jecs/actions/workflows/ci.yaml) for stability
- Rigorously [unit tested](https://github.com/Ukendio/jecs/actions/workflows/unit-testing.yaml) for stability
### Installation
With [Wally](https://wally.run/):
```bash
jecs = "ukendio/jecs@0.6.0" # Inside wally.toml
```
With [pesde](https://pesde.dev/):
```bash
pesde add wally#ukendio/jecs@0.6.0
```
With [npm](https://www.npmjs.com/package/@rbxts/jecs) ([roblox-ts](https://roblox-ts.com/)):
```bash
npm i @rbxts/jecs
```
### Example
@ -55,6 +70,8 @@ end
-- sara is the child of alice
```
### Benchmarks
21,000 entities 125 archetypes 4 random components queried.
![Queries](assets/image-3.png)
Can be found under /benches/visual/query.luau

View file

@ -1,21 +1,22 @@
local jecs = require("@jecs")
type Observer = {
callback: (jecs.Entity) -> (),
query: jecs.Query<...jecs.Id>,
}
export type PatchedWorld = jecs.World & {
added: <T>(PatchedWorld, jecs.Id<T>, (jecs.Entity, jecs.Id, T) -> ()) -> () -> (),
removed: <T>(PatchedWorld, jecs.Id<T>, (jecs.Entity, jecs.Id) -> ()) -> () -> (),
changed: <T>(PatchedWorld, jecs.Id<T>, (jecs.Entity, jecs.Id, T) -> ()) -> () -> (),
observer: (PatchedWorld, Observer) -> (),
monitor: (PatchedWorld, Observer) -> (),
added: <T>(PatchedWorld, jecs.Id<T>, (e: jecs.Entity, id: jecs.Id, value: T) -> ()) -> () -> (),
removed: <T>(PatchedWorld, jecs.Id<T>, (e: jecs.Entity, id: jecs.Id) -> ()) -> () -> (),
changed: <T>(PatchedWorld, jecs.Id<T>, (e: jecs.Entity, id: jecs.Id, value: T) -> ()) -> () -> (),
observer: (
PatchedWorld,
any,
(jecs.Entity) -> ()
) -> (),
monitor: (
PatchedWorld,
any,
(jecs.Entity, jecs.Id) -> ()
) -> ()
}
local function observers_new(world, description)
local query = description.query
local callback = description.callback
local function observers_new(world, query, callback)
local terms = query.filter_with :: { jecs.Id }
if not terms then
local ids = query.ids
@ -45,7 +46,6 @@ local function observers_new(world, description)
end
end
local function join(world, component)
local sparse_array = {}
local dense_array = {}
@ -90,9 +90,7 @@ local function join(world, component)
end
end
local function monitors_new(world, description)
local query = description.query
local callback = description.callback
local function monitors_new(world, query, callback)
local terms = query.filter_with :: { jecs.Id }
if not terms then
local ids = query.ids
@ -127,7 +125,8 @@ local function monitors_new(world, description)
local archetype = r.archetype
if jecs.query_match(query, archetype) then
callback(entity, jecs.OnRemove)
local EcsOnRemove = jecs.OnRemove :: jecs.Id
callback(entity, EcsOnRemove)
end
end
@ -158,18 +157,19 @@ local function observers_add(world: jecs.World): PatchedWorld
listeners = {}
signals.added[component] = listeners
local function on_add(entity: number, id: number, value: any)
local function on_add(entity, id, value)
for _, listener in listeners :: any do
listener(entity, id, value)
end
end
local existing_hook = world:get(component, jecs.OnAdd)
if existing_hook then
table.insert(listeners, existing_hook)
end
local idr = world.component_index[component]
if idr then
local idr_hook_existing = idr.hooks.on_add
if idr_hook_existing then
table.insert(listeners, idr_hook_existing)
end
idr.hooks.on_add = on_add :: any
idr.hooks.on_add = on_add
else
world:set(component, jecs.OnAdd, on_add)
end
@ -192,18 +192,18 @@ local function observers_add(world: jecs.World): PatchedWorld
if not listeners then
listeners = {}
signals.emplaced[component] = listeners
local function on_change(entity: number, id: number, value: any)
local function on_change(entity, id, value: any)
for _, listener in listeners :: any do
listener(entity, id, value)
end
end
local existing_hook = world:get(component, jecs.OnChange)
if existing_hook then
table.insert(listeners, existing_hook)
end
local idr = world.component_index[component]
if idr then
local idr_hook_existing = idr.hooks.on_change
if idr_hook_existing then
table.insert(listeners, idr_hook_existing)
end
idr.hooks.on_change = on_change :: any
idr.hooks.on_change = on_change
else
world:set(component, jecs.OnChange, on_change)
end
@ -226,23 +226,26 @@ local function observers_add(world: jecs.World): PatchedWorld
if not listeners then
listeners = {}
signals.removed[component] = listeners
local function on_remove(entity: number, id: number, value: any)
local function on_remove(entity, id)
for _, listener in listeners :: any do
listener(entity, id, value)
listener(entity, id)
end
end
local existing_hook = world:get(component, jecs.OnRemove)
if existing_hook then
table.insert(listeners, existing_hook)
end
local idr = world.component_index[component]
if idr then
local idr_hook_existing = idr.hooks.on_remove
if idr_hook_existing then
table.insert(listeners, idr_hook_existing)
end
idr.hooks.on_remove = on_remove :: any
idr.hooks.on_remove = on_remove
else
world:set(component, jecs.OnRemove, on_remove)
end
end
table.insert(listeners, fn)
return function()
local n = #listeners
local i = table.find(listeners, fn)

View file

@ -1,18 +0,0 @@
option ClientOutput = "../net/client.luau"
option ServerOutput = "../net/server.luau"
event UpdateTransform {
From: Server,
Type: Unreliable,
Call: SingleSync,
Poll: true,
Data: (f64, CFrame)
}
event SpawnMob {
From: Server,
Type: Reliable,
Call: SingleSync,
Poll: true,
Data: (f64, CFrame, u8)
}

View file

@ -1,336 +0,0 @@
--!strict
--!native
--!optimize 2
--!nolint LocalShadow
--#selene: allow(shadowing)
-- File generated by Blink v0.14.1 (https://github.com/1Axen/Blink)
-- This file is not meant to be edited
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
if not RunService:IsClient() then
error("Client network module can only be required from the client.")
end
local Reliable: RemoteEvent = ReplicatedStorage:WaitForChild("BLINK_RELIABLE_REMOTE") :: RemoteEvent
local Unreliable: UnreliableRemoteEvent =
ReplicatedStorage:WaitForChild("BLINK_UNRELIABLE_REMOTE") :: UnreliableRemoteEvent
local Invocations = 0
local SendSize = 64
local SendOffset = 0
local SendCursor = 0
local SendBuffer = buffer.create(64)
local SendInstances = {}
local RecieveCursor = 0
local RecieveBuffer = buffer.create(64)
local RecieveInstances = {}
local RecieveInstanceCursor = 0
type Entry = {
value: any,
next: Entry?,
}
type Queue = {
head: Entry?,
tail: Entry?,
}
type BufferSave = {
Size: number,
Cursor: number,
Buffer: buffer,
Instances: { Instance },
}
local function Read(Bytes: number)
local Offset = RecieveCursor
RecieveCursor += Bytes
return Offset
end
local function Save(): BufferSave
return {
Size = SendSize,
Cursor = SendCursor,
Buffer = SendBuffer,
Instances = SendInstances,
}
end
local function Load(Save: BufferSave?)
if Save then
SendSize = Save.Size
SendCursor = Save.Cursor
SendOffset = Save.Cursor
SendBuffer = Save.Buffer
SendInstances = Save.Instances
return
end
SendSize = 64
SendCursor = 0
SendOffset = 0
SendBuffer = buffer.create(64)
SendInstances = {}
end
local function Invoke()
if Invocations == 255 then
Invocations = 0
end
local Invocation = Invocations
Invocations += 1
return Invocation
end
local function Allocate(Bytes: number)
local InUse = (SendCursor + Bytes)
if InUse > SendSize then
--> Avoid resizing the buffer for every write
while InUse > SendSize do
SendSize *= 1.5
end
local Buffer = buffer.create(SendSize)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
SendBuffer = Buffer
end
SendOffset = SendCursor
SendCursor += Bytes
return SendOffset
end
local function CreateQueue(): Queue
return {
head = nil,
tail = nil,
}
end
local function Pop(queue: Queue): any
local head = queue.head
if head == nil then
return
end
queue.head = head.next
return head.value
end
local function Push(queue: Queue, value: any)
local entry: Entry = {
value = value,
next = nil,
}
if queue.tail ~= nil then
queue.tail.next = entry
end
queue.tail = entry
if queue.head == nil then
queue.head = entry
end
end
local Types = {}
local Calls = table.create(256)
local Events: any = {
Reliable = table.create(256),
Unreliable = table.create(256),
}
local Queue: any = {
Reliable = table.create(256),
Unreliable = table.create(256),
}
Queue.Unreliable[0] = CreateQueue()
Queue.Reliable[0] = CreateQueue()
function Types.ReadEVENT_UpdateTransform(): (number, CFrame)
-- Read BLOCK: 32 bytes
local BLOCK_START = Read(32)
local Value1 = buffer.readf64(RecieveBuffer, BLOCK_START + 0)
local X = buffer.readf32(RecieveBuffer, BLOCK_START + 8)
local Y = buffer.readf32(RecieveBuffer, BLOCK_START + 12)
local Z = buffer.readf32(RecieveBuffer, BLOCK_START + 16)
local Position = Vector3.new(X, Y, Z)
local rX = buffer.readf32(RecieveBuffer, BLOCK_START + 20)
local rY = buffer.readf32(RecieveBuffer, BLOCK_START + 24)
local rZ = buffer.readf32(RecieveBuffer, BLOCK_START + 28)
local Value2 = CFrame.new(Position) * CFrame.fromOrientation(rX, rY, rZ)
return Value1, Value2
end
function Types.WriteEVENT_UpdateTransform(Value1: number, Value2: CFrame): ()
-- Allocate BLOCK: 33 bytes
local BLOCK_START = Allocate(33)
buffer.writeu8(SendBuffer, BLOCK_START + 0, 0)
buffer.writef64(SendBuffer, BLOCK_START + 1, Value1)
local Vector = Value2.Position
buffer.writef32(SendBuffer, BLOCK_START + 9, Vector.X)
buffer.writef32(SendBuffer, BLOCK_START + 13, Vector.Y)
buffer.writef32(SendBuffer, BLOCK_START + 17, Vector.Z)
local rX, rY, rZ = Value2:ToOrientation()
buffer.writef32(SendBuffer, BLOCK_START + 21, rX)
buffer.writef32(SendBuffer, BLOCK_START + 25, rY)
buffer.writef32(SendBuffer, BLOCK_START + 29, rZ)
end
function Types.ReadEVENT_SpawnMob(): (number, CFrame, number)
-- Read BLOCK: 33 bytes
local BLOCK_START = Read(33)
local Value1 = buffer.readf64(RecieveBuffer, BLOCK_START + 0)
local X = buffer.readf32(RecieveBuffer, BLOCK_START + 8)
local Y = buffer.readf32(RecieveBuffer, BLOCK_START + 12)
local Z = buffer.readf32(RecieveBuffer, BLOCK_START + 16)
local Position = Vector3.new(X, Y, Z)
local rX = buffer.readf32(RecieveBuffer, BLOCK_START + 20)
local rY = buffer.readf32(RecieveBuffer, BLOCK_START + 24)
local rZ = buffer.readf32(RecieveBuffer, BLOCK_START + 28)
local Value2 = CFrame.new(Position) * CFrame.fromOrientation(rX, rY, rZ)
local Value3 = buffer.readu8(RecieveBuffer, BLOCK_START + 32)
return Value1, Value2, Value3
end
function Types.WriteEVENT_SpawnMob(Value1: number, Value2: CFrame, Value3: number): ()
-- Allocate BLOCK: 34 bytes
local BLOCK_START = Allocate(34)
buffer.writeu8(SendBuffer, BLOCK_START + 0, 0)
buffer.writef64(SendBuffer, BLOCK_START + 1, Value1)
local Vector = Value2.Position
buffer.writef32(SendBuffer, BLOCK_START + 9, Vector.X)
buffer.writef32(SendBuffer, BLOCK_START + 13, Vector.Y)
buffer.writef32(SendBuffer, BLOCK_START + 17, Vector.Z)
local rX, rY, rZ = Value2:ToOrientation()
buffer.writef32(SendBuffer, BLOCK_START + 21, rX)
buffer.writef32(SendBuffer, BLOCK_START + 25, rY)
buffer.writef32(SendBuffer, BLOCK_START + 29, rZ)
buffer.writeu8(SendBuffer, BLOCK_START + 33, Value3)
end
local function StepReplication()
if SendCursor <= 0 then
return
end
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
Reliable:FireServer(Buffer, SendInstances)
SendSize = 64
SendCursor = 0
SendOffset = 0
SendBuffer = buffer.create(64)
table.clear(SendInstances)
end
local Elapsed = 0
RunService.Heartbeat:Connect(function(DeltaTime: number)
Elapsed += DeltaTime
if Elapsed >= (1 / 61) then
Elapsed -= (1 / 61)
StepReplication()
end
end)
Reliable.OnClientEvent:Connect(function(Buffer: buffer, Instances: { Instance })
RecieveCursor = 0
RecieveBuffer = Buffer
RecieveInstances = Instances
RecieveInstanceCursor = 0
local Size = buffer.len(RecieveBuffer)
while RecieveCursor < Size do
-- Read BLOCK: 1 bytes
local BLOCK_START = Read(1)
local Index = buffer.readu8(RecieveBuffer, BLOCK_START + 0)
if Index == 0 then
Push(Queue.Reliable[0], table.pack(Types.ReadEVENT_SpawnMob()))
end
end
end)
Unreliable.OnClientEvent:Connect(function(Buffer: buffer, Instances: { Instance })
RecieveCursor = 0
RecieveBuffer = Buffer
RecieveInstances = Instances
RecieveInstanceCursor = 0
local Size = buffer.len(RecieveBuffer)
while RecieveCursor < Size do
-- Read BLOCK: 1 bytes
local BLOCK_START = Read(1)
local Index = buffer.readu8(RecieveBuffer, BLOCK_START + 0)
if Index == 0 then
Push(Queue.Unreliable[0], table.pack(Types.ReadEVENT_UpdateTransform()))
end
end
end)
return {
StepReplication = StepReplication,
UpdateTransform = {
Iter = function(): () -> (number, number, CFrame)
local index = 0
local queue = Queue.Unreliable[0]
return function(): (number, number, CFrame)
index += 1
local arguments = Pop(queue)
if arguments ~= nil then
return index, unpack(arguments, 1, arguments.n)
end
return
end
end,
Next = function(): () -> (number, number, CFrame)
local index = 0
local queue = Queue.Unreliable[0]
return function(): (number, number, CFrame)
index += 1
local arguments = Pop(queue)
if arguments ~= nil then
return index, unpack(arguments, 1, arguments.n)
end
return
end
end,
},
SpawnMob = {
Iter = function(): () -> (number, number, CFrame, number)
local index = 0
local queue = Queue.Reliable[0]
return function(): (number, number, CFrame, number)
index += 1
local arguments = Pop(queue)
if arguments ~= nil then
return index, unpack(arguments, 1, arguments.n)
end
return
end
end,
Next = function(): () -> (number, number, CFrame, number)
local index = 0
local queue = Queue.Reliable[0]
return function(): (number, number, CFrame, number)
index += 1
local arguments = Pop(queue)
if arguments ~= nil then
return index, unpack(arguments, 1, arguments.n)
end
return
end
end,
},
}

View file

@ -1,372 +0,0 @@
--!strict
--!native
--!optimize 2
--!nolint LocalShadow
--#selene: allow(shadowing)
-- File generated by Blink v0.14.1 (https://github.com/1Axen/Blink)
-- This file is not meant to be edited
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
if not RunService:IsServer() then
error("Server network module can only be required from the server.")
end
local Reliable: RemoteEvent = ReplicatedStorage:FindFirstChild("BLINK_RELIABLE_REMOTE") :: RemoteEvent
if not Reliable then
local RemoteEvent = Instance.new("RemoteEvent")
RemoteEvent.Name = "BLINK_RELIABLE_REMOTE"
RemoteEvent.Parent = ReplicatedStorage
Reliable = RemoteEvent
end
local Unreliable: UnreliableRemoteEvent =
ReplicatedStorage:FindFirstChild("BLINK_UNRELIABLE_REMOTE") :: UnreliableRemoteEvent
if not Unreliable then
local UnreliableRemoteEvent = Instance.new("UnreliableRemoteEvent")
UnreliableRemoteEvent.Name = "BLINK_UNRELIABLE_REMOTE"
UnreliableRemoteEvent.Parent = ReplicatedStorage
Unreliable = UnreliableRemoteEvent
end
local Invocations = 0
local SendSize = 64
local SendOffset = 0
local SendCursor = 0
local SendBuffer = buffer.create(64)
local SendInstances = {}
local RecieveCursor = 0
local RecieveBuffer = buffer.create(64)
local RecieveInstances = {}
local RecieveInstanceCursor = 0
type Entry = {
value: any,
next: Entry?,
}
type Queue = {
head: Entry?,
tail: Entry?,
}
type BufferSave = {
Size: number,
Cursor: number,
Buffer: buffer,
Instances: { Instance },
}
local function Read(Bytes: number)
local Offset = RecieveCursor
RecieveCursor += Bytes
return Offset
end
local function Save(): BufferSave
return {
Size = SendSize,
Cursor = SendCursor,
Buffer = SendBuffer,
Instances = SendInstances,
}
end
local function Load(Save: BufferSave?)
if Save then
SendSize = Save.Size
SendCursor = Save.Cursor
SendOffset = Save.Cursor
SendBuffer = Save.Buffer
SendInstances = Save.Instances
return
end
SendSize = 64
SendCursor = 0
SendOffset = 0
SendBuffer = buffer.create(64)
SendInstances = {}
end
local function Invoke()
if Invocations == 255 then
Invocations = 0
end
local Invocation = Invocations
Invocations += 1
return Invocation
end
local function Allocate(Bytes: number)
local InUse = (SendCursor + Bytes)
if InUse > SendSize then
--> Avoid resizing the buffer for every write
while InUse > SendSize do
SendSize *= 1.5
end
local Buffer = buffer.create(SendSize)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
SendBuffer = Buffer
end
SendOffset = SendCursor
SendCursor += Bytes
return SendOffset
end
local function CreateQueue(): Queue
return {
head = nil,
tail = nil,
}
end
local function Pop(queue: Queue): any
local head = queue.head
if head == nil then
return
end
queue.head = head.next
return head.value
end
local function Push(queue: Queue, value: any)
local entry: Entry = {
value = value,
next = nil,
}
if queue.tail ~= nil then
queue.tail.next = entry
end
queue.tail = entry
if queue.head == nil then
queue.head = entry
end
end
local Types = {}
local Calls = table.create(256)
local Events: any = {
Reliable = table.create(256),
Unreliable = table.create(256),
}
local Queue: any = {
Reliable = table.create(256),
Unreliable = table.create(256),
}
function Types.ReadEVENT_UpdateTransform(): (number, CFrame)
-- Read BLOCK: 32 bytes
local BLOCK_START = Read(32)
local Value1 = buffer.readf64(RecieveBuffer, BLOCK_START + 0)
local X = buffer.readf32(RecieveBuffer, BLOCK_START + 8)
local Y = buffer.readf32(RecieveBuffer, BLOCK_START + 12)
local Z = buffer.readf32(RecieveBuffer, BLOCK_START + 16)
local Position = Vector3.new(X, Y, Z)
local rX = buffer.readf32(RecieveBuffer, BLOCK_START + 20)
local rY = buffer.readf32(RecieveBuffer, BLOCK_START + 24)
local rZ = buffer.readf32(RecieveBuffer, BLOCK_START + 28)
local Value2 = CFrame.new(Position) * CFrame.fromOrientation(rX, rY, rZ)
return Value1, Value2
end
function Types.WriteEVENT_UpdateTransform(Value1: number, Value2: CFrame): ()
-- Allocate BLOCK: 33 bytes
local BLOCK_START = Allocate(33)
buffer.writeu8(SendBuffer, BLOCK_START + 0, 0)
buffer.writef64(SendBuffer, BLOCK_START + 1, Value1)
local Vector = Value2.Position
buffer.writef32(SendBuffer, BLOCK_START + 9, Vector.X)
buffer.writef32(SendBuffer, BLOCK_START + 13, Vector.Y)
buffer.writef32(SendBuffer, BLOCK_START + 17, Vector.Z)
local rX, rY, rZ = Value2:ToOrientation()
buffer.writef32(SendBuffer, BLOCK_START + 21, rX)
buffer.writef32(SendBuffer, BLOCK_START + 25, rY)
buffer.writef32(SendBuffer, BLOCK_START + 29, rZ)
end
function Types.ReadEVENT_SpawnMob(): (number, CFrame, number)
-- Read BLOCK: 33 bytes
local BLOCK_START = Read(33)
local Value1 = buffer.readf64(RecieveBuffer, BLOCK_START + 0)
local X = buffer.readf32(RecieveBuffer, BLOCK_START + 8)
local Y = buffer.readf32(RecieveBuffer, BLOCK_START + 12)
local Z = buffer.readf32(RecieveBuffer, BLOCK_START + 16)
local Position = Vector3.new(X, Y, Z)
local rX = buffer.readf32(RecieveBuffer, BLOCK_START + 20)
local rY = buffer.readf32(RecieveBuffer, BLOCK_START + 24)
local rZ = buffer.readf32(RecieveBuffer, BLOCK_START + 28)
local Value2 = CFrame.new(Position) * CFrame.fromOrientation(rX, rY, rZ)
local Value3 = buffer.readu8(RecieveBuffer, BLOCK_START + 32)
return Value1, Value2, Value3
end
function Types.WriteEVENT_SpawnMob(Value1: number, Value2: CFrame, Value3: number): ()
-- Allocate BLOCK: 34 bytes
local BLOCK_START = Allocate(34)
buffer.writeu8(SendBuffer, BLOCK_START + 0, 0)
buffer.writef64(SendBuffer, BLOCK_START + 1, Value1)
local Vector = Value2.Position
buffer.writef32(SendBuffer, BLOCK_START + 9, Vector.X)
buffer.writef32(SendBuffer, BLOCK_START + 13, Vector.Y)
buffer.writef32(SendBuffer, BLOCK_START + 17, Vector.Z)
local rX, rY, rZ = Value2:ToOrientation()
buffer.writef32(SendBuffer, BLOCK_START + 21, rX)
buffer.writef32(SendBuffer, BLOCK_START + 25, rY)
buffer.writef32(SendBuffer, BLOCK_START + 29, rZ)
buffer.writeu8(SendBuffer, BLOCK_START + 33, Value3)
end
local PlayersMap: { [Player]: BufferSave } = {}
Players.PlayerRemoving:Connect(function(Player)
PlayersMap[Player] = nil
end)
local function StepReplication()
for Player, Send in PlayersMap do
if Send.Cursor <= 0 then
continue
end
local Buffer = buffer.create(Send.Cursor)
buffer.copy(Buffer, 0, Send.Buffer, 0, Send.Cursor)
Reliable:FireClient(Player, Buffer, Send.Instances)
Send.Size = 64
Send.Cursor = 0
Send.Buffer = buffer.create(64)
table.clear(Send.Instances)
end
end
RunService.Heartbeat:Connect(StepReplication)
Reliable.OnServerEvent:Connect(function(Player: Player, Buffer: buffer, Instances: { Instance })
RecieveCursor = 0
RecieveBuffer = Buffer
RecieveInstances = Instances
RecieveInstanceCursor = 0
local Size = buffer.len(RecieveBuffer)
while RecieveCursor < Size do
-- Read BLOCK: 1 bytes
local BLOCK_START = Read(1)
local Index = buffer.readu8(RecieveBuffer, BLOCK_START + 0)
end
end)
Unreliable.OnServerEvent:Connect(function(Player: Player, Buffer: buffer, Instances: { Instance })
RecieveCursor = 0
RecieveBuffer = Buffer
RecieveInstances = Instances
RecieveInstanceCursor = 0
local Size = buffer.len(RecieveBuffer)
while RecieveCursor < Size do
-- Read BLOCK: 1 bytes
local BLOCK_START = Read(1)
local Index = buffer.readu8(RecieveBuffer, BLOCK_START + 0)
end
end)
return {
StepReplication = StepReplication,
UpdateTransform = {
Fire = function(Player: Player, Value1: number, Value2: CFrame): ()
Load()
Types.WriteEVENT_UpdateTransform(Value1, Value2)
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
Unreliable:FireClient(Player, Buffer, SendInstances)
end,
FireAll = function(Value1: number, Value2: CFrame): ()
Load()
Types.WriteEVENT_UpdateTransform(Value1, Value2)
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
Unreliable:FireAllClients(Buffer, SendInstances)
end,
FireList = function(List: { Player }, Value1: number, Value2: CFrame): ()
Load()
Types.WriteEVENT_UpdateTransform(Value1, Value2)
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
for _, Player in List do
Unreliable:FireClient(Player, Buffer, SendInstances)
end
end,
FireExcept = function(Except: Player, Value1: number, Value2: CFrame): ()
Load()
Types.WriteEVENT_UpdateTransform(Value1, Value2)
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
for _, Player in Players:GetPlayers() do
if Player == Except then
continue
end
Unreliable:FireClient(Player, Buffer, SendInstances)
end
end,
},
SpawnMob = {
Fire = function(Player: Player, Value1: number, Value2: CFrame, Value3: number): ()
Load(PlayersMap[Player])
Types.WriteEVENT_SpawnMob(Value1, Value2, Value3)
PlayersMap[Player] = Save()
end,
FireAll = function(Value1: number, Value2: CFrame, Value3: number): ()
Load()
Types.WriteEVENT_SpawnMob(Value1, Value2, Value3)
local Buffer, Size, Instances = SendBuffer, SendCursor, SendInstances
for _, Player in Players:GetPlayers() do
Load(PlayersMap[Player])
local Position = Allocate(Size)
buffer.copy(SendBuffer, Position, Buffer, 0, Size)
table.move(Instances, 1, #Instances, #SendInstances + 1, SendInstances)
PlayersMap[Player] = Save()
end
end,
FireList = function(List: { Player }, Value1: number, Value2: CFrame, Value3: number): ()
Load()
Types.WriteEVENT_SpawnMob(Value1, Value2, Value3)
local Buffer, Size, Instances = SendBuffer, SendCursor, SendInstances
for _, Player in List do
Load(PlayersMap[Player])
local Position = Allocate(Size)
buffer.copy(SendBuffer, Position, Buffer, 0, Size)
table.move(Instances, 1, #Instances, #SendInstances + 1, SendInstances)
PlayersMap[Player] = Save()
end
end,
FireExcept = function(Except: Player, Value1: number, Value2: CFrame, Value3: number): ()
Load()
Types.WriteEVENT_SpawnMob(Value1, Value2, Value3)
local Buffer, Size, Instances = SendBuffer, SendCursor, SendInstances
for _, Player in Players:GetPlayers() do
if Player == Except then
continue
end
Load(PlayersMap[Player])
local Position = Allocate(Size)
buffer.copy(SendBuffer, Position, Buffer, 0, Size)
table.move(Instances, 1, #Instances, #SendInstances + 1, SendInstances)
PlayersMap[Player] = Save()
end
end,
},
}

View file

@ -4,66 +4,81 @@ local remotes = require("../remotes")
local collect = require("../collect")
local client_ids = {}
local function ecs_map_get(world: types.World, id: types.Entity)
local function ecs_map_get(world, id)
local deserialised_id = client_ids[id]
if not deserialised_id then
if world:has(id, jecs.Name) then
deserialised_id = world:entity(id)
else
if world:exists(id) then
deserialised_id = world:entity()
else
deserialised_id = world:entity(id)
end
deserialised_id = world:entity()
end
client_ids[id] = deserialised_id
end
-- local deserialised_id = client_ids[id]
-- if not deserialised_id then
-- if world:has(id, jecs.Name) then
-- deserialised_id = world:entity(id)
-- else
-- if world:exists(id) then
-- deserialised_id = world:entity()
-- else
-- deserialised_id = world:entity(id)
-- end
-- end
-- client_ids[id] = deserialised_id
-- end
return deserialised_id
end
local function ecs_make_alive_id(world: types.World, id: jecs.Id)
local function ecs_make_alive_id(world, id)
local rel = jecs.ECS_PAIR_FIRST(id)
local tgt = jecs.ECS_PAIR_SECOND(id)
ecs_map_get(world, rel)
ecs_map_get(world, tgt)
rel = ecs_map_get(world, rel)
tgt = ecs_map_get(world, tgt)
return jecs.pair(rel, tgt)
end
local snapshots = collect(remotes.replication.OnClientEvent)
return function(world: types.World)
return function()
for snapshot in snapshots do
for key, map in snapshot do
local id = (tonumber(key) :: any) :: jecs.Id
if jecs.IS_PAIR(id) then
ecs_make_alive_id(world, id)
end
for snapshot in snapshots do
for id, map in snapshot do
id = tonumber(id)
if jecs.IS_PAIR(id) then
id = ecs_make_alive_id(world, id)
end
local set = map.set
if set then
if jecs.is_tag(world, id) then
for _, entity in set do
entity = ecs_map_get(world, entity)
world:add(entity, id)
end
else
local values = map.values :: { any }
for i, entity in set do
entity = ecs_map_get(world, entity)
world:set(entity, id, values[i])
end
end
end
local set = map.set
if set then
if jecs.is_tag(world, id) then
for _, entity in set do
entity = ecs_map_get(world, entity)
world:add(entity, id)
end
else
local values = map.values
for i, entity in set do
entity = ecs_map_get(world, entity)
world:set(entity, id, values[i])
end
end
end
local removed = map.removed
if removed then
for i, e in removed do
if not world:contains(e) then
continue
end
world:remove(e, id)
local removed = map.removed
if removed then
for i, e in removed do
if not world:contains(e) then
continue
end
world:remove(e, id)
end
end
end

View file

@ -4,5 +4,12 @@ local observers_add = require("../ReplicatedStorage/observers_add")
export type World = typeof(observers_add(jecs.world()))
export type Entity = jecs.Entity
export type Id<T> = jecs.Id<T>
export type Snapshot = {
[string]: {
set: { jecs.Entity }?,
values: { any }?,
removed: { jecs.Entity }?
}
}
return {}

View file

@ -3,102 +3,169 @@ local types = require("../../ReplicatedStorage/types")
local ct = require("../../ReplicatedStorage/components")
local jecs = require(ReplicatedStorage.ecs)
local remotes = require("../../ReplicatedStorage/remotes")
local components = ct :: {[string]: jecs.Entity }
return function(world: types.World)
local storages = {}
return function(world: ty.World)
for component in world:query(ct.Networked) do
local is_tag = jecs.is_tag(world, component)
local storage = {} :: { [types.Entity]: any }
storages[component] = storage
--- integration test
if is_tag then
world:added(component, function(entity)
storage[entity] = true
end)
else
world:added(component, function(entity, _, value)
storage[entity] = value
end)
world:changed(component, function(entity, _, value)
storage[entity] = value
end)
end
-- for _ = 1, 10 do
-- local e = world:entity()
-- world:set(e, ct.TestA, true)
-- end
local storages = {} :: { [jecs.Entity]: {[jecs.Entity]: any }}
local networked_components = {}
local networked_pairs = {}
for component in world:each(ct.Networked) do
local name = world:get(component, jecs.Name) :: string
if components[name] == nil then
continue
end
storages[component] = {}
table.insert(networked_components, component)
end
for relation in world:each(ct.NetworkedPair) do
local name = world:get(relation, jecs.Name) :: string
if not components[name] then
continue
end
table.insert(networked_pairs, relation)
end
for _, component in networked_components do
local name = world:get(component, jecs.Name) :: string
if not components[name] then
error(`Networked Component (%id{component}%name{name})`)
end
local is_tag = jecs.is_tag(world, component)
local storage = storages[component]
if is_tag then
world:added(component, function(entity)
storage[entity] = true
end)
else
world:added(component, function(entity, _, value)
storage[entity] = value
end)
world:changed(component, function(entity, _, value)
storage[entity] = value
end)
end
world:removed(component, function(entity)
storage[entity] = "jecs.Remove"
end)
end
end)
end
for relation in world:query(ct.NetworkedPair) do
world:added(relation, function(entity, id, value)
local is_tag = jecs.is_tag(world, id)
local storage = storages[id]
if not storage then
storage = {}
storages[id] = storage
end
if is_tag then
storage[entity] = true
else
storage[entity] = value
end
end)
for _, relation in networked_pairs do
world:added(relation, function(entity, id, value)
local is_tag = jecs.is_tag(world, id)
local storage = storages[id]
if not storage then
storage = {}
storages[id] = storage
end
if is_tag then
storage[entity] = true
else
storage[entity] = value
end
end)
world:changed(relation, function(entity, id, value)
local is_tag = jecs.is_tag(world, id)
if is_tag then
return
end
world:changed(relation, function(entity, id, value)
local is_tag = jecs.is_tag(world, id)
if is_tag then
return
end
local storage = storages[id]
if not storage then
storage = {}
storages[id] = storage
end
local storage = storages[id]
if not storage then
storage = {}
storages[id] = storage
end
storage[entity] = value
end :: <T>(types.Entity, types.Id<T>, T) -> ())
storage[entity] = value
end)
world:removed(relation, function(entity, id)
local storage = storages[id]
if not storage then
storage = {}
storages[id] = storage
end
world:removed(relation, function(entity, id)
local storage = storages[id]
if not storage then
storage = {}
storages[id] = storage
end
storage[entity] = "jecs.Remove"
end)
end
storage[entity] = "jecs.Remove"
end)
end
local players_added = collect(Players.PlayerAdded)
return function()
local snapshot = {} :: {
[string]: {
set: { types.Entity }?,
values: { any }?,
removed: { types.Entity }?
}
}
local snapshot_lazy: ty.Snapshot
local set_ids_lazy: { jecs.Entity }
local set_ids = {} :: { types.Entity }
local removed_ids = {} :: { types.Entity }
for player in players_added do
if not snapshot_lazy then
snapshot_lazy, set_ids_lazy = {}, {}
for component, storage in storages do
local set_values = {}
local set_n = 0
local removed_n = 0
for e, v in storage do
if v ~= "jecs.Remove" then
set_n += 1
set_ids[set_n] = e
set_values[set_n] = v or true
elseif world:contains(e) then
removed_n += 1
removed_ids[removed_n] = e
end
end
for component, storage in storages do
local set_values = {}
local set_n = 0
table.clear(storage)
local q = world:query(component)
local is_tag = jecs.is_tag(world, component)
for _, archetype in q:archetypes() do
local entities = archetype.entities
local entities_len = #entities
table.move(entities, 1, entities_len, set_n + 1, set_ids_lazy)
if is_tag then
set_values = table.create(entities_len, true)
else
local column = archetype.columns[archetype.records[component]]
table.move(column, 1, entities_len, set_n + 1, set_values)
end
set_n += entities_len
end
local set = table.move(set_ids_lazy, 1, set_n, 1, {})
snapshot_lazy[tostring(component)] = {
set = if set_n > 0 then set else nil,
values = if set_n > 0 then set_values else nil,
}
end
end
remotes.replication:FireClient(player, snapshot_lazy)
end
local snapshot = {} :: ty.Snapshot
local set_ids = {}
local removed_ids = {}
for component, storage in storages do
local set_values = {} :: { any }
local set_n = 0
local removed_n = 0
for e, v in storage do
if v ~= "jecs.Remove" then
set_n += 1
set_ids[set_n] = e
set_values[set_n] = v or true
elseif not world:contains(e) then
removed_n += 1
removed_ids[removed_n] = e
end
end
table.clear(storage)
local dirty = false
@ -107,14 +174,15 @@ return function(world: types.World)
end
if dirty then
local removed = table.move(removed_ids, 1, removed_n, 1, {}) :: { jecs.Entity }
local set = table.move(set_ids, 1, set_n, 1, {}) :: { jecs.Entity }
snapshot[tostring(component)] = {
set = if set_n > 0 then table.move(set_ids, 1, set_n, 1, {}) else nil,
set = if set_n > 0 then set else nil,
values = if set_n > 0 then set_values else nil,
removed = if removed_n > 0 then table.move(removed_ids, 1, removed_n, 1, {} :: { types.Entity }) else nil
} :: any
removed = if removed_n > 0 then removed else nil
}
end
end
if next(snapshot) ~= nil then
remotes.replication:FireAllClients(snapshot)
end

View file

@ -8,15 +8,15 @@ 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: "API reference",
text: "Namespaces",
items: [
{ text: "jecs", link: "/api/jecs" },
{ text: "World", link: "/api/world" },
@ -26,34 +26,20 @@ export default defineConfig({
],
"/learn/": [
{
text: "Introduction",
text: "API Reference",
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: "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: "FAQ",
items: [{ text: "How can I contribute?", link: "/learn/faq/contributing" }],
},
],
"/contributing/": [
{
text: "Contributing",
items: [
{ 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" },
],
},
],

View file

@ -34,24 +34,23 @@ const myOtherWorld = new World();
## entity
Creates a new entity.
Creates a new entity. It accepts the overload to create an entity with a specific ID.
```luau
function World:entity(): Entity
function World:entity<T>(
id: Entity<T>? -- The desired id
): Entity<T>
```
Example:
::: code-group
```luau [luau]
local entity = world:entity()
```
```ts [typescript]
const entity = world.entity();
```
:::
## component
@ -464,23 +463,19 @@ function World:each(
```
Example:
::: code-group
```luau [luau]
local id = world:entity()
for entity in world:each(id) do
-- Do something
end
```
```ts [typescript]
const id = world.entity();
for (const entity of world.each(id)) {
// Do something
}
```
:::
## children
@ -498,3 +493,13 @@ This is the same as calling:
```luau
world:each(pair(ChildOf, parent))
```
## range
Enforces a check for entities to be created within a desired range.
```luau
function World:range(
range_begin: number -- The starting point,
range_begin: number? -- The end point (optional)
)
```

View file

@ -1,3 +0,0 @@
## TODO
This is a TODO stub.

View file

@ -1,3 +0,0 @@
## TODO
This is a TODO stub.

View file

@ -1,3 +0,0 @@
## TODO
This is a TODO stub.

View file

@ -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.

View file

@ -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](https://github.com/Ukendio/jecs)!
# 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

View file

@ -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)

View file

@ -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);
```
:::

View file

@ -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 dont 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)

View file

@ -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).

View file

@ -0,0 +1,17 @@
# Code Coverage Reports
All of the code coverage reports can be found here:
[Overview](/jecs/coverage/index.html){target="_self"}
[jecs.luau](/jecs/coverage/jecs.luau.html){target="_self"}
[ANSI](/jecs/coverage/ansi.luau.html){target="_self"}
[Entity Visualiser](/jecs/coverage/entity_visualiser.luau.html){target="_self"}
[Lifetime Tracker](/jecs/coverage/lifetime_tracker.luau.html){target="_self"}
[Testkit](/jecs/coverage/testkit.luau.html){target="_self"}
[Tests](/jecs/coverage/tests.luau.html){target="_self"}

View file

@ -0,0 +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.

View file

@ -0,0 +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.

View file

@ -0,0 +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 [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!

View file

@ -1,3 +0,0 @@
## TODO
This is a TODO stub.

697
docs/learn/overview.md Normal file
View file

@ -0,0 +1,697 @@
# 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.
## Installation
Jecs supports the following installation methods using package managers:
:::code-group
```bash [wally]
jecs = "ukendio/jecs@0.6.0" # Inside wally.toml
```
```bash [pesde]
pesde add wally#ukendio/jecs@0.6.0
```
```bash [npm]
npm i @rbxts/jecs
```
:::
Additionally an `rbxm` is published with [each release under the assets submenu](https://github.com/Ukendio/jecs/releases/latest).
## 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
```
:::
### Entity ranges
Jecs reserves entity ids under a threshold (HI_COMPONENT_ID, default is 256) for components. That means that regular entities will start after this number. This number can be further specified via the `range` member function.
::: code-group
```luau [luau]
world:range(1000, 5000) -- Defines the lower and upper bounds of the entity range respectively
local e = world:entity()
print(e)
-- Output:
-- 1000
```
```typescript [typescript]
world.range(1000, 5000) // Defines the lower and upper bounds of the entity range respectively
const e = world.entity()
print(e)
// Output:
// 1000
```
:::
### 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, id, data)
-- A transform component `id` has been added with `data` to `entity`
end)
world:set(Transform, OnRemove, function(entity, id)
-- A transform component `id` has been removed from `entity`
end)
world:set(Transform, OnChange, function(entity, id, data)
-- A transform component `id` has been changed to `data` on `entity`
end)
```
```typescript [typescript]
const Transform = world.component();
world.set(Transform, OnAdd, (entity, id, data) => {
// A transform component `id` has been added with `data` to `entity`
});
world.set(Transform, OnRemove, (entity, id) => {
// A transform component `id` has been removed from `entity`
});
world.set(Transform, OnChange, (entity, id, data) => {
// A transform component `id` has been changed to `data` on `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 dont 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.
### 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).

View file

@ -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)

View file

@ -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.
![jecs.rbxm](rbxm.png)
### 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

78
docs/resources.md Normal file
View file

@ -0,0 +1,78 @@
## 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)
- [Formalisation of Concepts behind ECS and Entitas - Maxim Zaks](https://medium.com/@icex33/formalisation-of-concepts-behind-ecs-and-entitas-8efe535d9516)
- [Entity Component System and Rendering - Our Machinery](https://ourmachinery.com/post/ecs-and-rendering/)
- [Specs and Legion, two very different approaches to ECS - Cora Sherrat](https://csherratt.github.io/blog/posts/specs-and-legion/)
- [Where are my Entities and Components - Sander Mertens](https://ajmmertens.medium.com/building-an-ecs-1-where-are-my-entities-and-components-63d07c7da742)
- [Archetypes and Vectorization - Sander Mertens](https://medium.com/@ajmmertens/building-an-ecs-2-archetypes-and-vectorization-fe21690805f9)
- [Building Games with Entity Relationships - Sander Mertens](https://ajmmertens.medium.com/building-games-in-ecs-with-entity-relationships-657275ba2c6c)
- [Why it is time to start thinking of games as databases - Sander Mertens](https://ajmmertens.medium.com/why-it-is-time-to-start-thinking-of-games-as-databases-e7971da33ac3)
- [A Roadmap to Entity Relationships - Sander Mertens](https://ajmmertens.medium.com/a-roadmap-to-entity-relationships-5b1d11ebb4eb)
- [Making the most of Entity Identifiers - Sander Mertens](https://ajmmertens.medium.com/doing-a-lot-with-a-little-ecs-identifiers-25a72bd2647)
- [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/)
- [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)
- [Using Rust for Game Development - Catherine West, RustConf](https://www.youtube.com/watch?v=aKLntZcp27M)
- [CPU caches and why you should care - Scott Meyers, NDC](https://vimeo.com/97337258)
- [Building a fast ECS on top of a slow ECS - @UnitOfTime](https://youtu.be/71RSWVyOMEY)
- [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)
- [Understanding Data Oriented Design - Unity](https://learn.unity.com/tutorial/part-1-understand-data-oriented-design?courseId=60132919edbc2a56f9d439c3&signup=true&uv=2020.1)
- [Data Oriented Design - Richard Fabian](https://www.dataorienteddesign.com/dodbook/dodmain.html)
- [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/tools/entity_visualiser.luau)
A simple entity and component visualiser in the output
#### [jecs_lifetime_tracker](https://github.com/Ukendio/jecs/blob/main/tools/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

33
jecs.d.ts vendored
View file

@ -120,6 +120,7 @@ export class World {
* @returns An entity (Tag) with no data.
*/
entity(): Tag;
entity<T extends Entity>(id: T): InferComponent<T> extends undefined ? Tag : T;
/**
* Creates a new entity in the first 256 IDs, typically used for static
@ -148,8 +149,16 @@ export class World {
* @param entity The target entity.
* @param component The component (or tag) to add.
*/
add(entity: Entity, component: Id<undefined>): void;
add<C>(entity: Entity, component: undefined extends InferComponent<C> ? C : Id<undefined>): void;
/**
* Installs a hook on the given component.
* @param component The target component.
* @param hook The hook to install.
* @param value The hook callback.
*/
set<T>(component: Entity<T>, hook: StatefulHook, value: (e: Entity<T>, id: Id<T>, data: T) => void): void;
set<T>(component: Entity<T>, hook: StatelessHook, value: (e: Entity<T>, id: Id<T>) => void): void;
/**
* Assigns a value to a component on the given entity.
* @param entity The target entity.
@ -243,12 +252,12 @@ export class World {
export function component<T>(): Entity<T>;
export function tag<T>(): Entity<T>;
export function tag(): Tag;
// note: original types had id: Entity, id: Id<T>, which does not work with TS.
export function meta<T>(e: Entity, id: Id<T>, value?: T): Entity<T>
export function meta<T>(e: Entity, id: Id<T>, value?: T): Entity<T>;
export function is_tag<T>(world: World, id: Id<T>): boolean;
export function is_tag(world: World, id: Id): boolean;
/**
* Creates a composite key (pair)
@ -279,9 +288,19 @@ export function pair_first<P, O>(world: World, p: Pair<P, O>): Entity<P>;
*/
export function pair_second<P, O>(world: World, p: Pair<P, O>): Entity<O>;
export declare const OnAdd: Entity<(e: Entity) => void>;
export declare const OnRemove: Entity<(e: Entity) => void>;
export declare const OnChange: Entity<(e: Entity, value: unknown) => void>;
export function ECS_PAIR_FIRST(pair: Pair): number;
export function ECS_PAIR_SECOND(pair: Pair): number;
type StatefulHook = Entity<<T>(e: Entity<T>, id: Id<T>, data: T) => void> & {
readonly __nominal_StatefulHook: unique symbol,
}
type StatelessHook = Entity<<T>(e: Entity<T>, id: Id<T>) => void> & {
readonly __nominal_StatelessHook: unique symbol,
}
export declare const OnAdd: StatefulHook;
export declare const OnRemove: StatelessHook;
export declare const OnChange: StatefulHook;
export declare const ChildOf: Tag;
export declare const Wildcard: Entity;
export declare const w: Entity;

129
jecs.luau
View file

@ -1,3 +1,4 @@
--!optimize 2
--!native
--!strict
@ -94,29 +95,31 @@ type ecs_world_t = {
observable: Map<i53, Map<i53, { ecs_observer_t }>>,
}
local HI_COMPONENT_ID = _G.__JECS_HI_COMPONENT_ID or 256
-- stylua: ignore start
local EcsOnAdd = HI_COMPONENT_ID + 1
local EcsOnRemove = HI_COMPONENT_ID + 2
local EcsOnChange = HI_COMPONENT_ID + 3
local EcsWildcard = HI_COMPONENT_ID + 4
local EcsChildOf = HI_COMPONENT_ID + 5
local EcsComponent = HI_COMPONENT_ID + 6
local EcsOnDelete = HI_COMPONENT_ID + 7
local EcsOnDeleteTarget = HI_COMPONENT_ID + 8
local EcsDelete = HI_COMPONENT_ID + 9
local EcsRemove = HI_COMPONENT_ID + 10
local EcsName = HI_COMPONENT_ID + 11
local EcsOnArchetypeCreate = HI_COMPONENT_ID + 12
local EcsOnArchetypeDelete = HI_COMPONENT_ID + 13
local EcsRest = HI_COMPONENT_ID + 14
local ECS_ID_DELETE = 0b01
local ECS_ID_IS_TAG = 0b10
local ECS_ID_MASK = 0b00
local ECS_ENTITY_MASK = bit32.lshift(1, 24)
local ECS_GENERATION_MASK = bit32.lshift(1, 16)
local ECS_PAIR_OFFSET = 2^48
local ECS_ENTITY_MASK = bit32.lshift(1, 24)
local ECS_GENERATION_MASK = bit32.lshift(1, 16)
local ECS_ID_DELETE = 0b01
local ECS_ID_IS_TAG = 0b10
local ECS_ID_MASK = 0b00
local HI_COMPONENT_ID = 256
local EcsOnAdd = HI_COMPONENT_ID + 1
local EcsOnRemove = HI_COMPONENT_ID + 2
local EcsOnChange = HI_COMPONENT_ID + 3
local EcsWildcard = HI_COMPONENT_ID + 4
local EcsChildOf = HI_COMPONENT_ID + 5
local EcsComponent = HI_COMPONENT_ID + 6
local EcsOnDelete = HI_COMPONENT_ID + 7
local EcsOnDeleteTarget = HI_COMPONENT_ID + 8
local EcsDelete = HI_COMPONENT_ID + 9
local EcsRemove = HI_COMPONENT_ID + 10
local EcsName = HI_COMPONENT_ID + 11
local EcsOnArchetypeCreate = HI_COMPONENT_ID + 12
local EcsOnArchetypeDelete = HI_COMPONENT_ID + 13
local EcsRest = HI_COMPONENT_ID + 14
local NULL_ARRAY = table.freeze({}) :: Column
local NULL = newproxy(false)
@ -168,7 +171,6 @@ end
local function ECS_COMBINE(id: number, generation: number): i53
return id + (generation * ECS_ENTITY_MASK)
end
local ECS_PAIR_OFFSET = 2^48
local function ECS_IS_PAIR(e: number): boolean
return e > ECS_PAIR_OFFSET
@ -824,7 +826,7 @@ local function world_entity(world: ecs_world_t, entity: i53?): i53
return entity
end
end
return entity_index_new_id(entity_index, entity)
return entity_index_new_id(entity_index)
end
local function world_parent(world: ecs_world_t, entity: i53)
@ -1050,7 +1052,7 @@ local function world_remove(world: ecs_world_t, entity: i53, id: i53)
end
end
local function archetype_fast_delete_last(columns: { Column }, column_count: number, types: { i53 }, entity: i53)
local function archetype_fast_delete_last(columns: { Column }, column_count: number)
for i, column in columns do
if column ~= NULL_ARRAY then
column[column_count] = nil
@ -1058,7 +1060,7 @@ local function archetype_fast_delete_last(columns: { Column }, column_count: num
end
end
local function archetype_fast_delete(columns: { Column }, column_count: number, row, types, entity)
local function archetype_fast_delete(columns: { Column }, column_count: number, row: number)
for i, column in columns do
if column ~= NULL_ARRAY then
column[row] = column[column_count]
@ -1100,9 +1102,9 @@ local function archetype_delete(world: ecs_world_t, archetype: ecs_archetype_t,
entities[last] = nil :: any
if row == last then
archetype_fast_delete_last(columns, column_count, id_types, delete)
archetype_fast_delete_last(columns, column_count)
else
archetype_fast_delete(columns, column_count, row, id_types, delete)
archetype_fast_delete(columns, column_count, row)
end
end
@ -1408,14 +1410,14 @@ local function world_delete(world: ecs_world_t, entity: i53)
local tr = idr_r_archetype.records[rel]
local tr_count = idr_r_archetype.counts[rel]
local types = idr_r_archetype.types
for i = tr, tr_count do
ids[types[tr]] = true
for i = tr, tr + tr_count - 1 do
ids[types[i]] = true
end
local n = #entities
table.move(entities, 1, n, count + 1, children)
count += n
end
for _, child in children do
for id in ids do
world_remove(world, child, id)
@ -1933,6 +1935,9 @@ local function query_cached(query: ecs_query_data_t)
local function on_delete_callback(archetype)
local i = table.find(archetypes, archetype) :: number
if i == nil then
return
end
local n = #archetypes
archetypes[i] = archetypes[n]
archetypes[n] = nil
@ -2521,8 +2526,8 @@ end
World.new = world_new
export type Entity<T = any> = { __T: T }
export type Id<T = any> = { __T: T }
export type Entity<T = any> = number | { __T: T }
export type Id<T = any> = number | { __T: T }
export type Pair<P, O> = Id<P>
type ecs_id_t<T=unknown> = Id<T> | Pair<T, "Tag"> | Pair<"Tag", T>
export type Item<T...> = (self: Query<T...>) -> (Entity, T...)
@ -2570,46 +2575,46 @@ export type World = {
range: (self: World, range_begin: number, range_end: number?) -> (),
--- Creates a new entity
entity: (self: World, id: Entity?) -> Entity,
entity: <T>(self: World, id: Entity<T>?) -> Entity<T>,
--- Creates a new entity located in the first 256 ids.
--- These should be used for static components for fast access.
component: <T>(self: World) -> Entity<T>,
--- Gets the target of an relationship. For example, when a user calls
--- `world:target(id, ChildOf(parent), 0)`, you will obtain the parent entity.
target: <T>(self: World, id: Entity, relation: Id<T>, index: number?) -> Entity?,
target: <T, a>(self: World, id: Entity<T>, relation: Id<a>, index: number?) -> Entity?,
--- Deletes an entity and all it's related components and relationships.
delete: (self: World, id: Entity) -> (),
delete: <T>(self: World, id: Entity<T>) -> (),
--- Adds a component to the entity with no value
add: <T>(self: World, id: Entity, component: Id<T>) -> (),
add: <T, a>(self: World, id: Entity<T>, component: Id<a>) -> (),
--- Assigns a value to a component on the given entity
set: <T>(self: World, id: Entity, component: Id<T>, data: T) -> (),
set: <T, a>(self: World, id: Entity<T>, component: Id<a>, data: a) -> (),
cleanup: (self: World) -> (),
-- Clears an entity from the world
clear: <T>(self: World, id: Id<T>) -> (),
clear: <a>(self: World, id: Id<a>) -> (),
--- Removes a component from the given entity
remove: <T>(self: World, id: Entity, component: Id<T>) -> (),
remove: <T, a>(self: World, id: Entity<T>, component: Id<a>) -> (),
--- Retrieves the value of up to 4 components. These values may be nil.
get: (<A>(self: World, id: Entity, Id<A>) -> A?)
& (<A, B>(self: World, id: Entity, Id<A>, Id<B>) -> (A?, B?))
& (<A, B, C>(self: World, id: Entity, Id<A>, Id<B>, Id<C>) -> (A?, B?, C?))
& <A, B, C, D>(self: World, id: Entity, Id<A>, Id<B>, Id<C>, Id<D>) -> (A?, B?, C?, D?),
get: & (<T, a>(World, Entity<T>, Id<a>) -> a?)
& (<T, a, b>(World, Entity<T>, Id<a>, Id<b>) -> (a?, b?))
& (<T, a, b, c>(World, Entity<T>, Id<a>, Id<b>, Id<c>) -> (a?, b?, c?))
& (<T, a, b, c, d>(World, Entity<T>, Id<a>, Id<b>, Id<c>, Id<d>) -> (a?, b?, c?, d?)),
--- Returns whether the entity has the ID.
has: (<A>(World, Entity, A) -> boolean)
& (<A, B>(World, Entity, A, B) -> boolean)
& (<A, B, C>(World, Entity, A, B, C) -> boolean)
& <A, B, C, D>(World, Entity, A, B, C, D) -> boolean,
has: (<T, a>(World, Entity<T>, Id<a>) -> boolean)
& (<T, a, b >(World, Entity<T>, Id<a>, Id<a>) -> boolean)
& (<T, a, b, c>(World, Entity<T>, Id<a>, Id<b>, Id<c>) -> boolean)
& <T, a, b, c, d>(World, Entity<T>, Id<a>, Id<b>, Id<c>, Id<d>) -> boolean,
--- Get parent (target of ChildOf relationship) for entity. If there is no ChildOf relationship pair, it will return nil.
parent:(self: World, entity: Entity) -> Entity,
parent: <T>(self: World, entity: Entity<T>) -> Entity,
--- Checks if the world contains the given entity
contains:(self: World, entity: Entity) -> boolean,
contains: <T>(self: World, entity: Entity<T>) -> boolean,
--- Checks if the entity exists
exists: (self: World, entity: Entity) -> boolean,
exists: <T>(self: World, entity: Entity<T>) -> boolean,
each: <T>(self: World, id: Id<T>) -> () -> Entity,
@ -2651,19 +2656,19 @@ return {
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<(entity: Entity) -> ()>,
OnRemove = EcsOnRemove :: Entity<(entity: Entity) -> ()>,
OnChange = EcsOnChange :: Entity<(entity: Entity, data: any) -> ()>,
ChildOf = EcsChildOf :: Entity,
Component = EcsComponent :: Entity,
Wildcard = EcsWildcard :: Entity,
w = EcsWildcard :: Entity,
OnDelete = EcsOnDelete :: Entity,
OnDeleteTarget = EcsOnDeleteTarget :: Entity,
Delete = EcsDelete :: Entity,
Remove = EcsRemove :: Entity,
Name = EcsName :: Entity<string>,
Rest = EcsRest :: Entity,
OnAdd = (EcsOnAdd :: any) :: Entity<<T>(entity: Entity, id: Id<T>, data: T) -> ()>,
OnRemove = (EcsOnRemove :: any) :: Entity<(entity: Entity, id: Id) -> ()>,
OnChange = (EcsOnChange :: any) :: Entity<<T>(entity: Entity, id: Id<T>, data: T) -> ()>,
ChildOf = (EcsChildOf :: any) :: Entity,
Component = (EcsComponent :: any) :: Entity,
Wildcard = (EcsWildcard :: any) :: Entity,
w = (EcsWildcard :: any) :: Entity,
OnDelete = (EcsOnDelete :: any) :: Entity,
OnDeleteTarget = (EcsOnDeleteTarget :: any) :: Entity,
Delete = (EcsDelete :: any) :: Entity,
Remove = (EcsRemove :: any) :: Entity,
Name = (EcsName :: any) :: Entity<string>,
Rest = (EcsRest :: any) :: Entity,
pair = (ECS_PAIR :: any) :: <P, O>(first: Id<P>, second: Id<O>) -> Pair<P, O>,

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "@rbxts/jecs",
"version": "0.6.0-rc.1",
"version": "0.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@rbxts/jecs",
"version": "0.6.0-rc.1",
"version": "0.6.0",
"license": "MIT",
"devDependencies": {
"@rbxts/compiler-types": "^2.3.0-types.1",

View file

@ -1,6 +1,6 @@
{
"name": "@rbxts/jecs",
"version": "0.6.0",
"version": "0.6.1",
"description": "Stupidly fast Entity Component System",
"main": "jecs.luau",
"repository": {

View file

@ -4,114 +4,132 @@ local test = testkit.test()
local CASE, TEST, FINISH, CHECK = test.CASE, test.TEST, test.FINISH, test.CHECK
local observers_add = require("@addons/observers")
TEST("addons/observers", function()
local world = observers_add(jecs.world())
local Test = world:component() :: jecs.Id<number>
type Q<T...> = () -> (jecs.Entity, T...)
local query:
(<A>(jecs.World, jecs.Id<A>) -> Q<A>)
& (<A, B>(jecs.World, jecs.Id<A>, jecs.Id<B>) -> Q<A, B>)
& (<A, B, C>(jecs.World, jecs.Id<A>, jecs.Id<B>, jecs.Id<C>) -> Q<A, B, C>)
= 1 :: never
for e, a in query(world, Test) do
end
do CASE "Should work even if set after the component has been used"
local A = world:component()
world:set(world:entity(), A, 2)
local ran = true
world:added(A, function()
ran = false
end)
local entity = world:entity()
world:set(entity, A, 3)
CHECK(ran)
end
do CASE "Should not override hook"
local A = world:component()
local count = 0
local count = 1
local function counter()
count += 1
count += 2
end
world:set(A, jecs.OnAdd, counter)
world:set(world:entity(), A, true)
CHECK(count == 1)
world:added(A, counter)
world:set(world:entity(), A, true)
world:set(world:entity(), A, false)
CHECK(count == 3)
world:set(world:entity(), A, false)
CHECK(count == 5)
end
do CASE "Ensure ordering between signals and observers"
local A = world:component()
local B = world:component()
local count = 0
local count = 1
local function counter()
count += 1
count += 2
end
world:observer({
callback = counter,
query = world:query(A, B),
})
world:observer(world:query(A, B), counter)
world:added(A, counter)
world:added(A, counter)
local e = world:entity()
world:add(e, A)
CHECK(count == 2)
CHECK(count == 3)
world:add(e, B)
CHECK(count == 3)
CHECK(count == 4)
end
do CASE "Rematch entities in observers"
local A = world:component()
local count = 0
local count = 1
local function counter()
count += 1
count += 2
end
world:observer({
query = world:query(A),
callback = counter
})
world:observer(world:query(A), counter)
local e = world:entity()
world:set(e, A, true)
CHECK(count == 1)
world:remove(e, A)
CHECK(count == 1)
world:set(e, A, true)
world:set(e, A, false)
CHECK(count == 2)
world:set(e, A, true)
world:remove(e, A)
CHECK(count == 2)
world:set(e, A, false)
CHECK(count == 3)
world:set(e, A, false)
CHECK(count == 4)
end
do CASE "Don't report changed components in monitor"
local A = world:component()
local count = 0
local count = 1
local function counter()
count += 1
count += 2
end
world:monitor({
query = world:query(A),
callback = counter
})
world:monitor(world:query(A), counter)
local e = world:entity()
world:set(e, A, true)
CHECK(count == 1)
world:remove(e, A)
world:set(e, A, false)
CHECK(count == 2)
world:set(e, A, true)
CHECK(count == 3)
world:set(e, A, true)
world:remove(e, A)
CHECK(count == 3)
world:set(e, A, false)
CHECK(count == 4)
world:set(e, A, false)
CHECK(count == 4)
end
do CASE "Call on pairs"
do CASE "Call off pairs"
local A = world:component()
local callcount = 0
local callcount = 1
world:added(A, function(entity)
callcount += 1
callcount += 2
end)
world:added(A, function(entity)
callcount += 1
callcount += 2
end)
local e = world:entity()
local e1 = world:entity()
local e2 = world:entity()
world:add(e1, jecs.pair(A, e))
world:add(e, jecs.pair(A, e1))
CHECK(callcount == 4)
world:add(e2, jecs.pair(A, e))
world:add(e, jecs.pair(A, e2))
CHECK(callcount == 5)
end
end)

View file

@ -289,6 +289,27 @@ TEST("world:contains()", function()
end)
TEST("world:delete()", function()
do CASE "remove (*, R) pairs when relationship is invalidated"
print("-------")
local world = jecs.world()
local e1 = world:entity()
local e2 = world:entity()
local A = world:component()
local B = world:component()
local C = world:component()
world:add(e1, pair(e2, A))
world:add(e1, B) -- Some stable component that should not be removed in the process
world:add(e1, pair(e2, C))
world:delete(e2)
CHECK(not world:contains(e2))
CHECK(not world:has(e1, pair(e2, A)))
CHECK(world:has(e1, B))
CHECK(not world:has(e1, pair(e2, C)))
CHECK(world:contains(e1))
end
do CASE "remove pair when relationship is deleted"
local world = jecs.world()
local e1 = world:entity()
@ -661,7 +682,7 @@ TEST("world:range()", function()
do CASE "under range start"
local world = jecs.world()
world:range(400, 1000)
local id = world:entity()
local id = world:entity() :: number
local e = world:entity(id + 5)
CHECK(e == id + 5)
CHECK(world:contains(e))
@ -669,7 +690,7 @@ TEST("world:range()", function()
CHECK(world:contains(e2))
world:delete(e2)
CHECK(not world:contains(e2))
local e2v1 = world:entity(399)
local e2v1 = world:entity(399) :: number
CHECK(world:contains(e2v1))
CHECK(ECS_ID(e2v1) == 399)
CHECK(ECS_GENERATION(e2v1) == 0)
@ -682,13 +703,13 @@ TEST("world:range()", function()
CHECK(world:contains(e2))
world:delete(e2)
CHECK(not world:contains(e2))
local e2v1 = world:entity(405)
local e2v1 = world:entity(405) :: number
CHECK(world:contains(e2v1))
CHECK(ECS_ID(e2v1) == 405)
CHECK(ECS_GENERATION(e2v1) == 0)
world:delete(e2v1)
local e2v2 = world:entity(e2v1)
local e2v2 = world:entity(e2v1) :: number
CHECK(ECS_ID(e2v2) == 405)
CHECK(ECS_GENERATION(e2v2) == 0)
end
@ -697,7 +718,7 @@ end)
TEST("world:entity()", function()
do CASE "desired id"
local world = jecs.world()
local id = world:entity()
local id = world:entity() :: number
local e = world:entity(id + 5)
CHECK(e == id + 5)
CHECK(world:contains(e))
@ -767,11 +788,11 @@ TEST("world:entity()", function()
local e = world:entity()
world:delete(e)
end
local e = world:entity() :: any
local e = world:entity() :: number
CHECK(ECS_ID(e) == pin)
CHECK(ECS_GENERATION(e) == 2^16-1)
world:delete(e)
e = world:entity()
e = world:entity() :: number
CHECK(ECS_ID(e) == pin)
CHECK(ECS_GENERATION(e) == 0)
end

View file

@ -1,6 +1,6 @@
[package]
name = "ukendio/jecs"
version = "0.6.0"
version = "0.6.1"
registry = "https://github.com/UpliftGames/wally-index"
realm = "shared"
license = "MIT"