Compare commits
No commits in common. "main" and "0.5.5" have entirely different histories.
9
.github/ISSUE_TEMPLATE/BUG-REPORT.md
vendored
Executable file → Normal file
|
|
@ -1,25 +1,22 @@
|
|||
---
|
||||
name: Bug report
|
||||
about: File a bug report for any behavior that you believe is unintentional or problematic
|
||||
title: ""
|
||||
title: "[BUG]"
|
||||
labels: bug
|
||||
assignees: ""
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Describe the bug
|
||||
|
||||
Put a clear and concise description of what the bug is. This should be short and to the point, not to exceed more than a paragraph. Put the details inside your reproduction steps.
|
||||
|
||||
## Reproduction
|
||||
|
||||
Make an easy-to-follow guide on how to reproduce it. Does it happen all the time? Will specific features affect reproduction? All these questions should be answered for a good issue.
|
||||
|
||||
This is a good place to put rbxl files or scripts that help explain your reproduction steps.
|
||||
|
||||
## Expected Behavior
|
||||
|
||||
What you expect to happen
|
||||
|
||||
## Actual Behavior
|
||||
|
||||
What actually happens
|
||||
14
.github/ISSUE_TEMPLATE/DOCUMENTATION.md
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
---
|
||||
name: Documentation
|
||||
about: Open an issue to add, change, or otherwise modify any part of the documentation.
|
||||
title: "[DOCS]"
|
||||
labels: documentation
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Which Sections Does This Issue Cover?
|
||||
[Put sections (e.g. Query Concepts), page links, etc as necessary]
|
||||
|
||||
## What Needs To Change?
|
||||
What specifically needs to change and what suggestions do you have to change it?
|
||||
6
.github/ISSUE_TEMPLATE/FEATURE-REQUEST.md
vendored
Executable file → Normal file
|
|
@ -1,9 +1,10 @@
|
|||
---
|
||||
name: Feature Request
|
||||
about: File a feature request for something you believe should be added to Jecs
|
||||
title: ""
|
||||
title: "[FEATURE]"
|
||||
labels: enhancement
|
||||
assignees: ""
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Describe your Feature
|
||||
|
|
@ -21,7 +22,6 @@ What other alternative implementations or otherwise relevant information is impo
|
|||
## Considerations
|
||||
|
||||
Some questions that need to be answered include the following:
|
||||
|
||||
- Will old code break in response to this feature?
|
||||
- What are the performance impacts with this feature (if any)?
|
||||
- How is it useful to include?
|
||||
|
|
|
|||
0
.github/PULL_REQUEST_TEMPLATE.md
vendored
Executable file → Normal file
5
.github/workflows/analysis.yaml
vendored
Executable file → Normal file
|
|
@ -11,11 +11,8 @@ jobs:
|
|||
- name: Checkout Project
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rokit
|
||||
uses: CompeyDev/setup-rokit@v0.1.2
|
||||
|
||||
- name: Install Luau
|
||||
run: rokit install --no-trust-check
|
||||
uses: encodedvenom/install-luau@v4.3
|
||||
|
||||
- name: Analyze
|
||||
run: |
|
||||
|
|
|
|||
26
.github/workflows/build-studio-docs.yaml
vendored
|
|
@ -1,26 +0,0 @@
|
|||
name: build-studio-docs
|
||||
|
||||
on:
|
||||
push:
|
||||
schedule:
|
||||
- cron: "10 0 1 * *" # Artifacts expire every 90 days. Doesn't hurt to just run this workflow first day of every month at 00:10 UTC.
|
||||
|
||||
jobs:
|
||||
studio-docs:
|
||||
name: Build Studio Docs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Project
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rokit
|
||||
uses: CompeyDev/setup-rokit@v0.1.2
|
||||
|
||||
- name: Build Studio Docs
|
||||
run: zune run scripts/build_studio_docs
|
||||
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: studio_docs
|
||||
path: studio_docs.rbxm
|
||||
11
.github/workflows/dependabot.yml
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
64
.github/workflows/deploy-docs.yaml
vendored
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
# Sample workflow for building and deploying a VitePress site to GitHub Pages
|
||||
#
|
||||
name: deploy-docs
|
||||
|
||||
on:
|
||||
# Runs on pushes targeting the `main` branch. Change this to `master` if you're
|
||||
# using the `master` branch as the default branch.
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
|
||||
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# Build job
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Not needed if lastUpdated is not enabled
|
||||
# - uses: pnpm/action-setup@v3 # Uncomment this if you're using pnpm
|
||||
# - uses: oven-sh/setup-bun@v1 # Uncomment this if you're using Bun
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm # or pnpm / yarn
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v4
|
||||
- name: Install dependencies
|
||||
run: npm ci # or pnpm install / yarn install / bun install
|
||||
- name: Build with VitePress
|
||||
run: npm run docs:build # or pnpm docs:build / yarn docs:build / bun run docs:build
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: docs/.vitepress/dist
|
||||
|
||||
# Deployment job
|
||||
deploy:
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
name: Deploy
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
0
.github/workflows/publish-npm.yml
vendored
Executable file → Normal file
6
.github/workflows/release.yaml
vendored
Executable file → Normal file
|
|
@ -2,7 +2,7 @@ name: release
|
|||
|
||||
on:
|
||||
push:
|
||||
tags: ["v*", "workflow_dispatch"]
|
||||
tags: ["v*"]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
|
@ -22,7 +22,7 @@ jobs:
|
|||
run: rojo build --output build.rbxm default.project.json
|
||||
|
||||
- name: Upload Build Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: build
|
||||
path: build.rbxm
|
||||
|
|
@ -38,7 +38,7 @@ jobs:
|
|||
uses: actions/checkout@v4
|
||||
|
||||
- name: Download Jecs Build
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: build
|
||||
path: build
|
||||
|
|
|
|||
7
.github/workflows/unit-testing.yaml
vendored
Executable file → Normal file
|
|
@ -12,8 +12,11 @@ jobs:
|
|||
- name: Checkout Project
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rokit
|
||||
uses: CompeyDev/setup-rokit@v0.1.2
|
||||
- name: Install Luau
|
||||
uses: encodedvenom/install-luau@v4.3
|
||||
with:
|
||||
version: "latest"
|
||||
verbose: "true"
|
||||
|
||||
- name: Run Unit Tests
|
||||
id: run_tests
|
||||
|
|
|
|||
11
.gitignore
vendored
Executable file → Normal file
|
|
@ -65,14 +65,3 @@ drafts/
|
|||
|
||||
# Luau tools
|
||||
profile.*
|
||||
|
||||
# Patch files
|
||||
|
||||
*.patch
|
||||
|
||||
genhtml.perl
|
||||
|
||||
rokit.toml
|
||||
package-lock.json
|
||||
mirror.luau
|
||||
studio_docs/
|
||||
|
|
|
|||
6
.luaurc
Executable file → Normal file
|
|
@ -1,8 +1,8 @@
|
|||
{
|
||||
"aliases": {
|
||||
"jecs": "./src/jecs",
|
||||
"modules": "./modules",
|
||||
"mirror": "./src/mirror",
|
||||
"jecs": "jecs",
|
||||
"testkit": "test/testkit",
|
||||
"mirror": "mirror"
|
||||
},
|
||||
"languageMode": "strict"
|
||||
}
|
||||
|
|
|
|||
6
.prettierrc
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"printWidth": 120,
|
||||
"tabWidth": 4,
|
||||
"trailingComma": "all",
|
||||
"useTabs": true
|
||||
}
|
||||
359
CHANGELOG.md
Executable file → Normal file
|
|
@ -1,212 +1,205 @@
|
|||
# Changelog
|
||||
# Jecs Changelog
|
||||
|
||||
## Unreleased
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
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]
|
||||
|
||||
- `[world]`:
|
||||
- 16% faster `world:get`
|
||||
- `world:has` no longer typechecks components after the 8th one.
|
||||
- `[typescript]`
|
||||
|
||||
- Fixed Entity type to default to `undefined | unknown` instead of just `undefined`
|
||||
|
||||
- `[query]`:
|
||||
- Fixed bug where `world:clear` did not invoke `jecs.OnRemove` hooks
|
||||
- Changed `query.__iter` to drain on iteration
|
||||
- It will initialize once wherever you left iteration off at last time
|
||||
- Changed `query:iter` to restart the iterator
|
||||
- Removed `query:drain` and `query:next`
|
||||
- If you want to get individual results outside of a for-loop, you need to call `query:iter` to initialize the iterator and then call the iterator function manually
|
||||
```lua
|
||||
local it = world:query(A, B, C):iter()
|
||||
local entity, a, b, c = it()
|
||||
entity, a, b, c = it() -- get next results
|
||||
```
|
||||
- `[world`
|
||||
- Fixed a bug with `world:clear` not invoking `jecs.OnRemove` hooks
|
||||
- `[typescript]`:
|
||||
- Changed pair to accept generics
|
||||
- Improved handling of Tags
|
||||
|
||||
## [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 signals that allow listening to relation part of pairs in signals.
|
||||
|
||||
- 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
|
||||
|
||||
### Changed
|
||||
- `OnRemove` hooks so that they are allowed to move entity's archetype even during deletion.
|
||||
|
||||
## 0.8.0
|
||||
- Iterator now goes backwards instead to prevent common cases of iterator invalidation
|
||||
|
||||
## [0.2.1] - 2024-07-06
|
||||
|
||||
### Added
|
||||
- `jecs.Exclusive` trait for making exclusive relationships.
|
||||
|
||||
- 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
|
||||
- `jecs.ChildOf` to be an exclusive relationship, which means you can only have one `ChildOf` pair on an entity.
|
||||
|
||||
## 0.7.2
|
||||
- Improved iteration speeds 20-40% by manually indexing rather than using `next()` :scream:
|
||||
|
||||
## [0.1.1] - 2024-05-19
|
||||
|
||||
### Added
|
||||
- `jecs.entity_index_try_get_fast` back as to not break the observer addon.
|
||||
|
||||
- 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
|
||||
|
||||
### Fixed
|
||||
- A linting problem with the types for `quer:with` and `query:without`.
|
||||
|
||||
- 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.7.0
|
||||
## [0.0.0-prototype.rc.3] - 2024-05-01
|
||||
|
||||
### Added
|
||||
- `jecs.component_record` for retrieving the component_record of a component.
|
||||
- `Column<T>` and `ColumnsMap<T>` types for typescript.
|
||||
- `bulk_insert` and `bulk_remove` respectively for moving an entity to an archetype without intermediate steps.
|
||||
|
||||
- Added observers
|
||||
- Added an arm to query `query:without()` for chaining invariants.
|
||||
|
||||
### Changed
|
||||
- The fields `archetype.records[id]` and `archetype.counts[id]` have been removed from the archetype struct and been moved to the component record `component_index[id].records[archetype.id]` and `component_index[id].counts[archetype.id]` respectively.
|
||||
- Removed the metatable `jecs.World`. Use `jecs.world()` to create your World.
|
||||
- Archetypes will no longer be garbage collected when invalidated, allowing them to be recycled to save a lot of performance during frequent deletion.
|
||||
- Removed `jecs.entity_index_try_get_fast`. Use `jecs.entity_index_try_get` instead.
|
||||
|
||||
## 0.6.1
|
||||
- Separates ranges for components and entity IDs.
|
||||
|
||||
- IDs created with `world:component()` will promote array lookups rather than map lookups in the `component_index` which is a significant boost
|
||||
|
||||
- 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
|
||||
|
||||
### Changed
|
||||
- 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
|
||||
- Optimized the creation of the query
|
||||
- It will now finds the smallest archetype map to iterate over
|
||||
- Optimized the query iterator
|
||||
|
||||
## 0.6.0
|
||||
- It will now populates iterator with columns for faster indexing
|
||||
|
||||
### Added
|
||||
- `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.
|
||||
- Renamed the insertion method from world:add to world:set to better reflect what it does.
|
||||
|
||||
### 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 1–5 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.
|
||||
## [0.0.0-prototype.rc.2] - 2024-04-23
|
||||
|
||||
### 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.
|
||||
- Initial release
|
||||
|
||||
## 0.5.0
|
||||
|
||||
### 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`.
|
||||
|
||||
### Fixed
|
||||
- `World:target` not giving adjacent pairs.
|
||||
|
||||
## 0.4.0
|
||||
|
||||
### Added
|
||||
- Recycling support to `world:entity` so reused entity IDs now increment generation.
|
||||
|
||||
### Removed
|
||||
- `Query:drain`
|
||||
- `Query:next`
|
||||
- `Query:replace`
|
||||
|
||||
### Changed
|
||||
- `jecs.Pair` type in Luau now returns the first element's type to avoid manual typecasting.
|
||||
|
||||
### 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 20–40% 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.
|
||||
[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
|
||||
|
|
|
|||
0
LICENSE
Executable file → Normal file
61
README.md
Executable file → Normal file
|
|
@ -1,3 +1,9 @@
|
|||
<p align="center">
|
||||
<img src="assets/image-5.png" width=35%/>
|
||||
</p>
|
||||
|
||||
[](LICENSE) [](https://wally.run/package/ukendio/jecs)
|
||||
|
||||
Just a stupidly fast Entity Component System
|
||||
|
||||
- [Entity Relationships](https://ajmmertens.medium.com/building-games-in-ecs-with-entity-relationships-657275ba2c6c) as first class citizens
|
||||
|
|
@ -6,30 +12,53 @@ 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/unit-testing.yaml) for stability
|
||||
- Rigorously [unit tested](https://github.com/Ukendio/jecs/actions/workflows/ci.yaml) for stability
|
||||
|
||||
### Get Started
|
||||
It is recommended that you clone the repository and navigate the documentation in your favourite editor.
|
||||
### Example
|
||||
|
||||
This repository includes a few subfolders that can help you get started with jecs:
|
||||
```lua
|
||||
local world = jecs.World.new()
|
||||
local pair = jecs.pair
|
||||
|
||||
- how_to:
|
||||
This is a step-by-step introduction to how this ECS works and the reasoning behind its design.
|
||||
-- These components and functions are actually already builtin
|
||||
-- but have been illustrated for demonstration purposes
|
||||
local ChildOf = world:component()
|
||||
local Name = world:component()
|
||||
|
||||
- modules:
|
||||
These are regularly used modules and should be mostly working, but some might not be. You can look in this folder to see some code that you might use to help you hit the ground running quickly.
|
||||
local function parent(entity)
|
||||
return world:target(entity, ChildOf)
|
||||
end
|
||||
local function getName(entity)
|
||||
return world:get(entity, Name)
|
||||
end
|
||||
|
||||
- examples:
|
||||
These are larger programs that showcase real use cases and can help you understand how everything fits together.
|
||||
local alice = world:entity()
|
||||
world:set(alice, Name, "alice")
|
||||
|
||||
If you wish to view the documentation inside Roblox Studio, you can find an importable model file [here](https://nightly.link/Ukendio/jecs/workflows/build-studio-docs.yaml/main/studio_docs.zip).
|
||||
local bob = world:entity()
|
||||
world:add(bob, pair(ChildOf, alice))
|
||||
world:set(bob, Name, "bob")
|
||||
|
||||
### Benchmarks
|
||||
local sara = world:entity()
|
||||
world:add(sara, pair(ChildOf, alice))
|
||||
world:set(sara, Name, "sara")
|
||||
|
||||
print(getName(parent(sara)))
|
||||
|
||||
for e in world:query(pair(ChildOf, alice)) do
|
||||
print(getName(e), "is the child of alice")
|
||||
end
|
||||
|
||||
-- Output
|
||||
-- "alice"
|
||||
-- bob is the child of alice
|
||||
-- sara is the child of alice
|
||||
```
|
||||
|
||||
21,000 entities 125 archetypes 4 random components queried.
|
||||

|
||||
Can be found under /test/benches/visual/query.luau
|
||||

|
||||
Can be found under /benches/visual/query.luau
|
||||
|
||||
Inserting 8 components to an entity and updating them over 50 times.
|
||||

|
||||
Can be found under /test/benches/visual/insertions.luau
|
||||

|
||||
Can be found under /benches/visual/insertions.luau
|
||||
|
|
|
|||
0
test/benches/data/image-1.png → assets/image-1.png
Executable file → Normal file
|
Before Width: | Height: | Size: 392 KiB After Width: | Height: | Size: 392 KiB |
0
test/benches/data/image-2.png → assets/image-2.png
Executable file → Normal file
|
Before Width: | Height: | Size: 391 KiB After Width: | Height: | Size: 391 KiB |
0
test/benches/data/image-3.png → assets/image-3.png
Executable file → Normal file
|
Before Width: | Height: | Size: 61 KiB After Width: | Height: | Size: 61 KiB |
0
test/benches/data/image-4.png → assets/image-4.png
Executable file → Normal file
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 103 KiB |
0
test/benches/data/image-5.png → assets/image-5.png
Executable file → Normal file
|
Before Width: | Height: | Size: 8.7 KiB After Width: | Height: | Size: 8.7 KiB |
0
test/benches/data/jecs_darkmode.svg → assets/jecs_darkmode.svg
Executable file → Normal file
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.2 KiB |
0
test/benches/data/jecs_lightmode.svg → assets/jecs_lightmode.svg
Executable file → Normal file
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.2 KiB |
0
test/benches/data/logo_old.png → assets/logo_old.png
Executable file → Normal file
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 68 KiB |
8
test/benches/default.project.json → bench.project.json
Executable file → Normal file
|
|
@ -12,16 +12,16 @@
|
|||
"ReplicatedStorage": {
|
||||
"$className": "ReplicatedStorage",
|
||||
"Lib": {
|
||||
"$path": "../../src/jecs.luau"
|
||||
"$path": "jecs.luau"
|
||||
},
|
||||
"benches": {
|
||||
"$path": "visual"
|
||||
"$path": "benches"
|
||||
},
|
||||
"mirror": {
|
||||
"$path": "../../src/mirror.luau"
|
||||
"$path": "mirror.luau"
|
||||
},
|
||||
"DevPackages": {
|
||||
"$path": "visual/DevPackages"
|
||||
"$path": "benches/visual/DevPackages"
|
||||
}
|
||||
}
|
||||
}
|
||||
2
test/benches/cached.luau → benches/cached.luau
Executable file → Normal file
|
|
@ -1,5 +1,5 @@
|
|||
local jecs = require("@jecs")
|
||||
local mirror = require("@mirror")
|
||||
local mirror = require("../mirror/init")
|
||||
|
||||
type i53 = number
|
||||
|
||||
51
test/benches/general.luau → benches/general.luau
Executable file → Normal file
|
|
@ -1,5 +1,5 @@
|
|||
local jecs = require("@jecs")
|
||||
local testkit = require("@modules/testkit")
|
||||
local testkit = require("@testkit")
|
||||
|
||||
local BENCH, START = testkit.benchmark()
|
||||
|
||||
|
|
@ -14,7 +14,7 @@ local pair = jecs.pair
|
|||
|
||||
do
|
||||
TITLE("create")
|
||||
local world = jecs.world()
|
||||
local world = jecs.World.new()
|
||||
|
||||
BENCH("entity", function()
|
||||
for i = 1, START(N) do
|
||||
|
|
@ -35,8 +35,8 @@ end
|
|||
do
|
||||
TITLE("set")
|
||||
|
||||
local world = jecs.world()
|
||||
local A = world:component()
|
||||
local world = jecs.World.new()
|
||||
local A = world:entity()
|
||||
|
||||
local entities = table.create(N)
|
||||
|
||||
|
|
@ -69,8 +69,8 @@ end
|
|||
do
|
||||
TITLE("set relationship")
|
||||
|
||||
local world = jecs.world()
|
||||
local A = world:component()
|
||||
local world = jecs.World.new()
|
||||
local A = world:entity()
|
||||
|
||||
local entities = table.create(N)
|
||||
|
||||
|
|
@ -103,7 +103,7 @@ end
|
|||
do
|
||||
TITLE("get")
|
||||
|
||||
local world = jecs.world()
|
||||
local world = jecs.World.new()
|
||||
local A = world:component()
|
||||
local B = world:component()
|
||||
local C = world:component()
|
||||
|
|
@ -147,7 +147,7 @@ do
|
|||
TITLE("target")
|
||||
|
||||
BENCH("1st target", function()
|
||||
local world = jecs.world()
|
||||
local world = jecs.World.new()
|
||||
local A = world:component()
|
||||
local B = world:component()
|
||||
local C = world:component()
|
||||
|
|
@ -179,7 +179,7 @@ do
|
|||
|
||||
local function view_bench(n: number)
|
||||
BENCH(`{n} entities per archetype`, function()
|
||||
local world = jecs.world()
|
||||
local world = jecs.World.new()
|
||||
|
||||
local A = world:component()
|
||||
local B = world:component()
|
||||
|
|
@ -194,19 +194,17 @@ do
|
|||
world:set(id, B, true)
|
||||
world:set(id, C, true)
|
||||
world:set(id, D, true)
|
||||
world:add(id, ct)
|
||||
world:set(id, ct, true)
|
||||
end
|
||||
end
|
||||
|
||||
local q = world:query(A, B, C, D)
|
||||
q:archetypes()
|
||||
START()
|
||||
for id in q do
|
||||
for id in world:query(A, B, C, D) do
|
||||
end
|
||||
end)
|
||||
|
||||
BENCH(`inlined query`, function()
|
||||
local world = jecs.world()
|
||||
local world = jecs.World.new()
|
||||
local A = world:component()
|
||||
local B = world:component()
|
||||
local C = world:component()
|
||||
|
|
@ -220,28 +218,17 @@ do
|
|||
world:set(id, B, true)
|
||||
world:set(id, C, true)
|
||||
world:set(id, D, true)
|
||||
world:add(id, ct)
|
||||
world:set(id, ct, true)
|
||||
end
|
||||
end
|
||||
|
||||
local archetypes = world:query(A, B, C, D):archetypes()
|
||||
START()
|
||||
-- for _, archetype in archetypes do
|
||||
-- local columns, records = archetype.columns, archetype.records
|
||||
-- local a = columns[records[A]]
|
||||
-- local b = columns[records[B]]
|
||||
-- local c = columns[records[C]]
|
||||
-- local d = columns[records[D]]
|
||||
-- for row in archetype.entities do
|
||||
-- local _1, _2, _3, _4 = a[row], b[row], c[row], d[row]
|
||||
-- end
|
||||
-- end
|
||||
for _, archetype in archetypes do
|
||||
local columns_map = archetype.columns_map
|
||||
local a = columns_map[A]
|
||||
local b = columns_map[B]
|
||||
local c = columns_map[C]
|
||||
local d = columns_map[D]
|
||||
for _, archetype in world:query(A, B, C, D):archetypes() do
|
||||
local columns, records = archetype.columns, archetype.records
|
||||
local a = columns[records[A].column]
|
||||
local b = columns[records[B].column]
|
||||
local c = columns[records[C].column]
|
||||
local d = columns[records[D].column]
|
||||
for row in archetype.entities do
|
||||
local _1, _2, _3, _4 = a[row], b[row], c[row], d[row]
|
||||
end
|
||||
118
test/benches/query.luau → benches/query.luau
Executable file → Normal file
|
|
@ -1,7 +1,7 @@
|
|||
--!optimize 2
|
||||
--!native
|
||||
|
||||
local testkit = require("@modules/testkit")
|
||||
local testkit = require("@testkit")
|
||||
local BENCH, START = testkit.benchmark()
|
||||
local function TITLE(title: string)
|
||||
print()
|
||||
|
|
@ -11,27 +11,57 @@ end
|
|||
local jecs = require("@jecs")
|
||||
local mirror = require("@mirror")
|
||||
|
||||
type i53 = number
|
||||
|
||||
do
|
||||
TITLE(testkit.color.white_underline("Jecs query"))
|
||||
local ecs = jecs.world() :: jecs.World
|
||||
local ecs = jecs.World.new()
|
||||
do
|
||||
TITLE("one component in common")
|
||||
|
||||
local function view_bench(world: jecs.World,
|
||||
A: jecs.Id,
|
||||
B: jecs.Id,
|
||||
C: jecs.Id,
|
||||
D: jecs.Id,
|
||||
E: jecs.Id,
|
||||
F: jecs.Id,
|
||||
G: jecs.Id,
|
||||
H: jecs.Id
|
||||
)
|
||||
local function view_bench(world: jecs.World, A: i53, B: i53, C: i53, D: i53, E: i53, F: i53, G: i53, H: i53)
|
||||
BENCH("1 component", function()
|
||||
for _ in world:query(A) do
|
||||
end
|
||||
end)
|
||||
|
||||
BENCH("2 component", function()
|
||||
for _ in world:query(B, A) do
|
||||
end
|
||||
end)
|
||||
|
||||
BENCH("4 component", function()
|
||||
for _ in world:query(D, C, B, A) do
|
||||
end
|
||||
end)
|
||||
|
||||
BENCH("8 component", function()
|
||||
for _ in world:query(H, G, F, E, D, C, B, A) do
|
||||
end
|
||||
end)
|
||||
|
||||
local e = world:entity()
|
||||
world:set(e, A, true)
|
||||
world:set(e, B, true)
|
||||
world:set(e, C, true)
|
||||
world:set(e, D, true)
|
||||
world:set(e, E, true)
|
||||
world:set(e, F, true)
|
||||
world:set(e, G, true)
|
||||
world:set(e, H, true)
|
||||
|
||||
BENCH("Update Data", function()
|
||||
for _ = 1, 100 do
|
||||
world:set(e, A, false)
|
||||
world:set(e, B, false)
|
||||
world:set(e, C, false)
|
||||
world:set(e, D, false)
|
||||
world:set(e, E, false)
|
||||
world:set(e, F, false)
|
||||
world:set(e, G, false)
|
||||
world:set(e, H, false)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
local D1 = ecs:component()
|
||||
|
|
@ -49,9 +79,8 @@ do
|
|||
|
||||
local added = 0
|
||||
local archetypes = {}
|
||||
for i = 1, 2 ^ 12 - 2 do
|
||||
for i = 1, 2 ^ 16 - 2 do
|
||||
local entity = ecs:entity()
|
||||
ecs:add(entity, entity)
|
||||
|
||||
local combination = ""
|
||||
|
||||
|
|
@ -102,25 +131,53 @@ end
|
|||
|
||||
do
|
||||
TITLE(testkit.color.white_underline("Mirror query"))
|
||||
local ecs = mirror.World.new() :: jecs.World
|
||||
local ecs = mirror.World.new()
|
||||
do
|
||||
TITLE("one component in common")
|
||||
|
||||
local function view_bench(
|
||||
world: mirror.World,
|
||||
A: jecs.Id,
|
||||
B: jecs.Id,
|
||||
C: jecs.Id,
|
||||
D: jecs.Id,
|
||||
E: jecs.Id,
|
||||
F: jecs.Id,
|
||||
G: jecs.Id,
|
||||
H: jecs.Id
|
||||
)
|
||||
local function view_bench(world: jecs.World, A: i53, B: i53, C: i53, D: i53, E: i53, F: i53, G: i53, H: i53)
|
||||
BENCH("1 component", function()
|
||||
for _ in world:query(A) do
|
||||
end
|
||||
end)
|
||||
|
||||
BENCH("2 component", function()
|
||||
for _ in world:query(B, A) do
|
||||
end
|
||||
end)
|
||||
|
||||
BENCH("4 component", function()
|
||||
for _ in world:query(D, C, B, A) do
|
||||
end
|
||||
end)
|
||||
|
||||
BENCH("8 component", function()
|
||||
for _ in world:query(H, G, F, E, D, C, B, A) do
|
||||
end
|
||||
end)
|
||||
|
||||
local e = world:entity()
|
||||
world:set(e, A, true)
|
||||
world:set(e, B, true)
|
||||
world:set(e, C, true)
|
||||
world:set(e, D, true)
|
||||
world:set(e, E, true)
|
||||
world:set(e, F, true)
|
||||
world:set(e, G, true)
|
||||
world:set(e, H, true)
|
||||
|
||||
BENCH("Update Data", function()
|
||||
for _ = 1, 100 do
|
||||
world:set(e, A, false)
|
||||
world:set(e, B, false)
|
||||
world:set(e, C, false)
|
||||
world:set(e, D, false)
|
||||
world:set(e, E, false)
|
||||
world:set(e, F, false)
|
||||
world:set(e, G, false)
|
||||
world:set(e, H, false)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
local D1 = ecs:component()
|
||||
|
|
@ -133,14 +190,13 @@ do
|
|||
local D8 = ecs:component()
|
||||
|
||||
local function flip()
|
||||
return math.random() >= 0.5
|
||||
return math.random() >= 0.15
|
||||
end
|
||||
|
||||
local added = 0
|
||||
local archetypes = {}
|
||||
for i = 1, 2 ^ 12 - 2 do
|
||||
for i = 1, 2 ^ 16 - 2 do
|
||||
local entity = ecs:entity()
|
||||
ecs:add(entity, entity)
|
||||
|
||||
local combination = ""
|
||||
|
||||
|
|
@ -173,9 +229,11 @@ do
|
|||
ecs:set(entity, D8, { value = true })
|
||||
end
|
||||
|
||||
if flip() then
|
||||
if #combination == 7 then
|
||||
added += 1
|
||||
ecs:set(entity, D1, { value = true })
|
||||
end
|
||||
archetypes[combination] = true
|
||||
end
|
||||
|
||||
local a = 0
|
||||
45
benches/visual/despawn.bench.luau
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
--!optimize 2
|
||||
--!native
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local Matter = require(ReplicatedStorage.DevPackages.Matter)
|
||||
local ecr = require(ReplicatedStorage.DevPackages.ecr)
|
||||
local jecs = require(ReplicatedStorage.Lib)
|
||||
local newWorld = Matter.World.new()
|
||||
local ecs = jecs.World.new()
|
||||
|
||||
local A, B = Matter.component(), Matter.component()
|
||||
local C, D = ecs:component(), ecs:component()
|
||||
|
||||
return {
|
||||
ParameterGenerator = function()
|
||||
local matter_entities = {}
|
||||
local jecs_entities = {}
|
||||
local entities = {
|
||||
matter = matter_entities,
|
||||
jecs = jecs_entities,
|
||||
}
|
||||
for i = 1, 1000 do
|
||||
table.insert(matter_entities, newWorld:spawn(A(), B()))
|
||||
local e = ecs:entity()
|
||||
ecs:set(e, C, {})
|
||||
ecs:set(e, D, {})
|
||||
table.insert(jecs_entities, e)
|
||||
end
|
||||
return entities
|
||||
end,
|
||||
|
||||
Functions = {
|
||||
Matter = function(_, entities)
|
||||
for _, entity in entities.matter do
|
||||
newWorld:despawn(entity)
|
||||
end
|
||||
end,
|
||||
|
||||
Jecs = function(_, entities)
|
||||
for _, entity in entities.jecs do
|
||||
ecs:delete(entity)
|
||||
end
|
||||
end,
|
||||
},
|
||||
}
|
||||
100
benches/visual/insertion.bench.luau
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
--!optimize 2
|
||||
--!native
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local Matter = require(ReplicatedStorage.DevPackages.Matter)
|
||||
local ecr = require(ReplicatedStorage.DevPackages.ecr)
|
||||
local jecs = require(ReplicatedStorage.Lib)
|
||||
local newWorld = Matter.World.new()
|
||||
local ecs = jecs.World.new()
|
||||
local mirror = require(ReplicatedStorage.mirror)
|
||||
local mcs = mirror.World.new()
|
||||
|
||||
local A1 = Matter.component()
|
||||
local A2 = Matter.component()
|
||||
local A3 = Matter.component()
|
||||
local A4 = Matter.component()
|
||||
local A5 = Matter.component()
|
||||
local A6 = Matter.component()
|
||||
local A7 = Matter.component()
|
||||
local A8 = Matter.component()
|
||||
|
||||
local B1 = ecr.component()
|
||||
local B2 = ecr.component()
|
||||
local B3 = ecr.component()
|
||||
local B4 = ecr.component()
|
||||
local B5 = ecr.component()
|
||||
local B6 = ecr.component()
|
||||
local B7 = ecr.component()
|
||||
local B8 = ecr.component()
|
||||
|
||||
local C1 = ecs:entity()
|
||||
local C2 = ecs:entity()
|
||||
local C3 = ecs:entity()
|
||||
local C4 = ecs:entity()
|
||||
local C5 = ecs:entity()
|
||||
local C6 = ecs:entity()
|
||||
local C7 = ecs:entity()
|
||||
local C8 = ecs:entity()
|
||||
local E1 = mcs:entity()
|
||||
local E2 = mcs:entity()
|
||||
local E3 = mcs:entity()
|
||||
local E4 = mcs:entity()
|
||||
local E5 = mcs:entity()
|
||||
local E6 = mcs:entity()
|
||||
local E7 = mcs:entity()
|
||||
local E8 = mcs:entity()
|
||||
|
||||
local registry2 = ecr.registry()
|
||||
return {
|
||||
ParameterGenerator = function()
|
||||
return
|
||||
end,
|
||||
|
||||
Functions = {
|
||||
Matter = function()
|
||||
local e = newWorld:spawn()
|
||||
for i = 1, 5000 do
|
||||
newWorld:insert(
|
||||
e,
|
||||
A1({ value = true }),
|
||||
A2({ value = true }),
|
||||
A3({ value = true }),
|
||||
A4({ value = true }),
|
||||
A5({ value = true }),
|
||||
A6({ value = true }),
|
||||
A7({ value = true }),
|
||||
A8({ value = true })
|
||||
)
|
||||
end
|
||||
end,
|
||||
|
||||
ECR = function()
|
||||
local e = registry2.create()
|
||||
for i = 1, 5000 do
|
||||
registry2:set(e, B1, { value = false })
|
||||
registry2:set(e, B2, { value = false })
|
||||
registry2:set(e, B3, { value = false })
|
||||
registry2:set(e, B4, { value = false })
|
||||
registry2:set(e, B5, { value = false })
|
||||
registry2:set(e, B6, { value = false })
|
||||
registry2:set(e, B7, { value = false })
|
||||
registry2:set(e, B8, { value = false })
|
||||
end
|
||||
end,
|
||||
|
||||
Jecs = function()
|
||||
local e = ecs:entity()
|
||||
for i = 1, 5000 do
|
||||
ecs:set(e, C1, { value = false })
|
||||
ecs:set(e, C2, { value = false })
|
||||
ecs:set(e, C3, { value = false })
|
||||
ecs:set(e, C4, { value = false })
|
||||
ecs:set(e, C5, { value = false })
|
||||
ecs:set(e, C6, { value = false })
|
||||
ecs:set(e, C7, { value = false })
|
||||
ecs:set(e, C8, { value = false })
|
||||
end
|
||||
end,
|
||||
},
|
||||
}
|
||||
100
test/benches/visual/query.bench.luau → benches/visual/query.bench.luau
Executable file → Normal file
|
|
@ -2,14 +2,14 @@
|
|||
--!native
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local Matter = require(ReplicatedStorage.DevPackages.Matter)
|
||||
local ecr = require(ReplicatedStorage.DevPackages.ecr)
|
||||
local Matter = require(ReplicatedStorage.DevPackages["_Index"]["matter-ecs_matter@0.8.1"].matter)
|
||||
local ecr = require(ReplicatedStorage.DevPackages["_Index"]["centau_ecr@0.8.0"].ecr)
|
||||
local newWorld = Matter.World.new()
|
||||
|
||||
local jecs = require(ReplicatedStorage.Lib:Clone())
|
||||
local mirror = require(ReplicatedStorage.mirror:Clone())
|
||||
local mcs = mirror.world()
|
||||
local ecs = jecs.world()
|
||||
local jecs = require(ReplicatedStorage.Lib)
|
||||
local mirror = require(ReplicatedStorage.mirror)
|
||||
local mcs = mirror.World.new()
|
||||
local ecs = jecs.World.new()
|
||||
|
||||
local A1 = Matter.component()
|
||||
local A2 = Matter.component()
|
||||
|
|
@ -38,66 +38,97 @@ local D6 = ecs:component()
|
|||
local D7 = ecs:component()
|
||||
local D8 = ecs:component()
|
||||
|
||||
local E1 = mcs:component()
|
||||
local E2 = mcs:component()
|
||||
local E3 = mcs:component()
|
||||
local E4 = mcs:component()
|
||||
local E5 = mcs:component()
|
||||
local E6 = mcs:component()
|
||||
local E7 = mcs:component()
|
||||
local E8 = mcs:component()
|
||||
local E1 = mcs:entity()
|
||||
local E2 = mcs:entity()
|
||||
local E3 = mcs:entity()
|
||||
local E4 = mcs:entity()
|
||||
local E5 = mcs:entity()
|
||||
local E6 = mcs:entity()
|
||||
local E7 = mcs:entity()
|
||||
local E8 = mcs:entity()
|
||||
|
||||
local registry2 = ecr.registry()
|
||||
|
||||
local function flip()
|
||||
return math.random() >= 0.5
|
||||
return math.random() >= 0.25
|
||||
end
|
||||
|
||||
local N = 2 ^ 12- 2
|
||||
local N = 2 ^ 16 - 2
|
||||
local archetypes = {}
|
||||
|
||||
local hm = 0
|
||||
for i = 1, N do
|
||||
local id = registry2.create()
|
||||
local combination = ""
|
||||
local n = newWorld:spawn()
|
||||
local entity = ecs:entity()
|
||||
local m = mcs:entity()
|
||||
if flip() then
|
||||
ecs:add(entity, entity)
|
||||
mcs:add(m, m)
|
||||
end
|
||||
|
||||
if flip() then
|
||||
registry2:set(id, B1, { value = true })
|
||||
ecs:set(entity, D1, { value = true })
|
||||
newWorld:insert(n, A1({ value = true }))
|
||||
mcs:set(m, E1, { value = 2 })
|
||||
ecs:set(entity, D1, {value = true})
|
||||
end
|
||||
if flip() then
|
||||
combination ..= "B"
|
||||
registry2:set(id, B2, { value = true })
|
||||
ecs:set(entity, D2, { value = true })
|
||||
mcs:set(m, E2, { value = 2 })
|
||||
newWorld:insert(n, A2({ value = true }))
|
||||
end
|
||||
if flip() then
|
||||
combination ..= "C"
|
||||
registry2:set(id, B3, { value = true })
|
||||
ecs:set(entity, D3, { value = true })
|
||||
mcs:set(m, E3, { value = 2 })
|
||||
newWorld:insert(n, A3({ value = true }))
|
||||
end
|
||||
if flip() then
|
||||
combination ..= "D"
|
||||
registry2:set(id, B4, { value = true })
|
||||
ecs:set(entity, D4, { value = true })
|
||||
mcs:set(m, E4, { value = 2 })
|
||||
|
||||
newWorld:insert(n, A4({ value = true }))
|
||||
end
|
||||
if flip() then
|
||||
combination ..= "E"
|
||||
registry2:set(id, B5, { value = true })
|
||||
ecs:set(entity, D5, { value = true })
|
||||
mcs:set(m, E5, { value = 2 })
|
||||
|
||||
newWorld:insert(n, A5({ value = true }))
|
||||
end
|
||||
if flip() then
|
||||
combination ..= "F"
|
||||
registry2:set(id, B6, { value = true })
|
||||
ecs:set(entity, D6, { value = true })
|
||||
mcs:set(m, E6, { value = 2 })
|
||||
newWorld:insert(n, A6({ value = true }))
|
||||
end
|
||||
if flip() then
|
||||
combination ..= "G"
|
||||
registry2:set(id, B7, { value = true })
|
||||
ecs:set(entity, D7, { value = true })
|
||||
mcs:set(m, E7, { value = 2 })
|
||||
newWorld:insert(n, A7({ value = true }))
|
||||
end
|
||||
if flip() then
|
||||
combination ..= "H"
|
||||
registry2:set(id, B8, { value = true })
|
||||
newWorld:insert(n, A8({ value = true }))
|
||||
ecs:set(entity, D8, { value = true })
|
||||
mcs:set(m, E8, { value = 2 })
|
||||
end
|
||||
|
||||
if combination:find("BCDF") then
|
||||
if not archetypes[combination] then
|
||||
print(combination)
|
||||
end
|
||||
hm += 1
|
||||
end
|
||||
archetypes[combination] = true
|
||||
end
|
||||
print("TEST", hm)
|
||||
|
||||
|
|
@ -109,38 +140,25 @@ end
|
|||
|
||||
print(count)
|
||||
|
||||
local mq = mcs:query(E1, E2, E3, E4)
|
||||
local jq = ecs:query(D1, D2, D3, D4)
|
||||
|
||||
return {
|
||||
ParameterGenerator = function()
|
||||
return
|
||||
end,
|
||||
|
||||
Functions = {
|
||||
-- Matter = function()
|
||||
-- for entityId, firstComponent in newWorld:query(A2, A4, A6, A8) do
|
||||
-- end
|
||||
-- end,
|
||||
Matter = function()
|
||||
for entityId, firstComponent in newWorld:query(A2, A4, A6, A8) do
|
||||
end
|
||||
end,
|
||||
|
||||
-- ECR = function()
|
||||
-- for entityId, firstComponent in registry2:view(B2, B4, B6, B8) do
|
||||
-- end
|
||||
-- end,
|
||||
|
||||
Mirror = function()
|
||||
for i = 1, 10 do
|
||||
for entityId, firstComponent in mq:iter() do
|
||||
end
|
||||
ECR = function()
|
||||
for entityId, firstComponent in registry2:view(B2, B4, B6, B8) do
|
||||
end
|
||||
end,
|
||||
|
||||
Jecs = function()
|
||||
for i = 1, 10 do
|
||||
for entityId, firstComponent in jq:iter() do
|
||||
end
|
||||
for entityId, firstComponent in ecs:query(D2, D4, D6, D8) do
|
||||
end
|
||||
|
||||
end,
|
||||
},
|
||||
}
|
||||
37
benches/visual/spawn.bench.luau
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
--!optimize 2
|
||||
--!native
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local Matter = require(ReplicatedStorage.DevPackages.Matter)
|
||||
local ecr = require(ReplicatedStorage.DevPackages.ecr)
|
||||
local jecs = require(ReplicatedStorage.Lib)
|
||||
local newWorld = Matter.World.new()
|
||||
local ecs = jecs.World.new()
|
||||
|
||||
return {
|
||||
ParameterGenerator = function()
|
||||
local registry2 = ecr.registry()
|
||||
|
||||
return registry2
|
||||
end,
|
||||
|
||||
Functions = {
|
||||
Matter = function()
|
||||
for i = 1, 1000 do
|
||||
newWorld:spawn()
|
||||
end
|
||||
end,
|
||||
|
||||
ECR = function(_, registry2)
|
||||
for i = 1, 1000 do
|
||||
registry2.create()
|
||||
end
|
||||
end,
|
||||
|
||||
Jecs = function()
|
||||
for i = 1, 1000 do
|
||||
ecs:entity()
|
||||
end
|
||||
end,
|
||||
},
|
||||
}
|
||||
0
test/benches/visual/wally.toml → benches/visual/wally.toml
Executable file → Normal file
2
default.project.json
Executable file → Normal file
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "jecs",
|
||||
"tree": {
|
||||
"$path": "src/jecs.luau"
|
||||
"$path": "jecs.luau"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
BIN
demo.rbxl
Normal file
18
demo/.config/blink
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
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)
|
||||
}
|
||||
6
demo/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
# Project place file
|
||||
/example.rbxlx
|
||||
|
||||
# Roblox Studio lock files
|
||||
/*.rbxlx.lock
|
||||
/*.rbxl.lock
|
||||
15
demo/README.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# Demo
|
||||
|
||||
## Build with Rojo
|
||||
To build the place, run the following commands from the root of the repository:
|
||||
|
||||
```bash
|
||||
cd demo
|
||||
rojo build -o "demo.rbxl"
|
||||
```
|
||||
|
||||
Next, open `demo.rbxl` in Roblox Studio and start the Rojo server:
|
||||
|
||||
```bash
|
||||
rojo serve
|
||||
```
|
||||
76
demo/default.project.json
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
{
|
||||
"name": "demo",
|
||||
"tree": {
|
||||
"$className": "DataModel",
|
||||
"ReplicatedStorage": {
|
||||
"$className": "ReplicatedStorage",
|
||||
"$path": "src/ReplicatedStorage",
|
||||
"ecs": {
|
||||
"$path": "../jecs.luau"
|
||||
},
|
||||
"net": {
|
||||
"$path": "net/client.luau"
|
||||
},
|
||||
"Packages": {
|
||||
"$path": "Packages"
|
||||
}
|
||||
},
|
||||
"ServerScriptService": {
|
||||
"$className": "ServerScriptService",
|
||||
"$path": "src/ServerScriptService",
|
||||
"net": {
|
||||
"$path": "net/server.luau"
|
||||
}
|
||||
},
|
||||
"Workspace": {
|
||||
"$properties": {
|
||||
"FilteringEnabled": true
|
||||
},
|
||||
"Baseplate": {
|
||||
"$className": "Part",
|
||||
"$properties": {
|
||||
"Anchored": true,
|
||||
"Color": [
|
||||
0.38823,
|
||||
0.37254,
|
||||
0.38823
|
||||
],
|
||||
"Locked": true,
|
||||
"Position": [
|
||||
0,
|
||||
-10,
|
||||
0
|
||||
],
|
||||
"Size": [
|
||||
512,
|
||||
20,
|
||||
512
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Lighting": {
|
||||
"$properties": {
|
||||
"Ambient": [
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"Brightness": 2,
|
||||
"GlobalShadows": true,
|
||||
"Outlines": false,
|
||||
"Technology": "Voxel"
|
||||
}
|
||||
},
|
||||
"SoundService": {
|
||||
"$properties": {
|
||||
"RespectFilteringEnabled": true
|
||||
}
|
||||
},
|
||||
"StarterPlayer": {
|
||||
"StarterPlayerScripts": {
|
||||
"$path": "src/StarterPlayer/StarterPlayerScripts"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
336
demo/net/client.luau
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
--!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,
|
||||
},
|
||||
}
|
||||
372
demo/net/server.luau
Normal file
|
|
@ -0,0 +1,372 @@
|
|||
--!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,
|
||||
},
|
||||
}
|
||||
4
demo/src/ReplicatedStorage/ecs_init.luau
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
_G.JECS_DEBUG = true
|
||||
_G.JECS_HI_COMPONENT_ID = 32
|
||||
require(game:GetService("ReplicatedStorage").ecs)
|
||||
return
|
||||
34
demo/src/ReplicatedStorage/start.luau
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local RunService = game:GetService("RunService")
|
||||
local UserInputService = game:GetService("UserInputService")
|
||||
local jabby = require(ReplicatedStorage.Packages.jabby)
|
||||
local std = ReplicatedStorage.std
|
||||
local scheduler = require(std.scheduler)
|
||||
local world = require(std.world)
|
||||
|
||||
local function start(modules)
|
||||
for _, module in modules do
|
||||
require(module)
|
||||
end
|
||||
local events = scheduler.COLLECT()
|
||||
scheduler.BEGIN(events)
|
||||
jabby.set_check_function(function(player)
|
||||
return true
|
||||
end)
|
||||
if RunService:IsClient() then
|
||||
local player = game:GetService("Players").LocalPlayer
|
||||
local playergui = player:WaitForChild("PlayerGui")
|
||||
local client = jabby.obtain_client()
|
||||
UserInputService.InputBegan:Connect(function(input)
|
||||
if input.KeyCode == Enum.KeyCode.F4 then
|
||||
local home = playergui:FindFirstChild("Home")
|
||||
if home then
|
||||
home:Destroy()
|
||||
end
|
||||
client.spawn_app(client.apps.home)
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
return start
|
||||
40
demo/src/ReplicatedStorage/std/bt.luau
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
--!optimize 2
|
||||
--!native
|
||||
|
||||
-- original author @centau
|
||||
|
||||
local FAILURE = -1
|
||||
local RUNNING = 0
|
||||
local SUCCESS = 1
|
||||
|
||||
local function SEQUENCE(nodes)
|
||||
return function(...)
|
||||
for _, node in nodes do
|
||||
local status = node(...)
|
||||
if status <= RUNNING then
|
||||
return status
|
||||
end
|
||||
end
|
||||
return SUCCESS
|
||||
end
|
||||
end
|
||||
|
||||
local function FALLBACK(nodes)
|
||||
return function(...)
|
||||
for _, node in nodes do
|
||||
local status = node(...)
|
||||
if status > FAILURE then
|
||||
return status
|
||||
end
|
||||
end
|
||||
return FAILURE
|
||||
end
|
||||
end
|
||||
|
||||
local bt = {
|
||||
SEQUENCE = SEQUENCE,
|
||||
FALLBACK = FALLBACK,
|
||||
RUNNING = RUNNING,
|
||||
}
|
||||
|
||||
return bt
|
||||
67
demo/src/ReplicatedStorage/std/collect.luau
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
--!nonstrict
|
||||
|
||||
--[[
|
||||
local signal = Signal.new() :: Signal.Signal<string, string>
|
||||
local events = collect(signal)
|
||||
local function system(world)
|
||||
for id, str1, str2 in events do
|
||||
--
|
||||
end
|
||||
end
|
||||
]]
|
||||
|
||||
--[[
|
||||
original author by @memorycode
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Michael
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
--]]
|
||||
|
||||
type Signal<T...> = { [any]: any }
|
||||
local function collect<T...>(event: Signal<T...>)
|
||||
local storage = {}
|
||||
local mt = {}
|
||||
local iter = function()
|
||||
local n = #storage
|
||||
return function()
|
||||
if n <= 0 then
|
||||
mt.__iter = nil
|
||||
return nil
|
||||
end
|
||||
|
||||
n -= 1
|
||||
return n + 1, unpack(table.remove(storage, 1) :: any)
|
||||
end
|
||||
end
|
||||
|
||||
local disconnect = event:Connect(function(...)
|
||||
table.insert(storage, { ... })
|
||||
mt.__iter = iter
|
||||
end)
|
||||
|
||||
setmetatable(storage, mt)
|
||||
return (storage :: any) :: () -> (number, T...), function()
|
||||
disconnect()
|
||||
end
|
||||
end
|
||||
|
||||
return collect
|
||||
30
demo/src/ReplicatedStorage/std/components.luau
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
local jecs = require(game:GetService("ReplicatedStorage").ecs)
|
||||
local world = require(script.Parent.world)
|
||||
|
||||
type Entity<T = nil> = jecs.Entity<T>
|
||||
local components: {
|
||||
Character: Entity<Model>,
|
||||
Mob: Entity,
|
||||
Model: Entity<Model>,
|
||||
Player: Entity,
|
||||
Target: Entity,
|
||||
Transform: Entity<{ new: CFrame, old: CFrame }>,
|
||||
Velocity: Entity<number>,
|
||||
Previous: Entity,
|
||||
} =
|
||||
{
|
||||
Character = world:component(),
|
||||
Mob = world:component(),
|
||||
Model = world:component(),
|
||||
Player = world:component(),
|
||||
Target = world:component(),
|
||||
Transform = world:component(),
|
||||
Velocity = world:component(),
|
||||
Previous = world:component(),
|
||||
}
|
||||
|
||||
for name, component in components :: {[string]: jecs.Entity} do
|
||||
world:set(component, jecs.Name, name)
|
||||
end
|
||||
|
||||
return table.freeze(components)
|
||||
19
demo/src/ReplicatedStorage/std/interval.luau
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
local function interval(s)
|
||||
local pin
|
||||
|
||||
local function throttle()
|
||||
if not pin then
|
||||
pin = os.clock()
|
||||
end
|
||||
|
||||
local elapsed = os.clock() - pin > s
|
||||
if elapsed then
|
||||
pin = os.clock()
|
||||
end
|
||||
|
||||
return elapsed
|
||||
end
|
||||
return throttle
|
||||
end
|
||||
|
||||
return interval
|
||||
14
demo/src/ReplicatedStorage/std/phases.luau
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
local std = game:GetService("ReplicatedStorage").std
|
||||
local Players = game:GetService("Players")
|
||||
|
||||
local scheduler = require(std.scheduler)
|
||||
local PHASE = scheduler.PHASE
|
||||
|
||||
return {
|
||||
PlayerAdded = PHASE({
|
||||
event = Players.PlayerAdded
|
||||
}),
|
||||
PlayerRemoved = PHASE({
|
||||
event = Players.PlayerRemoving
|
||||
})
|
||||
}
|
||||
26
demo/src/ReplicatedStorage/std/ref.luau
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
local world = require(script.Parent.world)
|
||||
local jecs = require(game:GetService("ReplicatedStorage").ecs)
|
||||
local refs: {[any]: jecs.Entity} = {}
|
||||
|
||||
local function fini(key): () -> ()
|
||||
return function()
|
||||
refs[key] = nil
|
||||
end
|
||||
end
|
||||
|
||||
local function noop() end
|
||||
|
||||
local function ref(key): (jecs.Entity, () -> ())
|
||||
if not key then
|
||||
return world:entity(), noop
|
||||
end
|
||||
local e = refs[key]
|
||||
if not e then
|
||||
e = world:entity()
|
||||
refs[key] = e
|
||||
end
|
||||
-- Cannot cache handles because they will get invalidated
|
||||
return e, fini(key)
|
||||
end
|
||||
|
||||
return ref
|
||||
171
demo/src/ReplicatedStorage/std/scheduler.luau
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
--!native
|
||||
--!optimize 2
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local RunService = game:GetService("RunService")
|
||||
local jabby = require(ReplicatedStorage.Packages.jabby)
|
||||
local jecs = require(ReplicatedStorage.ecs)
|
||||
local pair = jecs.pair
|
||||
local Name = jecs.Name
|
||||
|
||||
type World = jecs.World
|
||||
type Entity<T = nil> = jecs.Entity<T>
|
||||
type Id<T = unknown> = jecs.Id<T>
|
||||
|
||||
type System = {
|
||||
callback: (world: World) -> (),
|
||||
id: number,
|
||||
}
|
||||
|
||||
type Systems = { System }
|
||||
|
||||
type Events = {
|
||||
RenderStepped: Systems,
|
||||
Heartbeat: Systems,
|
||||
}
|
||||
|
||||
local world = require(script.Parent.world)
|
||||
local Disabled = world:entity()
|
||||
local System = world:component() :: Id<{ callback: (any) -> (), name: string}>
|
||||
local DependsOn = world:entity()
|
||||
local Event = world:component() :: Id<RBXScriptSignal>
|
||||
local Phase = world:entity()
|
||||
|
||||
local PreRender = world:entity()
|
||||
local Heartbeat = world:entity()
|
||||
local PreAnimation = world:entity()
|
||||
local PreSimulation = world:entity()
|
||||
|
||||
local sys: System
|
||||
local dt: number
|
||||
|
||||
local jabby_scheduler = jabby.scheduler.create("Scheduler")
|
||||
|
||||
local a, b, c, d
|
||||
local function run()
|
||||
local id = sys.id
|
||||
jabby_scheduler:run(id, sys.callback, a, b, c, d)
|
||||
return nil
|
||||
end
|
||||
|
||||
world:add(Heartbeat, Phase)
|
||||
world:set(Heartbeat, Event, RunService.Heartbeat)
|
||||
|
||||
world:add(PreSimulation, Phase)
|
||||
world:set(PreSimulation, Event, RunService.PreSimulation)
|
||||
|
||||
world:add(PreAnimation, Phase)
|
||||
world:set(PreAnimation, Event, RunService.PreAnimation)
|
||||
|
||||
jabby.register({
|
||||
applet = jabby.applets.world,
|
||||
name = "MyWorld",
|
||||
configuration = {
|
||||
world = world,
|
||||
},
|
||||
})
|
||||
|
||||
jabby.register({
|
||||
applet = jabby.applets.scheduler,
|
||||
name = "Scheduler",
|
||||
configuration = {
|
||||
scheduler = jabby_scheduler,
|
||||
},
|
||||
})
|
||||
|
||||
if RunService:IsClient() then
|
||||
world:add(PreRender, Phase)
|
||||
world:set(PreRender, Event, (RunService :: RunService).PreRender)
|
||||
end
|
||||
|
||||
local function begin(events: { [RBXScriptSignal]: Systems })
|
||||
local connections = {}
|
||||
for event, systems in events do
|
||||
if not event then
|
||||
continue
|
||||
end
|
||||
local event_name = tostring(event)
|
||||
connections[event] = event:Connect(function(...)
|
||||
debug.profilebegin(event_name)
|
||||
for _, s in systems do
|
||||
sys = s
|
||||
a, b, c, d = ...
|
||||
|
||||
for _ in run do
|
||||
break
|
||||
end
|
||||
|
||||
end
|
||||
debug.profileend()
|
||||
end)
|
||||
end
|
||||
return connections
|
||||
end
|
||||
|
||||
local function scheduler_collect_systems_under_phase_recursive(systems, phase: Entity)
|
||||
local phase_name = world:get(phase, Name)
|
||||
for _, s in world:query(System):with(pair(DependsOn, phase)) do
|
||||
table.insert(systems, {
|
||||
id = jabby_scheduler:register_system({
|
||||
name = s.name,
|
||||
phase = phase_name,
|
||||
} :: any),
|
||||
callback = s.callback,
|
||||
})
|
||||
end
|
||||
for after in world:query(Phase):with(pair(DependsOn, phase)):iter() do
|
||||
scheduler_collect_systems_under_phase_recursive(systems, after)
|
||||
end
|
||||
end
|
||||
|
||||
local function scheduler_collect_systems_under_event(event)
|
||||
local systems = {}
|
||||
scheduler_collect_systems_under_phase_recursive(systems, event)
|
||||
return systems
|
||||
end
|
||||
|
||||
local function scheduler_collect_systems_all()
|
||||
local events = {}
|
||||
for phase, event in world:query(Event):with(Phase) do
|
||||
events[event] = scheduler_collect_systems_under_event(phase)
|
||||
end
|
||||
return events
|
||||
end
|
||||
|
||||
local function scheduler_phase_new(d: { after: Entity?, event: RBXScriptSignal? })
|
||||
local phase = world:entity()
|
||||
world:add(phase, Phase)
|
||||
local after = d.after
|
||||
if after then
|
||||
local dependency = pair(DependsOn, after :: Entity)
|
||||
world:add(phase, dependency)
|
||||
end
|
||||
|
||||
local event = d.event
|
||||
if event then
|
||||
world:set(phase, Event, event)
|
||||
end
|
||||
return phase
|
||||
end
|
||||
|
||||
local function scheduler_systems_new(callback: (any) -> (), phase: Entity?)
|
||||
local system = world:entity()
|
||||
world:set(system, System, { callback = callback, name = debug.info(callback, "n") })
|
||||
local depends_on = DependsOn :: jecs.Entity
|
||||
local p: Entity = phase or Heartbeat
|
||||
world:add(system, pair(depends_on, p))
|
||||
|
||||
return system
|
||||
end
|
||||
|
||||
return {
|
||||
SYSTEM = scheduler_systems_new,
|
||||
BEGIN = begin,
|
||||
PHASE = scheduler_phase_new,
|
||||
COLLECT = scheduler_collect_systems_all,
|
||||
phases = {
|
||||
Heartbeat = Heartbeat,
|
||||
PreSimulation = PreSimulation,
|
||||
PreAnimation = PreAnimation,
|
||||
PreRender = PreRender
|
||||
}
|
||||
}
|
||||
4
demo/src/ReplicatedStorage/std/world.luau
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
local jecs = require(game:GetService("ReplicatedStorage").ecs)
|
||||
|
||||
-- I like the idea of only having the world be a singleton.
|
||||
return jecs.World.new() :: jecs.World
|
||||
4
demo/src/ServerScriptService/main.server.luau
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local start = require(ReplicatedStorage.start)
|
||||
|
||||
start(script.Parent:WaitForChild("systems"):GetChildren())
|
||||
88
demo/src/ServerScriptService/systems/mobs.luau
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
--!optimize 2
|
||||
--!native
|
||||
--!strict
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local blink = require(game:GetService("ServerScriptService").net)
|
||||
local jecs = require(ReplicatedStorage.ecs)
|
||||
local __ = jecs.Wildcard
|
||||
local std = ReplicatedStorage.std
|
||||
local ref = require(std.ref)
|
||||
local interval = require(std.interval)
|
||||
|
||||
local world = require(std.world)
|
||||
local cts = require(std.components)
|
||||
|
||||
local Mob = cts.Mob
|
||||
local Transform = cts.Transform
|
||||
local Velocity = cts.Velocity
|
||||
local Player = cts.Player
|
||||
local Character = cts.Character
|
||||
|
||||
local characters = world
|
||||
:query(Character)
|
||||
:with(Player)
|
||||
:cached()
|
||||
|
||||
|
||||
local moving_mobs = world
|
||||
:query(Transform, Velocity)
|
||||
:with(Mob)
|
||||
:cached()
|
||||
|
||||
|
||||
local function mobsMove(dt: number)
|
||||
local targets = {}
|
||||
|
||||
for _, character in characters do
|
||||
table.insert(targets, (character.PrimaryPart :: Part).Position)
|
||||
end
|
||||
|
||||
for mob, transform, v in moving_mobs do
|
||||
local cf = transform.new
|
||||
local p = cf.Position
|
||||
|
||||
local target
|
||||
local closest
|
||||
|
||||
for _, pos in targets do
|
||||
local distance = (p - pos).Magnitude
|
||||
if not target or distance < closest then
|
||||
target = pos
|
||||
closest = distance
|
||||
end
|
||||
end
|
||||
|
||||
if not target then
|
||||
continue
|
||||
end
|
||||
|
||||
local moving = CFrame.new(p + (target - p).Unit * dt * v)
|
||||
transform.new = moving
|
||||
blink.UpdateTransform.FireAll(mob, moving)
|
||||
end
|
||||
end
|
||||
|
||||
local throttle = interval(5)
|
||||
|
||||
local function spawnMobs()
|
||||
if throttle() then
|
||||
local p = Vector3.new(0, 5, 0)
|
||||
local cf = CFrame.new(p)
|
||||
local v = 5
|
||||
|
||||
local e = world:entity()
|
||||
world:set(e, Velocity, v)
|
||||
world:set(e, Transform, { new = cf })
|
||||
world:add(e, Mob)
|
||||
|
||||
blink.SpawnMob.FireAll(e, cf, v)
|
||||
end
|
||||
end
|
||||
|
||||
local scheduler = require(std.scheduler)
|
||||
|
||||
scheduler.SYSTEM(spawnMobs)
|
||||
scheduler.SYSTEM(mobsMove)
|
||||
|
||||
return 0
|
||||
40
demo/src/ServerScriptService/systems/players.luau
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
local Players = game:GetService("Players")
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
|
||||
local std = ReplicatedStorage.std
|
||||
local ref = require(std.ref)
|
||||
local collect = require(std.collect)
|
||||
|
||||
local cts = require(std.components)
|
||||
local world = require(std.world)
|
||||
local Player = cts.Player
|
||||
local Character = cts.Character
|
||||
|
||||
local conn = {}
|
||||
|
||||
local function playersAdded(player: Player)
|
||||
local e = ref(player.UserId)
|
||||
world:set(e, Player, player)
|
||||
local characterAdd = player.CharacterAdded
|
||||
conn[e] = characterAdd:Connect(function(rig)
|
||||
while rig.Parent ~= workspace do
|
||||
task.wait()
|
||||
end
|
||||
world:set(e, Character, rig)
|
||||
end)
|
||||
end
|
||||
|
||||
local function playersRemoved(player: Player)
|
||||
local e = ref(player.UserId)
|
||||
world:clear(e)
|
||||
local connection = conn[e]
|
||||
connection:Disconnect()
|
||||
conn[e] = nil
|
||||
end
|
||||
|
||||
local scheduler = require(std.scheduler)
|
||||
local phases = require(std.phases)
|
||||
scheduler.SYSTEM(playersAdded, phases.PlayerAdded)
|
||||
scheduler.SYSTEM(playersRemoved, phases.PlayerRemoved)
|
||||
|
||||
return 0
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local start = require(ReplicatedStorage.start)
|
||||
|
||||
start(script.Parent:WaitForChild("systems"):GetChildren())
|
||||
67
demo/src/StarterPlayer/StarterPlayerScripts/systems/lol.luau
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
--!optimize 2
|
||||
--!native
|
||||
--!strict
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local jecs = require(ReplicatedStorage.ecs)
|
||||
local __ = jecs.Wildcard
|
||||
local std = ReplicatedStorage.std
|
||||
|
||||
local world = require(std.world)
|
||||
|
||||
local Position = world:component() :: jecs.Entity<vector>
|
||||
local Previous = jecs.Rest
|
||||
local pre = jecs.pair(Position, Previous)
|
||||
|
||||
local added = world
|
||||
:query(Position)
|
||||
:without(pre)
|
||||
:cached()
|
||||
local changed = world
|
||||
:query(Position, pre)
|
||||
:cached()
|
||||
local removed = world
|
||||
:query(pre)
|
||||
:without(Position)
|
||||
:cached()
|
||||
|
||||
local children = {}
|
||||
for i = 1, 10 do
|
||||
local e = world:entity()
|
||||
world:set(e, Position, vector.create(i, i, i))
|
||||
table.insert(children, e)
|
||||
end
|
||||
local function flip()
|
||||
return math.random() > 0.5
|
||||
end
|
||||
local function system()
|
||||
for i, child in children do
|
||||
world:set(child, Position, vector.create(i,i,i))
|
||||
end
|
||||
for e, p in added:iter() do
|
||||
world:set(e, pre, p)
|
||||
end
|
||||
for i, child in children do
|
||||
if flip() then
|
||||
world:set(child, Position, vector.create(i + 1, i + 1, i + 1))
|
||||
end
|
||||
end
|
||||
for e, new, old in changed:iter() do
|
||||
if new ~= old then
|
||||
world:set(e, pre, new)
|
||||
end
|
||||
end
|
||||
|
||||
for i, child in children do
|
||||
world:remove(child, Position)
|
||||
end
|
||||
|
||||
for e in removed:iter() do
|
||||
world:remove(e, pre)
|
||||
end
|
||||
end
|
||||
local scheduler = require(std.scheduler)
|
||||
|
||||
scheduler.SYSTEM(system)
|
||||
|
||||
return 0
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
--!optimize 2
|
||||
--!native
|
||||
--!strict
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local jecs = require(ReplicatedStorage.ecs)
|
||||
local __ = jecs.Wildcard
|
||||
local std = ReplicatedStorage.std
|
||||
|
||||
local world = require(std.world)
|
||||
|
||||
local Position = world:component() :: jecs.Entity<vector>
|
||||
local Previous = jecs.Rest
|
||||
local pre = jecs.pair(Position, Previous)
|
||||
|
||||
local added = world
|
||||
:query(Position)
|
||||
:without(pre)
|
||||
:cached()
|
||||
local changed = world
|
||||
:query(Position, pre)
|
||||
:cached()
|
||||
local removed = world
|
||||
:query(pre)
|
||||
:without(Position)
|
||||
:cached()
|
||||
|
||||
local children = {}
|
||||
for i = 1, 10 do
|
||||
local e = world:entity()
|
||||
world:set(e, Position, vector.create(i, i, i))
|
||||
table.insert(children, e)
|
||||
end
|
||||
local function flip()
|
||||
return math.random() > 0.5
|
||||
end
|
||||
local entity_index = world.entity_index
|
||||
local function copy(archetypes, id)
|
||||
for _, archetype in archetypes do
|
||||
|
||||
local to = jecs.archetype_traverse_add(world, pre, archetype)
|
||||
local columns = to.columns
|
||||
local records = to.records
|
||||
local old = columns[records[pre].column]
|
||||
local new = columns[records[id].column]
|
||||
|
||||
if to ~= archetype then
|
||||
for _, entity in archetype.entities do
|
||||
local r = jecs.entity_index_try_get_fast(entity_index, entity)
|
||||
jecs.entity_move(entity_index, entity, r, to)
|
||||
end
|
||||
end
|
||||
|
||||
table.move(new, 1, #new, 1, old)
|
||||
|
||||
end
|
||||
end
|
||||
local function system2()
|
||||
for i, child in children do
|
||||
world:set(child, Position, vector.create(i,i,i))
|
||||
end
|
||||
for e, p in added:iter() do
|
||||
end
|
||||
copy(added:archetypes(), Position)
|
||||
for i, child in children do
|
||||
if flip() then
|
||||
world:set(child, Position, vector.create(i + 1, i + 1, i + 1))
|
||||
end
|
||||
end
|
||||
|
||||
for e, new, old in changed:iter() do
|
||||
if new ~= old then
|
||||
end
|
||||
end
|
||||
|
||||
copy(changed:archetypes(), Position)
|
||||
|
||||
for i, child in children do
|
||||
world:remove(child, Position)
|
||||
end
|
||||
|
||||
for e in removed:iter() do
|
||||
world:remove(e, pre)
|
||||
end
|
||||
end
|
||||
local scheduler = require(std.scheduler)
|
||||
|
||||
scheduler.SYSTEM(system2)
|
||||
|
||||
return 0
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local blink = require(ReplicatedStorage.net)
|
||||
local std = ReplicatedStorage.std
|
||||
local world = require(std.world)
|
||||
local ref = require(std.ref)
|
||||
|
||||
local cts = require(std.components)
|
||||
|
||||
local Model = cts.Model
|
||||
local Transform = cts.Transform
|
||||
|
||||
local moved_models = world:query(Model, Transform):cached()
|
||||
local updated_models = {}
|
||||
local i = 0
|
||||
local function processed(n)
|
||||
i += 1
|
||||
if i > n then
|
||||
i = 0
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function move(dt: number)
|
||||
for entity, model in moved_models do
|
||||
if updated_models[entity] then
|
||||
updated_models[entity] = nil
|
||||
model.PrimaryPart.CFrame = transform
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function syncTransforms()
|
||||
for _, id, cf in blink.UpdateTransform.Iter() do
|
||||
local e = ref("server-" .. tostring(id))
|
||||
world:set(e, Transform, cf)
|
||||
moved_models[e] = true
|
||||
end
|
||||
end
|
||||
|
||||
local scheduler = require(std.scheduler)
|
||||
|
||||
scheduler.SYSTEM(move)
|
||||
scheduler.SYSTEM(syncTransforms)
|
||||
|
||||
return 0
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local blink = require(ReplicatedStorage.net)
|
||||
local std = ReplicatedStorage.std
|
||||
local ref = require(std.ref)
|
||||
local world = require(std.world)
|
||||
local cts = require(std.components)
|
||||
|
||||
local function syncMobs()
|
||||
for _, id, cf, vel in blink.SpawnMob.Iter() do
|
||||
local part = Instance.new("Part")
|
||||
part.Size = Vector3.one * 5
|
||||
part.BrickColor = BrickColor.Red()
|
||||
part.Anchored = true
|
||||
local model = Instance.new("Model")
|
||||
model.PrimaryPart = part
|
||||
part.Parent = model
|
||||
model.Parent = workspace
|
||||
|
||||
local e = ref("server-" .. tostring(id))
|
||||
world:set(e, cts.Transform, { new = cf, old = cf })
|
||||
world:set(e, cts.Velocity, vel)
|
||||
world:set(e, cts.Model, model)
|
||||
world:add(e, cts.Mob)
|
||||
end
|
||||
end
|
||||
|
||||
local scheduler = require(std.scheduler)
|
||||
scheduler.SYSTEM(syncMobs)
|
||||
|
||||
return 0
|
||||
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local std = ReplicatedStorage.std
|
||||
local world = require(std.world)
|
||||
|
||||
local A = world:component()
|
||||
local B = world:component()
|
||||
local C = world:component()
|
||||
local D = world:component()
|
||||
|
||||
local function flip()
|
||||
return math.random() >= 0.15
|
||||
end
|
||||
|
||||
for i = 1, 2^8 do
|
||||
local e = world:entity()
|
||||
if flip() then
|
||||
world:set(e, A, true)
|
||||
end
|
||||
if flip() then
|
||||
world:set(e, B, true)
|
||||
end
|
||||
if flip() then
|
||||
world:set(e, C, true)
|
||||
end
|
||||
if flip() then
|
||||
world:set(e, D, true)
|
||||
end
|
||||
end
|
||||
|
||||
local function uncached()
|
||||
for _ in world:query(A, B, C, D) do
|
||||
end
|
||||
end
|
||||
|
||||
local q = world:query(A, B, C, D):cached()
|
||||
local function cached()
|
||||
for _ in q do
|
||||
end
|
||||
end
|
||||
|
||||
local scheduler = require(std.scheduler)
|
||||
scheduler.SYSTEM(uncached)
|
||||
scheduler.SYSTEM(cached)
|
||||
return 0
|
||||
8
demo/wally.toml
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "marcus/demo"
|
||||
version = "0.1.0"
|
||||
registry = "https://github.com/UpliftGames/wally-index"
|
||||
realm = "shared"
|
||||
|
||||
[dependencies]
|
||||
jabby = "alicesaidhi/jabby@0.2.0-rc.9"
|
||||
69
docs/.vitepress/config.mts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { defineConfig } from 'vitepress'
|
||||
|
||||
// https://vitepress.dev/reference/site-config
|
||||
export default defineConfig({
|
||||
title: "Jecs",
|
||||
base: "/jecs/",
|
||||
description: "A VitePress Site",
|
||||
themeConfig: {
|
||||
// https://vitepress.dev/reference/default-theme-config
|
||||
nav: [
|
||||
{ text: 'Learn', link: '/' },
|
||||
{ text: 'API', link: '/api/jecs.md' },
|
||||
{ text: 'Examples', link: 'https://github.com/Ukendio/jecs/tree/main/examples' },
|
||||
],
|
||||
|
||||
sidebar: {
|
||||
"/api/": [
|
||||
{
|
||||
text: "API reference",
|
||||
items: [
|
||||
{ text: "jecs", link: "/api/jecs" },
|
||||
{ text: "World", link: "/api/world" },
|
||||
{ text: "Query", link: "/api/query" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"/learn/": [
|
||||
{
|
||||
text: "Introduction",
|
||||
items: [
|
||||
{ text: 'Getting Started', link: '/learn/overview/get-started' },
|
||||
{ text: 'First Jecs Project', link: '/learn/overview/first-jecs-project' }
|
||||
]
|
||||
},
|
||||
{
|
||||
text: 'Concepts',
|
||||
items: [
|
||||
{ text: 'Entities and Components', link: '/learn/concepts/entities-and-components' },
|
||||
{ text: 'Queries', link: '/learn/concepts/queries' },
|
||||
{ text: 'Relationships', link: '/learn/concepts/relationships' },
|
||||
{ text: 'Component Traits', link: 'learn/concepts/component-traits' },
|
||||
{ text: 'Addons', link: '/learn/concepts/addons' }
|
||||
]
|
||||
},
|
||||
{
|
||||
text: "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' },
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/ukendio/jecs' }
|
||||
]
|
||||
}
|
||||
})
|
||||
50
docs/api/jecs.md
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
# Jecs
|
||||
|
||||
Jecs. Just an Entity Component System.
|
||||
|
||||
# Properties
|
||||
|
||||
## World
|
||||
```luau
|
||||
jecs.World: World
|
||||
```
|
||||
A world is a container of all ECS data. Games can have multiple worlds but component IDs may conflict between worlds. Ensure to register the same component IDs in the same order for each world.
|
||||
|
||||
## Wildcard
|
||||
```luau
|
||||
jecs.Wildcard: Entity
|
||||
```
|
||||
Builtin component type. This ID is used for wildcard queries.
|
||||
|
||||
## Component
|
||||
```luau
|
||||
jecs.Component: Entity
|
||||
```
|
||||
Builtin component type. Every ID created with [world:component()](world.md#component()) has this type added to it. This is meant for querying every component ID.
|
||||
|
||||
## ChildOf
|
||||
```luau
|
||||
jecs.ChildOf: Entity
|
||||
```
|
||||
Builtin component type. This ID is for creating parent-child hierarchies.
|
||||
|
||||
## Rest
|
||||
```luau
|
||||
jecs.Rest: Entity
|
||||
```
|
||||
|
||||
# Functions
|
||||
|
||||
## pair()
|
||||
```luau
|
||||
function jecs.pair(
|
||||
first: Entity, -- The first element of the pair, referred to as the relationship of the relationship pair.
|
||||
object: Entity, -- The second element of the pair, referred to as the target of the relationship pair.
|
||||
): number -- Returns the ID with those two elements
|
||||
|
||||
```
|
||||
::: info
|
||||
|
||||
Note that while relationship pairs can be used as components, meaning you can add data with it as an ID, however they cannot be used as entities. Meaning you cannot add components to a pair as the source of a binding.
|
||||
|
||||
:::
|
||||
110
docs/api/query.md
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
# Query
|
||||
|
||||
A World contains entities which have components. The World is queryable and can be used to get entities with a specific set of components.
|
||||
|
||||
# Methods
|
||||
|
||||
## iter
|
||||
|
||||
Returns an iterator that can be used to iterate over the query.
|
||||
|
||||
```luau
|
||||
function Query:iter(): () -> (Entity, ...)
|
||||
```
|
||||
|
||||
## with
|
||||
|
||||
Adds components (IDs) to query with, but will not use their data. This is useful for Tags or generally just data you do not care for.
|
||||
|
||||
```luau
|
||||
function Query:with(
|
||||
...: Entity -- The IDs to query with
|
||||
): Query
|
||||
```
|
||||
|
||||
Example:
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
for id, position in world:query(Position):with(Velocity) do
|
||||
-- Do something
|
||||
end
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
for (const [id, position] of world.query(Position).with(Velocity)) {
|
||||
// Do something
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
:::info
|
||||
Put the IDs inside of `world:query()` instead if you need the data.
|
||||
:::
|
||||
|
||||
## without
|
||||
|
||||
Removes entities with the provided components from the query.
|
||||
|
||||
```luau
|
||||
function Query:without(
|
||||
...: Entity -- The IDs to filter against.
|
||||
): Query -- Returns the Query
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
for entity, position in world:query(Position):without(Velocity) do
|
||||
-- Do something
|
||||
end
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
for (const [entity, position] of world.query(Position).without(Velocity)) {
|
||||
// Do something
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## archetypes
|
||||
|
||||
Returns the matching archetypes of the query.
|
||||
|
||||
```luau
|
||||
function Query:archetypes(): { Archetype }
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```luau [luau]
|
||||
for i, archetype in world:query(Position, Velocity):archetypes() do
|
||||
local columns = archetype.columns
|
||||
local field = archetype.records
|
||||
|
||||
local P = field[Position]
|
||||
local V = field[Velocity]
|
||||
|
||||
for row, entity in archetype.entities do
|
||||
local position = columns[P][row]
|
||||
local velocity = columns[V][row]
|
||||
-- Do something
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
:::info
|
||||
This function is meant for people who want to really customize their query behaviour at the archetype-level
|
||||
:::
|
||||
|
||||
## cached
|
||||
|
||||
Returns a cached version of the query. This is useful if you want to iterate over the same query multiple times.
|
||||
|
||||
```luau
|
||||
function Query:cached(): Query -- Returns the cached Query
|
||||
```
|
||||
500
docs/api/world.md
Normal file
|
|
@ -0,0 +1,500 @@
|
|||
# World
|
||||
|
||||
A World contains entities which have components. The World is queryable and can be used to get entities with a specific set of components and to perform different kinds of operations on them.
|
||||
|
||||
# Functions
|
||||
|
||||
## new
|
||||
|
||||
`World` utilizes a class, meaning JECS allows you to create multiple worlds.
|
||||
|
||||
```luau
|
||||
function World.new(): World
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local world = jecs.World.new()
|
||||
local myOtherWorld = jecs.World.new()
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
import { World } from "@rbxts/jecs";
|
||||
|
||||
const world = new World();
|
||||
const myOtherWorld = new World();
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
# Methods
|
||||
|
||||
## entity
|
||||
|
||||
Creates a new entity.
|
||||
|
||||
```luau
|
||||
function World:entity(): Entity
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local entity = world:entity()
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
const entity = world.entity();
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## component
|
||||
|
||||
Creates a new component. Do note components are entities as well, meaning JECS allows you to add other components onto them.
|
||||
|
||||
These are meant to be added onto other entities through `add` and `set`
|
||||
|
||||
```luau
|
||||
function World:component<T>(): Entity<T> -- The new componen.
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local Health = world:component() :: jecs.Entity<number> -- Typecasting this will allow us to know what kind of data the component holds!
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
const Health = world.component<number>();
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## get
|
||||
|
||||
Returns the data present in the component that was set in the entity. Will return nil if the component was a tag or is not present.
|
||||
|
||||
```luau
|
||||
function World:get<T>(
|
||||
entity: Entity, -- The entity
|
||||
id: Entity<T> -- The component ID to fetch
|
||||
): T?
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local Health = world:component() :: jecs.Entity<number>
|
||||
|
||||
local Entity = world:entity()
|
||||
world:set(Entity, Health, 100)
|
||||
|
||||
print(world:get(Entity, Health))
|
||||
|
||||
-- Outputs:
|
||||
-- 100
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
const Health = world.component<number>();
|
||||
|
||||
const Entity = world.entity();
|
||||
world.set(Entity, Health, 100);
|
||||
|
||||
print(world.get(Entity, Health));
|
||||
|
||||
// Outputs:
|
||||
// 100
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## has
|
||||
|
||||
Returns whether an entity has a component (ID). Useful for checking if an entity has a tag or if you don't care of the data that is inside the component.
|
||||
|
||||
```luau
|
||||
function World:has(
|
||||
entity: Entity, -- The entity
|
||||
id: Entity<T> -- The component ID to check
|
||||
): boolean
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local IsMoving = world:component()
|
||||
local Ragdolled = world:entity() -- This is a tag, meaning it won't contain data
|
||||
local Health = world:component() :: jecs.Entity<number>
|
||||
|
||||
local Entity = world:entity()
|
||||
world:set(Entity, Health, 100)
|
||||
world:add(Entity, Ragdolled)
|
||||
|
||||
print(world:has(Entity, Health))
|
||||
print(world:has(Entity, IsMoving)
|
||||
|
||||
print(world:get(Entity, Ragdolled))
|
||||
print(world:has(Entity, Ragdolled))
|
||||
|
||||
-- Outputs:
|
||||
-- true
|
||||
-- false
|
||||
-- nil
|
||||
-- true
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
const IsMoving = world.component();
|
||||
const Ragdolled = world.entity(); // This is a tag, meaning it won't contain data
|
||||
const Health = world.component<number>();
|
||||
|
||||
const Entity = world.entity();
|
||||
world.set(Entity, Health, 100);
|
||||
world.add(Entity, Ragdolled);
|
||||
|
||||
print(world.has(Entity, Health));
|
||||
print(world.has(Entity, IsMoving));
|
||||
|
||||
print(world.get(Entity, Ragdolled));
|
||||
print(world.has(Entity, Ragdolled));
|
||||
|
||||
// Outputs:
|
||||
// true
|
||||
// false
|
||||
// nil
|
||||
// true
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## add
|
||||
|
||||
Adds a component (ID) to the entity. Useful for adding a tag to an entity, as this adds the component to the entity without any additional values inside
|
||||
|
||||
```luau
|
||||
function World:add(
|
||||
entity: Entity, -- The entity
|
||||
id: Entity<T> -- The component ID to add
|
||||
): void
|
||||
```
|
||||
|
||||
::: info
|
||||
This function is idempotent, meaning if the entity already has the id, this operation will have no side effects.
|
||||
:::
|
||||
|
||||
## set
|
||||
|
||||
Adds or changes data in the entity's component.
|
||||
|
||||
```luau
|
||||
function World:set(
|
||||
entity: Entity, -- The entity
|
||||
id: Entity<T>, -- The component ID to set
|
||||
data: T -- The data of the component's type
|
||||
): void
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local Health = world:component() :: jecs.Entity<number>
|
||||
|
||||
local Entity = world:entity()
|
||||
world:set(Entity, Health, 100)
|
||||
|
||||
print(world:get(Entity, Health))
|
||||
|
||||
world:set(Entity, Health, 50)
|
||||
print(world:get(Entity, Health))
|
||||
|
||||
-- Outputs:
|
||||
-- 100
|
||||
-- 50
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
const Health = world.component<number>();
|
||||
|
||||
const Entity = world.entity();
|
||||
world.set(Entity, Health, 100);
|
||||
|
||||
print(world.get(Entity, Health));
|
||||
|
||||
world.set(Entity, Health, 50);
|
||||
print(world.get(Entity, Health));
|
||||
|
||||
// Outputs:
|
||||
// 100
|
||||
// 50
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## query
|
||||
|
||||
Creates a [`query`](query) with the given components (IDs). Entities that satisfies the conditions of the query will be returned and their corresponding data.
|
||||
|
||||
```luau
|
||||
function World:query(
|
||||
...: Entity -- The components to query with
|
||||
): Query
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
-- Entity could also be a component if a component also meets the requirements, since they are also entities which you can add more components onto
|
||||
for entity, position, velocity in world:query(Position, Velocity) do
|
||||
|
||||
end
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
// Roblox-TS allows to deconstruct tuples on the act like if they were arrays!
|
||||
// Entity could also be a component if a component also meets the requirements, since they are also entities which you can add more components onto
|
||||
for (const [entity, position, velocity] of world.query(Position, Velocity) {
|
||||
// Do something
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
:::info
|
||||
Queries are uncached by default, this is generally very cheap unless you have high fragmentation from e.g. relationships.
|
||||
|
||||
:::
|
||||
|
||||
## target
|
||||
|
||||
Get the target of a relationship.
|
||||
This will return a target (second element of a pair) of the entity for the specified relationship. The index allows for iterating through the targets, if a single entity has multiple targets for the same relationship.
|
||||
If the index is larger than the total number of instances the entity has for the relationship or if there is no pair with the specified relationship on the entity, the operation will return nil.
|
||||
|
||||
```luau
|
||||
function World:target(
|
||||
entity: Entity, -- The entity
|
||||
relation: Entity, -- The relationship between the entity and the target
|
||||
nth: number, -- The index
|
||||
): Entity? -- The target for the relationship at the specified index.
|
||||
```
|
||||
|
||||
## parent
|
||||
|
||||
Get parent (target of ChildOf relationship) for entity. If there is no ChildOf relationship pair, it will return nil.
|
||||
|
||||
```luau
|
||||
function World:parent(
|
||||
child: Entity -- The child ID to find the parent of
|
||||
): Entity? -- Returns the parent of the child
|
||||
```
|
||||
|
||||
This operation is the same as calling:
|
||||
|
||||
```luau
|
||||
world:target(entity, jecs.ChildOf, 0)
|
||||
```
|
||||
|
||||
## contains
|
||||
|
||||
Checks if an entity or component (id) exists in the world.
|
||||
|
||||
```luau
|
||||
function World:contains(
|
||||
entity: Entity,
|
||||
): boolean
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local entity = world:entity()
|
||||
print(world:contains(entity))
|
||||
print(world:contains(1))
|
||||
print(world:contains(2))
|
||||
|
||||
-- Outputs:
|
||||
-- true
|
||||
-- true
|
||||
-- false
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
const entity = world.entity();
|
||||
print(world.contains(entity));
|
||||
print(world.contains(1));
|
||||
print(world.contains(2));
|
||||
|
||||
// Outputs:
|
||||
// true
|
||||
// true
|
||||
// false
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## remove
|
||||
|
||||
Removes a component (ID) from an entity
|
||||
|
||||
```luau
|
||||
function World:remove(
|
||||
entity: Entity,
|
||||
component: Entity<T>
|
||||
): void
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local IsMoving = world:component()
|
||||
|
||||
local entity = world:entity()
|
||||
world:add(entity, IsMoving)
|
||||
|
||||
print(world:has(entity, IsMoving))
|
||||
|
||||
world:remove(entity, IsMoving)
|
||||
print(world:has(entity, IsMoving))
|
||||
|
||||
-- Outputs:
|
||||
-- true
|
||||
-- false
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
const IsMoving = world.component();
|
||||
|
||||
const entity = world.entity();
|
||||
world.add(entity, IsMoving);
|
||||
|
||||
print(world.has(entity, IsMoving));
|
||||
|
||||
world.remove(entity, IsMoving);
|
||||
print(world.has(entity, IsMoving));
|
||||
|
||||
// Outputs:
|
||||
// true
|
||||
// false
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## delete
|
||||
|
||||
Deletes an entity and all of its related components and relationships.
|
||||
|
||||
```luau
|
||||
function World:delete(
|
||||
entity: Entity
|
||||
): void
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [luau]
|
||||
local entity = world:entity()
|
||||
print(world:has(entity))
|
||||
|
||||
world:delete(entity)
|
||||
|
||||
print(world:has(entity))
|
||||
|
||||
-- Outputs:
|
||||
-- true
|
||||
-- false
|
||||
```
|
||||
|
||||
```ts [typescript]
|
||||
const entity = world.entity();
|
||||
print(world.has(entity));
|
||||
|
||||
world.delete(entity);
|
||||
|
||||
print(world.has(entity));
|
||||
|
||||
// Outputs:
|
||||
// true
|
||||
// false
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## clear
|
||||
|
||||
Clears all of the components and relationships of the entity without deleting it.
|
||||
|
||||
```luau
|
||||
function World:clear(
|
||||
entity: Entity
|
||||
): void
|
||||
```
|
||||
|
||||
## each
|
||||
|
||||
Iterate over all entities with the specified component.
|
||||
Useful when you only need the entity for a specific ID and you want to avoid creating a query.
|
||||
|
||||
```luau
|
||||
function World:each(
|
||||
id: Entity -- The component ID
|
||||
): () -> Entity
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
Iterate entities in root of parent
|
||||
|
||||
```luau
|
||||
function World:children(
|
||||
parent: Entity -- The parent entity
|
||||
): () -> Entity
|
||||
```
|
||||
|
||||
This is the same as calling:
|
||||
|
||||
```luau
|
||||
world:each(pair(ChildOf, parent))
|
||||
```
|
||||
3
docs/contributing/guidelines.md
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
## TODO
|
||||
|
||||
This is a TODO stub.
|
||||
3
docs/contributing/issues.md
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
## TODO
|
||||
|
||||
This is a TODO stub.
|
||||
3
docs/contributing/pull-requests.md
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
## TODO
|
||||
|
||||
This is a TODO stub.
|
||||
29
docs/index.md
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
---
|
||||
# https://vitepress.dev/reference/default-theme-home-page
|
||||
layout: home
|
||||
|
||||
hero:
|
||||
name: "Jecs"
|
||||
tagline: Just a stupidly fast ECS
|
||||
image:
|
||||
src: /jecs_logo.svg
|
||||
alt: Jecs logo
|
||||
actions:
|
||||
- theme: brand
|
||||
text: Get Started
|
||||
link: learn/overview/get-started.md
|
||||
- theme: alt
|
||||
text: API References
|
||||
link: /api/jecs.md
|
||||
|
||||
features:
|
||||
- title: Stupidly Fast
|
||||
icon: 🔥
|
||||
details: Iterates 500,000 entities at 60 frames per second.
|
||||
- title: Strictly Typed API
|
||||
icon: 🔒
|
||||
details: Has typings for both Luau and Typescript.
|
||||
- title: Zero-Dependencies
|
||||
icon: 📦
|
||||
details: Jecs doesn't rely on anything other than itself.
|
||||
---
|
||||
28
docs/learn/concepts/addons.md
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# 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)!
|
||||
|
||||
# Debuggers
|
||||
|
||||
## [jabby](https://github.com/alicesaidhi/jabby)
|
||||
|
||||
A jecs debugger with a string-based query language and entity editing capabilities.
|
||||
|
||||
# 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.
|
||||
185
docs/learn/concepts/component-traits.md
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
# 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.
|
||||
|
||||
## 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)
|
||||
140
docs/learn/concepts/entities-and-components.md
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
# 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);
|
||||
```
|
||||
|
||||
:::
|
||||
186
docs/learn/concepts/queries.md
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
# Queries
|
||||
|
||||
## Introductiuon
|
||||
|
||||
Queries enable games to quickly find entities that satifies provided conditions.
|
||||
|
||||
Jecs queries can do anything from returning entities that match a simple list of components, to matching against entity graphs.
|
||||
|
||||
This manual contains a full overview of the query features available in Jecs. Some of the features of Jecs queries are:
|
||||
|
||||
- Queries have support for relationships pairs which allow for matching against entity graphs without having to build complex data structures for it.
|
||||
- Queries support filters such as [`query:with(...)`](../../api/query.md#with) if entities are required to have the components but you don’t actually care about components value. And [`query:without(...)`](../../api/query.md#without) which selects entities without the components.
|
||||
- Queries can be drained or reset on when called, which lets you choose iterator behaviour.
|
||||
- Queries can be called with any ID, including entities created dynamically, this is useful for pairs.
|
||||
- Queries are already fast but can be futher inlined via [`query:archetypes()`](../../api/query.md#archetypes) for maximum performance to eliminate function call overhead which is roughly 70-80% of the cost for iteration.
|
||||
|
||||
## Performance and Caching
|
||||
|
||||
Understanding the basic architecture of queries helps to make the right tradeoffs when using queries in games.
|
||||
The biggest impact on query performance is whether a query is cached or not.
|
||||
This section goes over what caching is, how it can be used and when it makes sense to use it.
|
||||
|
||||
### Caching: what is it?
|
||||
|
||||
Jecs is an archetype ECS, which means that entities with exactly the same components are
|
||||
grouped together in an "archetype". Archetypes are created on the fly
|
||||
whenever a new component combination is created in the ECS. For example:
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
local e1 = world:entity()
|
||||
world:set(e1, Position, Vector3.new(10, 20, 30)) -- create archetype [Position]
|
||||
world:set(e1, Velocity, Vector3.new(1, 2, 3)) -- create archetype [Position, Velocity]
|
||||
|
||||
local e2 = world:entity()
|
||||
world:set(e2, Position, Vector3.new(10, 20, 30)) -- archetype [Position] already exists
|
||||
world:set(e2, Velocity, Vector3.new(1, 2, 3)) -- archetype [Position, Velocity] already exists
|
||||
world:set(e3, Mass, 100) -- create archetype [Position, Velocity, Mass]
|
||||
|
||||
-- e1 is now in archetype [Position, Velocity]
|
||||
-- e2 is now in archetype [Position, Velocity, Mass]
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const e1 = world.entity();
|
||||
world.set(e1, Position, new Vector3(10, 20, 30)); // create archetype [Position]
|
||||
world.set(e1, Velocity, new Vector3(1, 2, 3)); // create archetype [Position, Velocity]
|
||||
|
||||
const e2 = world.entity();
|
||||
world.set(e2, Position, new Vector3(10, 20, 30)); // archetype [Position] already exists
|
||||
world.set(e2, Velocity, new Vector3(1, 2, 3)); // archetype [Position, Velocity] already exists
|
||||
world.set(e3, Mass, 100); // create archetype [Position, Velocity, Mass]
|
||||
|
||||
// e1 is now in archetype [Position, Velocity]
|
||||
// e2 is now in archetype [Position, Velocity, Mass]
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Archetypes are important for queries. Since all entities in an archetype have the same components, and a query matches entities with specific components, a query can often match entire archetypes instead of individual entities. This is one of the main reasons why queries in an archetype ECS are fast.
|
||||
|
||||
The second reason that queries in an archetype ECS are fast is that they are cheap to cache. While an archetype is created for each unique component combination, games typically only use a finite set of component combinations which are created quickly after game assets are loaded.
|
||||
|
||||
This means that instead of searching for archetypes each time a query is evaluated, a query can instead cache the list of matching archetypes. This is a cheap cache to maintain: even though entities can move in and out of archetypes, the archetypes themselves are often stable.
|
||||
|
||||
If none of that made sense, the main thing to remember is that a cached query does not actually have to search for entities. Iterating a cached query just means iterating a list of prematched results, and this is really, really fast.
|
||||
|
||||
### Tradeoffs
|
||||
|
||||
Jecs has both cached and uncached queries. If cached queries are so fast, why even bother with uncached queries? There are four main reasons:
|
||||
|
||||
- Cached queries are really fast to iterate, but take more time to create because the cache must be initialized first.
|
||||
- Cached queries have a higher RAM utilization, whereas uncached queries have very little overhead and are stateless.
|
||||
- Cached queries add overhead to archetype creation/deletion, as these changes have to get propagated to caches.
|
||||
- While caching archetypes is fast, some query features require matching individual entities, which are not efficient to cache (and aren't cached).
|
||||
|
||||
As a rule of thumb, if you have a query that is evaluated each frame (as is typically the case with systems), they will benefit from being cached. If you need to create a query ad-hoc, an uncached query makes more sense.
|
||||
|
||||
Ad-hoc queries are often necessary when a game needs to find entities that match a condition that is only known at runtime, for example to find all child entities for a specific parent.
|
||||
|
||||
## Creating Queries
|
||||
|
||||
This section explains how to create queries in the different language bindings.
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
for _ in world:query(Position, Velocity) do end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
for (const [_] of world.query(Position, Velocity)) {
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Components
|
||||
|
||||
A component is any single ID that can be added to an entity. This includes tags and regular entities, which are IDs that do not have the builtin `Component` component. To match a query, an entity must have all the requested components. An example:
|
||||
|
||||
```luau
|
||||
local e1 = world:entity()
|
||||
world:add(e1, Position)
|
||||
|
||||
local e2 = world:entity()
|
||||
world:add(e2, Position)
|
||||
world:add(e2, Velocity)
|
||||
|
||||
local e3 = world:entity()
|
||||
world:add(e3, Position)
|
||||
world:add(e3, Velocity)
|
||||
world:add(e3, Mass)
|
||||
|
||||
```
|
||||
|
||||
Only entities `e2` and `e3` match the query Position, Velocity.
|
||||
|
||||
### Wildcards
|
||||
|
||||
Jecs currently only supports the `Any` type of wildcards which a single result for the first component that it matches.
|
||||
|
||||
When using the `Any` type wildcard it is undefined which component will be matched, as this can be influenced by other parts of the query. It is guaranteed that iterating the same query twice on the same dataset will produce the same result.
|
||||
|
||||
If you want to iterate multiple targets for the same relation on a pair, then use [`world:target`](../../api/world.md#target)
|
||||
|
||||
Wildcards are particularly useful when used in combination with pairs (next section).
|
||||
|
||||
### Pairs
|
||||
|
||||
A pair is an ID that encodes two elements. Pairs, like components, can be added to entities and are the foundation for [Relationships](relationships.md).
|
||||
|
||||
The elements of a pair are allowed to be wildcards. When a query pair returns an `Any` type wildcard, the query returns at most a single matching pair on an entity.
|
||||
|
||||
The following sections describe how to create queries for pairs in the different language bindings.
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
local Likes = world:entity()
|
||||
local bob = world:entity()
|
||||
for _ in world:query(pair(Likes, bob)) do end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Likes = world.entity();
|
||||
const bob = world.entity();
|
||||
for (const [_] of world.query(pair(Likes, bob))) {
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
When a query pair contains a wildcard, the `world:target()` function can be used to determine the target of the pair element that matched the query:
|
||||
|
||||
:::code-group
|
||||
|
||||
```luau [luau]
|
||||
for id in world:query(pair(Likes, jecs.Wildcard)) do
|
||||
print(`entity {getName(id)} likes {getName(world, world:target(id, Likes))}`)
|
||||
end
|
||||
```
|
||||
|
||||
```typescript [typescript]
|
||||
const Likes = world.entity();
|
||||
const bob = world.entity();
|
||||
for (const [_] of world.query(pair(Likes, jecs.Wildcard))) {
|
||||
print(`entity ${getName(id)} likes ${getName(world.target(id, Likes))}`);
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Filters
|
||||
|
||||
Filters are extensions to queries which allow you to select entities from a more complex pattern but you don't actually care about the component values.
|
||||
|
||||
The following filters are supported by queries:
|
||||
|
||||
| Identifier | Description |
|
||||
| ---------- | ----------------------------------- |
|
||||
| With | Must match with all terms. |
|
||||
| Without | Must not match with provided terms. |
|
||||
|
||||
This page takes wording and terminology directly from Flecs [documentation](https://www.flecs.dev/flecs/md_docs_2Queries.html)
|
||||
198
docs/learn/concepts/relationships.md
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
# 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).
|
||||
3
docs/learn/faq/contributing.md
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
## TODO
|
||||
|
||||
This is a TODO stub.
|
||||
71
docs/learn/overview/first-jecs-project.md
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
# 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)
|
||||
130
docs/learn/overview/get-started.md
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
# Getting Started
|
||||
|
||||
## Installation
|
||||
|
||||
### Installing Standalone
|
||||
|
||||
Navigate to the [releases page](https://github.com/Ukendio/jecs/releases) and download `jecs.rbxm` from the assets.
|
||||
|
||||

|
||||
|
||||
### Using Wally
|
||||
|
||||
Add the following to your wally configuration:
|
||||
|
||||
::: code-group
|
||||
|
||||
```toml [wally.toml]
|
||||
jecs = "ukendio/jecs@0.5.3"
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Using npm (roblox-ts)
|
||||
|
||||
Use one of the following commands on your root project directory:
|
||||
|
||||
::: code-group
|
||||
```bash [npm]
|
||||
npm i https://github.com/Ukendio/jecs.git
|
||||
```
|
||||
```bash [yarn]
|
||||
yarn add https://github.com/Ukendio/jecs.git
|
||||
```
|
||||
```bash [pnpm]
|
||||
pnpm add https://github.com/Ukendio/jecs.git
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Example Usage
|
||||
|
||||
::: code-group
|
||||
|
||||
```luau [Luau]
|
||||
local world = jecs.World.new()
|
||||
local pair = jecs.pair
|
||||
local Wildcard = jecs.Wildcard
|
||||
|
||||
local Name = world:component()
|
||||
|
||||
local function getName(e)
|
||||
return world:get(e, Name)
|
||||
end
|
||||
|
||||
local Eats = world:component()
|
||||
|
||||
-- Relationship objects
|
||||
local Apples = world:component()
|
||||
-- components are entities, so you can add components to components
|
||||
world:set(Apples, Name, "apples")
|
||||
local Oranges = world:component()
|
||||
world:set(Oranges, Name, "oranges")
|
||||
|
||||
local bob = world:entity()
|
||||
-- Pairs can be constructed from two entities
|
||||
|
||||
world:set(bob, pair(Eats, Apples), 10)
|
||||
world:set(bob, pair(Eats, Oranges), 5)
|
||||
world:set(bob, Name, "bob")
|
||||
|
||||
local alice = world:entity()
|
||||
world:set(alice, pair(Eats, Apples), 4)
|
||||
world:set(alice, Name, "alice")
|
||||
|
||||
for id, amount in world:query(pair(Eats, Wildcard)) do
|
||||
-- get the second target of the pair
|
||||
local food = world:target(id, Eats)
|
||||
print(string.format("%s eats %d %s", getName(id), amount, getName(food)))
|
||||
end
|
||||
|
||||
-- Output:
|
||||
-- bob eats 10 apples
|
||||
-- bob eats 5 pears
|
||||
-- alice eats 4 apples
|
||||
```
|
||||
|
||||
|
||||
```ts [Typescript]
|
||||
import { Wildcard, pair, World } from "@rbxts/jecs"
|
||||
|
||||
|
||||
const world = new World()
|
||||
const Name = world.component()
|
||||
function getName(e) {
|
||||
return world.get(e, Name)
|
||||
}
|
||||
|
||||
const Eats = world.component()
|
||||
|
||||
// Relationship objects
|
||||
const Apples = world.component()
|
||||
// components are entities, so you can add components to components
|
||||
world.set(Apples, Name, "apples")
|
||||
const Oranges = world.component()
|
||||
world.set(Oranges, Name, "oranges")
|
||||
|
||||
const bob = world.entity()
|
||||
// Pairs can be constructed from two entities
|
||||
|
||||
world.set(bob, pair(Eats, Apples), 10)
|
||||
world.set(bob, pair(Eats, Oranges), 5)
|
||||
world.set(bob, Name, "bob")
|
||||
|
||||
const alice = world.entity()
|
||||
world.set(alice, pair(Eats, Apples), 4)
|
||||
world.set(alice, Name, "alice")
|
||||
|
||||
for (const [id, amount] of world.query(pair(Eats, Wildcard))) {
|
||||
// get the second target of the pair
|
||||
const food = world:target(id, Eats)
|
||||
print(string.format("%s eats %d %s", getName(id), amount, getName(food)))
|
||||
}
|
||||
|
||||
// Output:
|
||||
// bob eats 10 apples
|
||||
// bob eats 5 pears
|
||||
// alice eats 4 apples
|
||||
|
||||
```
|
||||
|
||||
BIN
docs/learn/overview/rbxm.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
41
docs/learn/public/jecs_logo.svg
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="1080" height="1080" viewBox="0 0 1080 1080" xml:space="preserve">
|
||||
<desc>Created with Fabric.js 5.2.4</desc>
|
||||
<defs>
|
||||
</defs>
|
||||
<rect x="0" y="0" width="100%" height="100%" fill="transparent"></rect>
|
||||
<g transform="matrix(1 0 0 1 540 540)" id="09ac800d-29f3-4193-b9f5-faf19e8b1726" >
|
||||
<rect style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(255,255,255); fill-rule: nonzero; opacity: 1; visibility: hidden;" vector-effect="non-scaling-stroke" x="-540" y="-540" rx="0" ry="0" width="1080" height="1080" />
|
||||
</g>
|
||||
<g transform="matrix(Infinity NaN NaN Infinity 0 0)" id="619f0364-53a0-4caa-97e3-8f543e0cc17f" >
|
||||
</g>
|
||||
<g transform="matrix(NaN NaN NaN NaN 0 0)" >
|
||||
<g style="" >
|
||||
</g>
|
||||
</g>
|
||||
<g transform="matrix(17.7 0 0 17.7 540 540)" >
|
||||
<g style="" vector-effect="non-scaling-stroke" >
|
||||
<g transform="matrix(1 0 0 1 -18.25 0)" >
|
||||
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(52,81,178); fill-rule: nonzero; opacity: 1;" vector-effect="non-scaling-stroke" transform=" translate(-5, -9)" d="M 5 14 C 5.8 14 6 13.3333 6 13 L 6 4 L 0 4 L 0 0 L 6 0 L 10 0 L 10 13 C 10 17 6.66667 18 5 18 L 0 18 L 0 14 L 5 14 Z" stroke-linecap="round" />
|
||||
</g>
|
||||
<g transform="matrix(1 0 0 1 16.75 0)" >
|
||||
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(52,81,178); fill-rule: nonzero; opacity: 1;" vector-effect="non-scaling-stroke" transform=" translate(-40, -9)" d="M 46.5 4 L 46.5 0 L 39 0 C 37.1667 0 33.5 1.1 33.5 5.5 C 33.5 9.9 36.8333 11 38.5 11 L 41 11 C 41.5 11 42.5 11.3 42.5 12.5 C 42.5 13.7 41.5 14 41 14 L 33.5 14 L 33.5 18 L 41.5 18 C 43.1667 18 46.5 16.9 46.5 12.5 C 46.5 8.1 43.1667 7 41.5 7 L 39 7 C 38.5 7 37.5 6.7 37.5 5.5 C 37.5 4.3 38.5 4 39 4 L 46.5 4 Z" stroke-linecap="round" />
|
||||
</g>
|
||||
<g transform="matrix(1 0 0 1 3.25 0)" >
|
||||
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(52,81,178); fill-rule: evenodd; opacity: 1;" vector-effect="non-scaling-stroke" transform=" translate(-26.5, -9)" d="M 32.5 0 L 32.5 4 L 30.5 4 C 28.5 4 24.5 5 24.5 9 C 24.5 11.0835 25.5853 12.3531 26.9078 13.0914 L 22.4606 14.661 C 21.2893 13.3156 20.5 11.4775 20.5 9 C 20.5 1.8 27.1667 0 30.5 0 L 32.5 0 Z M 24.4656 16.3357 C 26.5037 17.5803 28.8905 18 30.5 18 L 32.5 18 L 32.5 14 L 31.0833 14 L 24.4656 16.3357 Z" stroke-linecap="round" />
|
||||
</g>
|
||||
<g transform="matrix(1 0 0 1 -5 0)" >
|
||||
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(52,81,178); fill-rule: evenodd; opacity: 1;" vector-effect="non-scaling-stroke" transform=" translate(-18.25, -9)" d="M 25.3793 0 C 24.766 0.241156 24.1568 0.53354 23.571 0.885014 C 22.1712 1.72492 20.9038 2.91123 20.0606 4.5 L 11 4.5 L 11 0 L 25.3793 0 Z M 25.5 4.39421 C 25.445 4.42876 25.3906 4.46402 25.3368 4.5 L 25.5 4.5 L 25.5 4.39421 Z M 20.0606 13.5 C 20.9038 15.0888 22.1712 16.2751 23.571 17.115 C 24.1568 17.4665 24.766 17.7588 25.3793 18 L 11 18 L 11 13.5 L 20.0606 13.5 Z M 19.1854 7 C 19.0649 7.62348 19 8.28956 19 9 C 19 9.71044 19.0649 10.3765 19.1854 11 L 11 11 L 11 7 L 19.1854 7 Z" stroke-linecap="round" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g transform="matrix(NaN NaN NaN NaN 0 0)" >
|
||||
<g style="" >
|
||||
</g>
|
||||
</g>
|
||||
<g transform="matrix(NaN NaN NaN NaN 0 0)" >
|
||||
<g style="" >
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.9 KiB |
41
docs/public/jecs_logo.svg
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="1080" height="1080" viewBox="0 0 1080 1080" xml:space="preserve">
|
||||
<desc>Created with Fabric.js 5.2.4</desc>
|
||||
<defs>
|
||||
</defs>
|
||||
<rect x="0" y="0" width="100%" height="100%" fill="transparent"></rect>
|
||||
<g transform="matrix(1 0 0 1 540 540)" id="09ac800d-29f3-4193-b9f5-faf19e8b1726" >
|
||||
<rect style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(255,255,255); fill-rule: nonzero; opacity: 1; visibility: hidden;" vector-effect="non-scaling-stroke" x="-540" y="-540" rx="0" ry="0" width="1080" height="1080" />
|
||||
</g>
|
||||
<g transform="matrix(Infinity NaN NaN Infinity 0 0)" id="619f0364-53a0-4caa-97e3-8f543e0cc17f" >
|
||||
</g>
|
||||
<g transform="matrix(NaN NaN NaN NaN 0 0)" >
|
||||
<g style="" >
|
||||
</g>
|
||||
</g>
|
||||
<g transform="matrix(17.7 0 0 17.7 540 540)" >
|
||||
<g style="" vector-effect="non-scaling-stroke" >
|
||||
<g transform="matrix(1 0 0 1 -18.25 0)" >
|
||||
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(52,81,178); fill-rule: nonzero; opacity: 1;" vector-effect="non-scaling-stroke" transform=" translate(-5, -9)" d="M 5 14 C 5.8 14 6 13.3333 6 13 L 6 4 L 0 4 L 0 0 L 6 0 L 10 0 L 10 13 C 10 17 6.66667 18 5 18 L 0 18 L 0 14 L 5 14 Z" stroke-linecap="round" />
|
||||
</g>
|
||||
<g transform="matrix(1 0 0 1 16.75 0)" >
|
||||
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(52,81,178); fill-rule: nonzero; opacity: 1;" vector-effect="non-scaling-stroke" transform=" translate(-40, -9)" d="M 46.5 4 L 46.5 0 L 39 0 C 37.1667 0 33.5 1.1 33.5 5.5 C 33.5 9.9 36.8333 11 38.5 11 L 41 11 C 41.5 11 42.5 11.3 42.5 12.5 C 42.5 13.7 41.5 14 41 14 L 33.5 14 L 33.5 18 L 41.5 18 C 43.1667 18 46.5 16.9 46.5 12.5 C 46.5 8.1 43.1667 7 41.5 7 L 39 7 C 38.5 7 37.5 6.7 37.5 5.5 C 37.5 4.3 38.5 4 39 4 L 46.5 4 Z" stroke-linecap="round" />
|
||||
</g>
|
||||
<g transform="matrix(1 0 0 1 3.25 0)" >
|
||||
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(52,81,178); fill-rule: evenodd; opacity: 1;" vector-effect="non-scaling-stroke" transform=" translate(-26.5, -9)" d="M 32.5 0 L 32.5 4 L 30.5 4 C 28.5 4 24.5 5 24.5 9 C 24.5 11.0835 25.5853 12.3531 26.9078 13.0914 L 22.4606 14.661 C 21.2893 13.3156 20.5 11.4775 20.5 9 C 20.5 1.8 27.1667 0 30.5 0 L 32.5 0 Z M 24.4656 16.3357 C 26.5037 17.5803 28.8905 18 30.5 18 L 32.5 18 L 32.5 14 L 31.0833 14 L 24.4656 16.3357 Z" stroke-linecap="round" />
|
||||
</g>
|
||||
<g transform="matrix(1 0 0 1 -5 0)" >
|
||||
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(52,81,178); fill-rule: evenodd; opacity: 1;" vector-effect="non-scaling-stroke" transform=" translate(-18.25, -9)" d="M 25.3793 0 C 24.766 0.241156 24.1568 0.53354 23.571 0.885014 C 22.1712 1.72492 20.9038 2.91123 20.0606 4.5 L 11 4.5 L 11 0 L 25.3793 0 Z M 25.5 4.39421 C 25.445 4.42876 25.3906 4.46402 25.3368 4.5 L 25.5 4.5 L 25.5 4.39421 Z M 20.0606 13.5 C 20.9038 15.0888 22.1712 16.2751 23.571 17.115 C 24.1568 17.4665 24.766 17.7588 25.3793 18 L 11 18 L 11 13.5 L 20.0606 13.5 Z M 19.1854 7 C 19.0649 7.62348 19 8.28956 19 9 C 19 9.71044 19.0649 10.3765 19.1854 11 L 11 11 L 11 7 L 19.1854 7 Z" stroke-linecap="round" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g transform="matrix(NaN NaN NaN NaN 0 0)" >
|
||||
<g style="" >
|
||||
</g>
|
||||
</g>
|
||||
<g transform="matrix(NaN NaN NaN NaN 0 0)" >
|
||||
<g style="" >
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.9 KiB |
11
examples/README.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# Examples
|
||||
|
||||
This folder contains code examples for the Luau/Typescript APIs.
|
||||
|
||||
## Run with Luau
|
||||
To run the examples with Luau, run the following commands from the root of the repository:
|
||||
|
||||
```sh
|
||||
cd examples/luau
|
||||
luau path/to/file.luau
|
||||
```
|
||||
21
examples/entities/basics.luau → examples/luau/entities/basics.luau
Executable file → Normal file
|
|
@ -1,19 +1,15 @@
|
|||
local jecs = require("@jecs")
|
||||
local world = jecs.world()
|
||||
local world = jecs.World.new()
|
||||
|
||||
local Position = world:component() :: jecs.Id<vector>
|
||||
local Position = world:component()
|
||||
local Walking = world:component()
|
||||
local Name = world:component() :: jecs.Id<string>
|
||||
|
||||
local function name(e: jecs.Entity): string
|
||||
return assert(world:get(e, Name))
|
||||
end
|
||||
local Name = world:component()
|
||||
|
||||
-- Create an entity with name Bob
|
||||
local bob = world:entity()
|
||||
|
||||
-- The set operation finds or creates a component, and sets it.
|
||||
world:set(bob, Position, vector.create(10, 20, 30))
|
||||
world:set(bob, Position, Vector3.new(10, 20, 30))
|
||||
-- Name the entity Bob
|
||||
world:set(bob, Name, "Bob")
|
||||
-- The add operation adds a component without setting a value. This is
|
||||
|
|
@ -22,16 +18,15 @@ world:add(bob, Walking)
|
|||
|
||||
-- Get the value for the Position component
|
||||
local pos = world:get(bob, Position)
|
||||
assert(pos)
|
||||
print(`\{{pos.x}, {pos.y}, {pos.z}\}`)
|
||||
print(`\{{pos.X}, {pos.Y}, {pos.Z}\}`)
|
||||
|
||||
-- Overwrite the value of the Position component
|
||||
world:set(bob, Position, vector.create(40, 50, 60))
|
||||
world:set(bob, Position, Vector3.new(40, 50, 60))
|
||||
|
||||
local alice = world:entity()
|
||||
-- Create another named entity
|
||||
world:set(alice, Name, "Alice")
|
||||
world:set(alice, Position, vector.create(10, 20, 30))
|
||||
world:set(alice, Position, Vector3.new(10, 20, 30))
|
||||
world:add(alice, Walking)
|
||||
|
||||
-- Remove tag
|
||||
|
|
@ -39,7 +34,7 @@ world:remove(alice, Walking)
|
|||
|
||||
-- Iterate all entities with Position
|
||||
for entity, p in world:query(Position) do
|
||||
print(`{name(entity)}: \{{p.x}, {p.y}, {p.z}\}`)
|
||||
print(`{entity}: \{{p.X}, {p.Y}, {p.Z}\}`)
|
||||
end
|
||||
|
||||
-- Output:
|
||||
0
examples/entities/hierarchy.luau → examples/luau/entities/hierarchy.luau
Executable file → Normal file
5
examples/hooks/cleanup.luau → examples/luau/hooks/cleanup.luau
Executable file → Normal file
|
|
@ -13,9 +13,8 @@ world:set(Model, jecs.OnRemove, function(entity)
|
|||
model:Destroy()
|
||||
end)
|
||||
|
||||
world:set(Model, jecs.OnAdd, function(entity, id, model)
|
||||
-- OnAdd is invoked after the data has been assigned.
|
||||
-- This hook only fires the first time the component is added.
|
||||
world:set(Model, jecs.OnSet, function(entity, model)
|
||||
-- OnSet is invoked after the data has been assigned.
|
||||
-- It also returns the data for faster access.
|
||||
-- There may be some logic to do some side effects on reassignments
|
||||
model:SetAttribute("entityId", entity)
|
||||
2
examples/queries/basics.luau → examples/luau/queries/basics.luau
Executable file → Normal file
|
|
@ -1,5 +1,5 @@
|
|||
local jecs = require("@jecs")
|
||||
local world = jecs.world()
|
||||
local world = jecs.World.new()
|
||||
|
||||
local Position = world:component()
|
||||
local Velocity = world:component()
|
||||
31
examples/queries/changetracking.luau → examples/luau/queries/changetracking.luau
Executable file → Normal file
|
|
@ -1,16 +1,19 @@
|
|||
local jecs = require("@jecs")
|
||||
local pair = jecs.pair
|
||||
|
||||
local world = jecs.world()
|
||||
local Name = world:component() :: jecs.Id<string>
|
||||
local world = jecs.World.new()
|
||||
local Name = world:component()
|
||||
|
||||
|
||||
local function name(e: jecs.Entity): string
|
||||
return assert(world:get(e, Name))
|
||||
local function named(ctr, name)
|
||||
local e = ctr(world)
|
||||
world:set(e, Name, name)
|
||||
return e
|
||||
end
|
||||
local function name(e)
|
||||
return world:get(e, Name)
|
||||
end
|
||||
|
||||
local Position = world:component() :: jecs.Id<vector>
|
||||
world:set(Position, Name, "Position")
|
||||
local Position = named(world.component, "Position") :: jecs.Entity<vector>
|
||||
local Previous = jecs.Rest
|
||||
|
||||
local added = world
|
||||
|
|
@ -26,14 +29,10 @@ local removed = world
|
|||
:cached()
|
||||
|
||||
|
||||
local e1 = world:entity()
|
||||
world:set(e1, Name, "e1")
|
||||
local e1 = named(world.entity, "e1")
|
||||
world:set(e1, Position, vector.create(10, 20, 30))
|
||||
|
||||
local e2 = world:entity()
|
||||
world:set(e2, Name, "e2")
|
||||
local e2 = named(world.entity, "e2")
|
||||
world:set(e2, Position, vector.create(10, 20, 30))
|
||||
|
||||
for entity, p in added do
|
||||
print(`Added {name(entity)}: \{{p.x}, {p.y}, {p.z}}`)
|
||||
world:set(entity, pair(Previous, Position), p)
|
||||
|
|
@ -41,10 +40,10 @@ end
|
|||
|
||||
world:set(e1, Position, vector.create(999, 999, 1998))
|
||||
|
||||
for entity, new, old in changed do
|
||||
for _, archetype in changed:archetypes() do
|
||||
if new ~= old then
|
||||
print(`{name(entity)}'s Position changed from \{{old.x}, {old.y}, {old.z}\} to \{{new.x}, {new.y}, {new.z}\}`)
|
||||
world:set(entity, pair(Previous, Position), new)
|
||||
print(`{name(e)}'s Position changed from \{{old.x}, {old.y}, {old.z}\} to \{{new.x}, {new.y}, {new.z}\}`)
|
||||
world:set(e, pair(Previous, Position), new)
|
||||
end
|
||||
end
|
||||
|
||||
63
examples/queries/spatial_grids.luau → examples/luau/queries/spatial_grids.luau
Executable file → Normal file
|
|
@ -3,47 +3,32 @@ local pair = jecs.pair
|
|||
local ChildOf = jecs.ChildOf
|
||||
local __ = jecs.Wildcard
|
||||
local Name = jecs.Name
|
||||
local world = jecs.world()
|
||||
local world = jecs.World.new()
|
||||
|
||||
local Voxel = world:component() :: jecs.Id
|
||||
local Position = world:component() :: jecs.Id<vector>
|
||||
local Perception = world:component() :: jecs.Id<{
|
||||
type Id<T = nil> = number & { __T: T }
|
||||
local Voxel = world:component() :: Id
|
||||
local Position = world:component() :: Id<Vector3>
|
||||
local Perception = world:component() :: Id<{
|
||||
range: number,
|
||||
fov: number,
|
||||
dir: vector,
|
||||
dir: Vector3,
|
||||
}>
|
||||
type part = {
|
||||
Position: vector
|
||||
}
|
||||
local PrimaryPart = world:component() :: jecs.Id<part>
|
||||
local PrimaryPart = world:component() :: Id<Part>
|
||||
|
||||
local local_player = {
|
||||
Character = {
|
||||
PrimaryPart = {
|
||||
Position = vector.create(50, 0, 30)
|
||||
}
|
||||
}
|
||||
}
|
||||
local workspace = {
|
||||
CurrentCamera = {
|
||||
CFrame = {
|
||||
LookVector = vector.create(0, 0, -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
local local_player = game:GetService("Players").LocalPlayer
|
||||
|
||||
local function distance(a: vector, b: vector)
|
||||
return vector.magnitude((b - a))
|
||||
local function distance(a: Vector3, b: Vector3)
|
||||
return (b - a).Magnitude
|
||||
end
|
||||
|
||||
local function is_in_fov(a: vector, b: vector, forward_dir: vector, fov_angle: number)
|
||||
local function is_in_fov(a: Vector3, b: Vector3, forward_dir: Vector3, fov_angle: number)
|
||||
local to_target = b - a
|
||||
|
||||
local forward_xz = vector.normalize(vector.create(forward_dir.x, 0, forward_dir.z))
|
||||
local to_target_xz = vector.normalize(vector.create(to_target.x, 0, to_target.z))
|
||||
local forward_xz = Vector3.new(forward_dir.X, 0, forward_dir.Z).Unit
|
||||
local to_target_xz = Vector3.new(to_target.X, 0, to_target.Z).Unit
|
||||
|
||||
local angle_to_target = math.deg(math.atan2(to_target_xz.z, to_target_xz.x))
|
||||
local forward_angle = math.deg(math.atan2(forward_xz.z, forward_xz.z))
|
||||
local angle_to_target = math.deg(math.atan2(to_target_xz.Z, to_target_xz.X))
|
||||
local forward_angle = math.deg(math.atan2(forward_xz.Z, forward_xz.X))
|
||||
|
||||
local angle_difference = math.abs(forward_angle - angle_to_target)
|
||||
|
||||
|
|
@ -57,7 +42,7 @@ end
|
|||
local map = {}
|
||||
local grid = 50
|
||||
|
||||
local function add_to_voxel(source: jecs.Entity, position: vector, prev_voxel_id: jecs.Entity?)
|
||||
local function add_to_voxel(source: number, position: Vector3, prev_voxel_id: number?)
|
||||
local hash = position // grid
|
||||
local voxel_id = map[hash]
|
||||
if not voxel_id then
|
||||
|
|
@ -94,7 +79,7 @@ local function update_camera_direction(dt: number)
|
|||
end
|
||||
|
||||
local function perceive_enemies(dt: number)
|
||||
local it = world:query(Perception, Position, PrimaryPart):iter()
|
||||
local it = world:query(Perception, Position, PrimaryPart)
|
||||
-- There is only going to be one entity matching the query
|
||||
local e, self_perception, self_position, self_primary_part = it()
|
||||
|
||||
|
|
@ -108,28 +93,28 @@ local function perceive_enemies(dt: number)
|
|||
|
||||
if is_in_fov(self_position, target_position, self_perception.dir, self_perception.fov) then
|
||||
local p = target_position
|
||||
print(`Entity {world:get(e, Name)} can see target {world:get(enemy, Name)} at ({p.x}, {p.y}, {p.z})`)
|
||||
print(`Entity {world:get(e, Name)} can see target {world:get(enemy, Name)} at ({p.X}, {p.Y}, {p.Z})`)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local player = world:entity()
|
||||
world:set(player, Perception, {
|
||||
range = 200,
|
||||
range = 100,
|
||||
fov = 90,
|
||||
dir = vector.create(1, 0, 0),
|
||||
dir = Vector3.new(1, 0, 0),
|
||||
})
|
||||
world:set(player, Name, "LocalPlayer")
|
||||
local primary_part = local_player.Character.PrimaryPart
|
||||
local primary_part = (local_player.Character :: Model).PrimaryPart :: Part
|
||||
world:set(player, PrimaryPart, primary_part)
|
||||
world:set(player, Position, vector.zero)
|
||||
world:set(player, Position, Vector3.zero)
|
||||
|
||||
local enemy = world:entity()
|
||||
world:set(enemy, Name, "Enemy $1")
|
||||
world:set(enemy, Position, vector.create(50, 0, 20))
|
||||
world:set(enemy, Position, Vector3.new(50, 0, 20))
|
||||
|
||||
add_to_voxel(player, primary_part.Position)
|
||||
add_to_voxel(enemy, assert(world:get(enemy, Position)))
|
||||
add_to_voxel(enemy, world)
|
||||
|
||||
local dt = 1 / 60
|
||||
reconcile_client_owned_assembly_to_voxel(dt)
|
||||
0
examples/queries/wildcards.luau → examples/luau/queries/wildcards.luau
Executable file → Normal file
|
|
@ -1,122 +0,0 @@
|
|||
--!strict
|
||||
local remotes = require("./remotes")
|
||||
local jecs = require("@jecs")
|
||||
local collect = require("@modules/collect")
|
||||
|
||||
-- this is just an example, you need an actually populated map
|
||||
local components: { [string]: jecs.Id } = {}
|
||||
|
||||
local client_ids: {[jecs.Entity]: jecs.Entity<nil> } = {}
|
||||
|
||||
local function ecs_ensure_entity(world: jecs.World, id: jecs.Entity)
|
||||
local e = 0
|
||||
|
||||
local ser_id = id
|
||||
local deser_id = client_ids[ser_id]
|
||||
if deser_id then
|
||||
if deser_id == 0::any then
|
||||
local new_id = world:entity()
|
||||
client_ids[ser_id] = new_id
|
||||
deser_id = new_id
|
||||
end
|
||||
else
|
||||
if not world:exists(ser_id)
|
||||
or (world:contains(ser_id) and not world:get(ser_id, jecs.Name))
|
||||
then
|
||||
deser_id = world:entity()
|
||||
else
|
||||
if world:contains(ser_id) and world:get(ser_id, jecs.Name) then
|
||||
deser_id = ser_id
|
||||
else
|
||||
deser_id = world:entity()
|
||||
end
|
||||
end
|
||||
client_ids[ser_id] = deser_id
|
||||
end
|
||||
|
||||
e = deser_id
|
||||
|
||||
return e
|
||||
end
|
||||
|
||||
-- local rel_render = `e{jecs.ECS_ID(rel)}v{jecs.ECS_GENERATION(rel)}`
|
||||
-- local tgt_render = `e{jecs.ECS_ID(tgt)}v{jecs.ECS_GENERATION(tgt)}`
|
||||
-- local function ecs_deser_pairs_str(world, token)
|
||||
-- local tokens = string.split(token, ",")
|
||||
-- local rel = tonumber(tokens[1]) :: jecs.Entity
|
||||
-- local tgt = tonumber(tokens[2]) :: jecs.Entity
|
||||
|
||||
-- rel = ecs_ensure_entity(world, rel)
|
||||
-- tgt = ecs_ensure_entity(world, tgt)
|
||||
|
||||
-- return jecs.pair(rel, tgt)
|
||||
-- end
|
||||
|
||||
local function ecs_deser_pairs(world, rel: jecs.Entity, tgt: jecs.Entity)
|
||||
rel = ecs_ensure_entity(world, rel)
|
||||
tgt = ecs_ensure_entity(world, tgt)
|
||||
|
||||
return jecs.pair(rel, tgt)
|
||||
end
|
||||
|
||||
local snapshots = collect(remotes.replication.OnClientEvent)
|
||||
|
||||
return function(world: jecs.World)
|
||||
for entity in world:each(components.Destroy) do
|
||||
client_ids[entity] = nil
|
||||
end
|
||||
for snapshot in snapshots do
|
||||
for ser_id, map in snapshot do
|
||||
local id = (tonumber(ser_id) :: any) :: jecs.Entity
|
||||
if jecs.IS_PAIR(id) and map.pair == true then
|
||||
id = ecs_deser_pairs(world, map.relation, map.target)
|
||||
elseif id then
|
||||
id = ecs_ensure_entity(world, id)
|
||||
end
|
||||
-- if not id then
|
||||
-- id = ecs_deser_pairs_str(world, ser_id)
|
||||
-- else
|
||||
-- id = ecs_ensure_entity(world, id)
|
||||
-- end
|
||||
local members = world:get(id, components.NetworkedMembers)
|
||||
|
||||
local set = map.set
|
||||
if set then
|
||||
if jecs.is_tag(world, id) then
|
||||
for _, entity in set do
|
||||
entity = ecs_ensure_entity(world, entity)
|
||||
world:add(entity, id)
|
||||
end
|
||||
else
|
||||
local values = map.values :: { any }
|
||||
for i, entity in set do
|
||||
entity = ecs_ensure_entity(world, entity)
|
||||
local value = values[i]
|
||||
if members then
|
||||
for _, member in members do
|
||||
local data = value[member] :: {jecs.Entity} | jecs.Entity -- targets
|
||||
if typeof(data) == "table" then
|
||||
for pos, tgt in data :: { jecs.Entity } do
|
||||
data[pos] = ecs_ensure_entity(world, tgt)
|
||||
end
|
||||
else
|
||||
value[member] = ecs_ensure_entity(world, data :: any)
|
||||
end
|
||||
end
|
||||
end
|
||||
world:set(entity, id, value)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local removed = map.removed
|
||||
|
||||
if removed then
|
||||
for _, entity in removed do
|
||||
entity = ecs_ensure_entity(world, entity)
|
||||
world:remove(entity, id)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
@ -1,225 +0,0 @@
|
|||
--!strict
|
||||
local Players = require("@game/Players")
|
||||
local remotes = require("./remotes")
|
||||
local jecs = require("@jecs")
|
||||
local collect = require("@modules/collect")
|
||||
local ty = require("./types")
|
||||
|
||||
-- this is just an example, you need an actually populated map
|
||||
local components: { [string]: jecs.Id } = {}
|
||||
local ct = components
|
||||
|
||||
local function networking_send(world: jecs.World)
|
||||
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)
|
||||
assert(name)
|
||||
if components[name] == nil then
|
||||
error("Invalid component:"..name)
|
||||
end
|
||||
|
||||
storages[component] = {}
|
||||
|
||||
table.insert(networked_components, component)
|
||||
end
|
||||
|
||||
for relation in world:each(ct.NetworkedPair) do
|
||||
local name = world:get(relation, jecs.Name)
|
||||
assert(name)
|
||||
if not components[name] then
|
||||
error("Invalid component")
|
||||
end
|
||||
table.insert(networked_pairs, relation)
|
||||
end
|
||||
|
||||
for _, component in networked_components do
|
||||
local name = world:get(component, jecs.Name)
|
||||
if not name or not components[name] then
|
||||
-- error("Invalid component")
|
||||
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
|
||||
|
||||
for _, relation in networked_pairs do
|
||||
world:added(relation, function(entity: jecs.Entity, id: jecs.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: jecs.Id, id: jecs.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
|
||||
|
||||
storage[entity] = value
|
||||
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
|
||||
|
||||
-- local requested_snapshots = collect(remotes.request_snapshot.OnServerEvent)
|
||||
local players_added = collect(Players.PlayerAdded)
|
||||
|
||||
return function(_, dt: number)
|
||||
local snapshot_lazy: ty.snapshot
|
||||
local set_ids_lazy: { jecs.Entity }
|
||||
|
||||
-- In the future maybe it should be requested by the player instead when they
|
||||
-- are ready to receive the replication. Otherwise streaming could be complicated
|
||||
-- with intances references being nil.
|
||||
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 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 not is_tag then
|
||||
local column = archetype.columns_map[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, table.create(set_n))
|
||||
|
||||
local map = {
|
||||
set = if set_n > 0 then set else nil,
|
||||
values = if set_n > 0 then set_values else nil,
|
||||
}
|
||||
|
||||
if jecs.IS_PAIR(component) then
|
||||
map.relation = jecs.pair_first(world, component)
|
||||
map.target = jecs.pair_second(world, component)
|
||||
map.pair = true
|
||||
end
|
||||
snapshot_lazy[tostring(component)] = map
|
||||
end
|
||||
end
|
||||
|
||||
remotes.replication:FireClient(player, snapshot_lazy)
|
||||
end
|
||||
|
||||
-- accumulator += dt
|
||||
|
||||
-- Purposely sending less diffs of the world because doing it at 60hz
|
||||
-- gets expensive. But this requires interpolated elements in the scene.
|
||||
-- if accumulator > 1/60 then
|
||||
-- accumulator = 0
|
||||
|
||||
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] = if is_tag then 0 else v
|
||||
elseif world:contains(e) then
|
||||
removed_n += 1
|
||||
removed_ids[removed_n] = e
|
||||
end
|
||||
end
|
||||
|
||||
table.clear(storage)
|
||||
|
||||
local dirty = false
|
||||
|
||||
if set_n > 0 or removed_n > 0 then
|
||||
dirty = true
|
||||
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 }
|
||||
|
||||
-- local ser_id: string = nil :: any
|
||||
|
||||
-- if jecs.IS_PAIR(component) then
|
||||
-- ser_id = `{jecs.pair_first(world, component)},{jecs.pair_second(world, component)}`
|
||||
-- else
|
||||
-- ser_id = tostring(component)
|
||||
-- end
|
||||
|
||||
local map = {
|
||||
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 removed else nil,
|
||||
}
|
||||
|
||||
if jecs.IS_PAIR(component) then
|
||||
map.relation = jecs.pair_first(world, component)
|
||||
map.target = jecs.pair_second(world, component)
|
||||
map.pair = true
|
||||
end
|
||||
|
||||
snapshot[tostring(component)] = map
|
||||
end
|
||||
end
|
||||
if next(snapshot) ~= nil then
|
||||
remotes.replication:FireAllClients(snapshot)
|
||||
-- print(snapshot)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return networking_send
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
local ReplicatedStorage = require("@game/ReplicatedStorage")
|
||||
local types = require("./types")
|
||||
|
||||
type Remote<T...> = {
|
||||
FireClient: (Remote<T...>, Player, T...) -> (),
|
||||
FireAllClients: (Remote<T...>, T...) -> (),
|
||||
FireServer: (Remote<T...>, T...) -> (),
|
||||
OnServerEvent: RBXScriptSignal<(Player, T...)>,
|
||||
OnClientEvent: RBXScriptSignal<T...>
|
||||
}
|
||||
|
||||
local function stream_ensure(name)
|
||||
local remote = ReplicatedStorage:FindFirstChild(name)
|
||||
if not remote then
|
||||
remote = Instance.new("RemoteEvent")
|
||||
remote.Name = name
|
||||
remote.Parent = ReplicatedStorage
|
||||
end
|
||||
return remote
|
||||
end
|
||||
|
||||
local function datagram_ensure(name)
|
||||
local remote = ReplicatedStorage:FindFirstChild(name)
|
||||
if not remote then
|
||||
remote = Instance.new("UnreliableRemoteEvent")
|
||||
remote.Name = name
|
||||
remote.Parent = ReplicatedStorage
|
||||
end
|
||||
return remote
|
||||
end
|
||||
|
||||
return {
|
||||
input = datagram_ensure("input") :: Remote<string>,
|
||||
replication = stream_ensure("replication") :: Remote<types.snapshot>,
|
||||
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
local jecs = require("@jecs")
|
||||
|
||||
export type snapshot = {
|
||||
[string]: {
|
||||
set: { jecs.Entity }?,
|
||||
values: { any }?,
|
||||
removed: { jecs.Entity }?,
|
||||
pair: true,
|
||||
relation: jecs.Entity,
|
||||
target: jecs.Entity
|
||||
} | {
|
||||
set: { jecs.Entity }?,
|
||||
values: { any }?,
|
||||
removed: { jecs.Entity }?,
|
||||
pair: false,
|
||||
}
|
||||
}
|
||||
|
||||
return {}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
-- Using world:target is the recommended way to grab the target in a wildcard
|
||||
-- query. However the random access can add up in very hot paths. Accessing its
|
||||
-- column can drastically improve performance, especially when there are
|
||||
-- multiple adjacent pairs.
|
||||
|
||||
local jecs = require("@jecs")
|
||||
local pair = jecs.pair
|
||||
local __ = jecs.Wildcard
|
||||
|
||||
local world = jecs.world()
|
||||
|
||||
local Likes = world:entity()
|
||||
local function name(e, name: string): string
|
||||
if name then
|
||||
world:set(e, jecs.Name, name)
|
||||
return name
|
||||
end
|
||||
return assert(world:get(e, jecs.Name))
|
||||
end
|
||||
|
||||
local e1 = world:entity()
|
||||
name(e1, "e1")
|
||||
local e2 = world:entity()
|
||||
name(e2, "e2")
|
||||
local e3 = world:entity()
|
||||
name(e3, "e3")
|
||||
|
||||
world:add(e1, pair(Likes, e2))
|
||||
world:add(e1, pair(Likes, e3))
|
||||
|
||||
local likes = jecs.component_record(world, pair(Likes, __))
|
||||
assert(likes)
|
||||
|
||||
local likes_cr = likes.records
|
||||
local likes_counts = likes.counts
|
||||
|
||||
local archetypes = world:query(pair(Likes, __)):archetypes()
|
||||
|
||||
for _, archetype in archetypes do
|
||||
local types = archetype.types
|
||||
|
||||
-- Get the starting index which is what the (R, *) alias is at
|
||||
local wc = likes_cr[archetype.id]
|
||||
local count = likes_counts[archetype.id]
|
||||
|
||||
local entities = archetype.entities
|
||||
for i = #entities, 1, -1 do
|
||||
-- It is generally a good idea to iterate backwards on arrays if you
|
||||
-- need to delete the iterated entity to prevent iterator invalidation
|
||||
local entity = entities[i]
|
||||
for cr = wc, wc + count - 1 do
|
||||
local person = jecs.pair_second(world, types[cr])
|
||||
print(`entity ${entity} likes ${person}`)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Output:
|
||||
-- entity $273 likes $275
|
||||
-- entity $273 likes $274
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
-- To get the most out of performance, you can lift the inner loop of queries to
|
||||
-- the system in which you can do archetype-specific optimizations like finding
|
||||
-- the parent once per archetype rather than per entity.
|
||||
|
||||
local jecs = require("@jecs")
|
||||
local pair = jecs.pair
|
||||
local ChildOf = jecs.ChildOf
|
||||
local __ = jecs.Wildcard
|
||||
|
||||
local world = jecs.world()
|
||||
|
||||
local Position = world:component() :: jecs.Id<vector>
|
||||
local Visible = world:entity()
|
||||
|
||||
local parent = world:entity()
|
||||
world:set(parent, Position, vector.zero)
|
||||
world:add(parent, Visible)
|
||||
|
||||
local child = world:entity()
|
||||
world:set(child, Position, vector.one)
|
||||
world:add(child, pair(ChildOf, parent))
|
||||
|
||||
local parents = jecs.component_record(world, pair(ChildOf, __))
|
||||
assert(parents)
|
||||
|
||||
local parent_cr = parents.records
|
||||
|
||||
local archetypes = world:query(Position, pair(ChildOf, __)):archetypes()
|
||||
|
||||
for _, archetype in archetypes do
|
||||
local types = archetype.types
|
||||
local p = jecs.pair_second(world, types[parent_cr[archetype.id]])
|
||||
if world:has(p, Visible) then
|
||||
local columns = archetype.columns_map
|
||||
local positions = columns[Position]
|
||||
for row, entity in archetype.entities do
|
||||
local pos = positions[row]
|
||||
print(`Child ${entity} of ${p} is visible at {pos}`)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Output:
|
||||
-- Child $274 of $273 is visibile at 1,1,1
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
--[[
|
||||
It all has to start somewhere. A world stores entities and their components,
|
||||
and manages them. This tour will reference it for every operation.
|
||||
]]
|
||||
|
||||
local jecs = require("@jecs")
|
||||
local world = jecs.world()
|
||||
|
||||
--[[
|
||||
You can declare component ids with specific types with this format:
|
||||
|
||||
ComponentId = world:component() :: jecs.Id<Type>
|
||||
]]
|
||||
|
||||
local Position = world:component() :: jecs.Id<vector>
|
||||
|
||||
-- Creates an empty entity and returns its handle
|
||||
local entity = world:entity()
|
||||
|
||||
-- You can give entities data using `world:set()`. The type solver will
|
||||
-- enforce that the data you assign to the entity will match the type
|
||||
-- of the component id.
|
||||
world:set(entity, Position, vector.create(1, 2, 3))
|
||||
|
||||
-- If you want the Entity's Position, you can look it up with the component ID.
|
||||
-- It will return the value with the component's type coalesced with "nil"
|
||||
-- because the entity's type is only known at runtime.
|
||||
print(`Entity's Position is {world:get(entity, Position)}`)
|
||||
|
||||
--[[
|
||||
To run it:
|
||||
luau 001_hello_world.luau
|
||||
]]
|
||||
|
|
@ -1,110 +0,0 @@
|
|||
local jecs = require("@jecs")
|
||||
local world = jecs.world()
|
||||
|
||||
--[[
|
||||
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.
|
||||
]]
|
||||
|
||||
|
||||
-- Creates a new entity with no components and returns its identifier
|
||||
local entity = world:entity()
|
||||
print(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.
|
||||
world:entity(42)
|
||||
|
||||
--[[
|
||||
|
||||
The entity ID will have a corresponding entity
|
||||
record that essentially just keeps indices into arrays of data.
|
||||
The format of the entity record is:
|
||||
|
||||
record: {
|
||||
row: number,
|
||||
}
|
||||
|
||||
--]]
|
||||
|
||||
-- You can retrieve an entity's record by using one of jecs' functions:
|
||||
|
||||
local record = jecs.record(world, entity)
|
||||
print(record)
|
||||
|
||||
--[[
|
||||
|
||||
Underneath the ECS the entity ID and its record will be stored in two separate arrays.
|
||||
A dense array and a sparse array. Other than the fact that there is
|
||||
two arrays is an unimportant implementation detail.
|
||||
We just use these distinct terms to differentiate tnem. The format is:
|
||||
|
||||
dense_array: { u53 }
|
||||
sparse_array: { [u24]: record }
|
||||
|
||||
The entity ID that you operate with is an element in the dense array with
|
||||
the u53 number type. In reality, there is no such thing as a u53 number
|
||||
type. In luau it is actually all just doubles (IEEE-754 f64).
|
||||
|
||||
However the size of the integer mantissa in a double is 53 bits, so it
|
||||
can represent integers with full precision up to 2^53.
|
||||
|
||||
As a refresher here is the IEEE-754 f64 (double) bit layout:
|
||||
|
||||
bit index: 63 52 51 0
|
||||
| | | |
|
||||
v v v v
|
||||
+---------+---------------+-------------------------------+
|
||||
| sign | exponent | mantissa / fraction |
|
||||
| (1 bit) | (11 bits) | (52 bits) |
|
||||
+---------+---------------+-------------------------------+
|
||||
|
||||
Entity IDs use 48 bits which is well within the range for the mantissa.
|
||||
This is useful to know because it allows the ECS to put a lot of information
|
||||
in this opaque ID number such as the index into the sparse_array and a generation.
|
||||
|
||||
A generation is a number that increments everytime an entity index is
|
||||
reused. By embedding this counter into the entity ID, any stale handle
|
||||
referring to a previous entity of that index becomes invalid.
|
||||
Because programmers are not perfect and often forget about dangling pointers
|
||||
as a result of storing and referencing entities outside of the ECS.
|
||||
|
||||
If the index 10 has been used for an entity, dies, and gets reused.
|
||||
The new entity becomes index 10, generation 2.
|
||||
|
||||
The layout of the ID itself is:
|
||||
|
||||
[ 47 ........ 24 ][ 23 ........ 0 ]
|
||||
| generation | index |
|
||||
| (24 bits) | (24 bits) |
|
||||
|
||||
The index is used to lookup the corresponding record for the entity such as:
|
||||
|
||||
record = sparse_array[downcast(u24)(dense_array[n])]
|
||||
--]]
|
||||
|
||||
-- It is possible to read the index and the generation of an entity ID
|
||||
-- using the public API with the following:
|
||||
|
||||
local ECS_ID = jecs.ECS_ID
|
||||
local ECS_GENERATION = jecs.ECS_GENERATION
|
||||
|
||||
local index = ECS_ID(entity)
|
||||
local generation = ECS_GENERATION(entity)
|
||||
|
||||
print(`Entity's index and generation are {index} and {generation} respectively`)
|
||||
|
||||
-- A notable detail about entity IDs is that they can become very large
|
||||
-- as the generation increases. This is because the bits
|
||||
-- further to the left represent much larger powers of two.
|
||||
|
||||
world:delete(entity)
|
||||
|
||||
local recycled_entity = world:entity()
|
||||
|
||||
print(`This is a huuuuge number {recycled_entity}`)
|
||||
print(`The recycled entity's generation incremented to {ECS_GENERATION(recycled_entity)} `)
|
||||
print(`However it retains the old index at {ECS_ID(recycled_entity)}`)
|
||||
|
|
@ -1,139 +0,0 @@
|
|||
local jecs = require("@jecs")
|
||||
local world = jecs.world()
|
||||
|
||||
--[[
|
||||
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").
|
||||
]]
|
||||
|
||||
-- Create a component with a type
|
||||
local Position = world:component() :: jecs.Id<vector>
|
||||
local Health = world:component() :: jecs.Id<number>
|
||||
|
||||
--[[
|
||||
Components are keys to ECS storage columns. Think of the ECS storage as
|
||||
a table where:
|
||||
- Rows are entities
|
||||
- Columns are components
|
||||
- Cells are the component data for that entity
|
||||
|
||||
When you create a component, you're creating a key that you'll use to
|
||||
index into the storage. The component ID is what tells the ECS "I want
|
||||
to access the Position column" or "I want to access the Health column".
|
||||
|
||||
The component ID is just a number, but it's been registered with the world.
|
||||
This registration is what allows the ECS to know about the component and
|
||||
allocate storage for it when entities use it.
|
||||
]]
|
||||
|
||||
print(`Position component ID: {Position}`)
|
||||
print(`Health component ID: {Health}`)
|
||||
|
||||
--[[
|
||||
If you try to use a number as a component ID that has not been registered,
|
||||
the ECS will throw an error at runtime because the ID is not known to the
|
||||
World. You must create components using world:component() before you can
|
||||
use them.
|
||||
]]
|
||||
|
||||
local entity = world:entity()
|
||||
|
||||
--[[
|
||||
world:set(entity, component, value)
|
||||
|
||||
Sets the value of a component for an entity. This is how you store data
|
||||
in the ECS columns. The component ID acts as the column index, and the
|
||||
entity acts as the row index.
|
||||
|
||||
If the entity doesn't already have the component, set() will add it
|
||||
automatically. If it does have the component, set() will update the
|
||||
existing value.
|
||||
|
||||
The type system enforces that the value you provide matches the component's
|
||||
type. This prevents type errors at compile time (if using a type checker).
|
||||
]]
|
||||
|
||||
-- Set initial values
|
||||
world:set(entity, Position, vector.create(10, 20, 30))
|
||||
world:set(entity, Health, 100)
|
||||
|
||||
-- Update values (set works for both adding and updating)
|
||||
world:set(entity, Position, vector.create(40, 50, 60))
|
||||
world:set(entity, Health, 50)
|
||||
|
||||
--[[
|
||||
world:get(entity, component)
|
||||
|
||||
Retrieves the value of a component from an entity. This is how you read
|
||||
data from the ECS columns. The component ID tells the ECS which column
|
||||
to look in, and the entity tells it which row.
|
||||
|
||||
The return type is `T?` (T or nil), not just `T`. This is because the
|
||||
entity might not have the component, or the entity might have been deleted.
|
||||
You should always handle the nil case.
|
||||
|
||||
In practice, you'll often use assert() if you know the component should
|
||||
exist, or check for nil if it might not exist.
|
||||
]]
|
||||
|
||||
-- Get component values
|
||||
local pos = world:get(entity, Position)
|
||||
local health = world:get(entity, Health)
|
||||
|
||||
print(`Entity position: {pos}`)
|
||||
print(`Entity health: {health}`)
|
||||
|
||||
-- Handle the nil case
|
||||
local maybe_pos = world:get(entity, Position)
|
||||
if maybe_pos then
|
||||
print(`Position exists: {maybe_pos}`)
|
||||
else
|
||||
print("Entity doesn't have Position")
|
||||
end
|
||||
|
||||
-- Or use assert if you know it should exist
|
||||
local pos_assert = assert(world:get(entity, Position))
|
||||
print(`Position (asserted): {pos_assert}`)
|
||||
|
||||
--[[
|
||||
world:remove(entity, component)
|
||||
|
||||
Removes a component from an entity. This removes the data from the storage
|
||||
column for that entity. The entity will no longer have that component.
|
||||
|
||||
If the entity doesn't have the component, remove() does nothing (it's
|
||||
idempotent). This makes it safe to call remove() multiple times.
|
||||
|
||||
Note: remove() only removes the component, it doesn't delete the entity.
|
||||
Use world:delete() if you want to delete the entire entity.
|
||||
]]
|
||||
|
||||
-- Remove a component
|
||||
world:remove(entity, Health)
|
||||
|
||||
-- Now Health is gone
|
||||
print(`Health after remove: {world:get(entity, Health)}`) -- nil
|
||||
|
||||
-- Position is still there
|
||||
print(`Position after removing Health: {world:get(entity, Position)}`) -- still has value
|
||||
|
||||
-- Removing a component that doesn't exist does nothing
|
||||
world:remove(entity, Health) -- Safe to call again, does nothing
|
||||
|
||||
--[[
|
||||
Components are keys to storage columns. When you use set(), get(), or remove(),
|
||||
you're using the component ID to index into the ECS storage:
|
||||
|
||||
set(entity, Position, value) -> storage[Position][entity] = value
|
||||
get(entity, Position) -> return storage[Position][entity]
|
||||
remove(entity, Position) -> storage[Position][entity] = nil
|
||||
|
||||
This is the fundamental abstraction of the ECS: components are column keys,
|
||||
entities are row keys, and the storage is a two-dimensional table.
|
||||
|
||||
In reality, the storage is more sophisticated (it uses archetypes for
|
||||
efficiency), but this mental model is useful for understanding how the
|
||||
APIs work.
|
||||
]]
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
local jecs = require("@jecs")
|
||||
|
||||
--[[
|
||||
Tags are components without data. They are used to mark or categorize entities
|
||||
without storing any associated values. Think of them as boolean flags that
|
||||
can be added or removed from entities.
|
||||
|
||||
A tag takes zero bytes of storage per entity. More importantly,
|
||||
tags enable a different mental model. When you see a tag on an
|
||||
entity, you know it's just a marker and there's no data to read or write.
|
||||
|
||||
Tags are entities that do not have the builtin jecs.Component trait which
|
||||
tells the ECS that this ID doesn't cannot store any data, it is just a marker.
|
||||
]]
|
||||
|
||||
--[[
|
||||
There are two ways to create tags:
|
||||
|
||||
1. Using jecs.tag() to preregister a tag entity which will be allocated when you create the world.
|
||||
2. Using world:entity() to create a regular entity id
|
||||
|
||||
The first method is the "proper" way to create tags but it hinges upon that
|
||||
you do remember to create the world after declaring all of your
|
||||
components/tags. This is a good practice because it is harder to mess up the
|
||||
offset of your component range, ensuring a stable type id.
|
||||
|
||||
More on this is discussed in 011_preregistering_components.luau
|
||||
]]
|
||||
|
||||
local Dead = jecs.tag()
|
||||
|
||||
-- Creating the world after the components to ensure they get allocated.
|
||||
local world = jecs.world()
|
||||
|
||||
--
|
||||
-- Tags are added using world:add(entity, component).
|
||||
-- You cannot use world:set() with tags
|
||||
-- because tags don't store data.
|
||||
|
||||
local entity = world:entity()
|
||||
|
||||
world:add(entity, Dead) -- Adds the tag
|
||||
|
||||
print(world:has(entity, Dead)) -- true
|
||||
|
||||
-- Tags are removed using world:remove(entity, component)
|
||||
|
||||
world:remove(entity, Dead)
|
||||
|
||||
print(world:has(entity, Dead)) -- false
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
local jecs = require("@jecs")
|
||||
local world = jecs.world()
|
||||
|
||||
-- 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.
|
||||
|
||||
local TimeOfDay = world:component() :: jecs.Id<number>
|
||||
world:set(TimeOfDay, TimeOfDay, 5)
|
||||
local t = world:get(TimeOfDay, TimeOfDay)
|
||||
print(`The time of day is {t}`)
|
||||