aiecsjs 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -1
- package/README.md +8 -3
- package/README_ZHTW.md +8 -3
- package/api.json +2 -2
- package/dist/chunk-37HMYMJG.cjs +2 -0
- package/dist/chunk-37HMYMJG.cjs.map +1 -0
- package/dist/chunk-4RPFOVQC.cjs +2 -0
- package/dist/chunk-4RPFOVQC.cjs.map +1 -0
- package/dist/chunk-AGHSWLNQ.cjs +2 -0
- package/dist/chunk-AGHSWLNQ.cjs.map +1 -0
- package/dist/chunk-FDXCXNZK.js +2 -0
- package/dist/chunk-FDXCXNZK.js.map +1 -0
- package/dist/chunk-L5CMKMIP.js +2 -0
- package/dist/chunk-L5CMKMIP.js.map +1 -0
- package/dist/chunk-QOKIEF7C.js +2 -0
- package/dist/chunk-QOKIEF7C.js.map +1 -0
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.js +1 -1
- package/dist/commands.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/observers.cjs +1 -1
- package/dist/observers.cjs.map +1 -1
- package/dist/observers.js +1 -1
- package/dist/observers.js.map +1 -1
- package/dist/relations.cjs +1 -1
- package/dist/relations.cjs.map +1 -1
- package/dist/relations.js +1 -1
- package/dist/relations.js.map +1 -1
- package/dist/serialize.cjs +1 -1
- package/dist/serialize.cjs.map +1 -1
- package/dist/serialize.js +1 -1
- package/dist/serialize.js.map +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/llms-full.txt +35 -4
- package/package.json +6 -2
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,31 @@ All notable changes to `aiecsjs` are recorded in this file.
|
|
|
6
6
|
|
|
7
7
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
8
8
|
|
|
9
|
+
## [0.3.1] - 2026-05-29
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- **Packed EntityId signed-overflow for generation ≥ 128**: `createEntity` returned a negative number diverging from the unsigned value stored in archetype row arrays (`Uint32Array`), so query iteration (`runQuery`/`iterQuery`/`forEachEntity`) yielded an eid that failed `entityRow` lookups; `refOf`/`entityExists`/`deref` on a query-iterated high-generation entity misbehaved (`refOf` threw on a live entity). `packEid`/`packEntity` now normalise with `>>> 0`. No public-bundle behaviour change beyond the corrected eid representation (EntityId is opaque + in-memory-only).
|
|
14
|
+
- **`toJSON` silently dropped high-generation entities** (gen ≥ 128 with default 8-bit generation): `toJSON` contained its own inline pack expression that produced a signed (negative) result, diverging from the unsigned key stored in `arch.entityRow`. The affected entity passed the archetype check but failed `entityRow.has()`, so it was omitted from every snapshot and `serializeWorld` call. Fixed by replacing the inline expression with the canonical `packEid` (which applies `>>> 0`). SPOT principle: one pack source of truth.
|
|
15
|
+
- **Cross-subpath registry isolation** (`tsup splitting: false` → `splitting: true`): each compiled entry point (`dist/index.js`, `dist/serialize.js`, etc.) previously bundled its own private copy of `internal/world.ts`, including the module-scope `worldRegistry`. A world created via the core subpath was invisible to `serializeWorld`/`getRelationTargets`/`transferableSnapshot` imported from their respective subpaths, causing `world N is destroyed or unknown` at runtime. With `splitting: true`, esbuild extracts a shared chunk used by all entries; ESM and CJS are both verified by the new `scripts/check-dist-subpaths.mjs` smoke script.
|
|
16
|
+
- **`getRelationTargets` returned raw index as `EntityId`** (gen always 0): `addRelation` stores the target as a raw slot index (`& indexMask`). The previous return path cast this raw index directly to `EntityId`, which is equivalent to a packed id with generation 0. For any target that had been recycled (gen > 0), callers received a stale id that failed `entityExists`, `entityRow` lookups, and component access. Fixed by re-packing each raw index against the current generation via `packEid` before returning.
|
|
17
|
+
- **`resolveOptions` did not validate `indexBits + generationBits ≤ 32`**: the individual range checks (`indexBits ∈ [1, 24]`, `generationBits ∈ [0, 16]`) allowed combinations such as `indexBits=24, generationBits=16` (40 bits), where `gen << 24` silently overflowed and high-generation bits were lost. A sum check is now enforced with a clear error message. The `[Unreleased]` example corrected accordingly (`indexBits: 16, generationBits: 16` = 32 bits).
|
|
18
|
+
|
|
19
|
+
### Known Limitations
|
|
20
|
+
|
|
21
|
+
- **`createDeltaSerializer.apply` with a recycled target world**: `apply` uses the raw entity index from the delta snapshot as the `EntityId` directly. When the target world has already recycled any of those slots (generation > 0), component operations silently act on the wrong packed id. This is a known limitation of the experimental delta API; the common usage (delta → a fresh gen-0 render-mirror world) is unaffected. A proper raw-index-to-packed-id mapping is planned for 0.4. Avoid `apply` against a world that has previously destroyed entities.
|
|
22
|
+
|
|
23
|
+
### Documentation
|
|
24
|
+
|
|
25
|
+
- README / README_ZHTW updated to reflect the shipped 0.3.0 `EntityRef` API: the previous README still described EntityRef as "targeted for 0.3+" and `getEntityGeneration`/`packEntity` as experimental. Both files now correctly state EntityId has been packed since 0.3, and `EntityRef` / `refOf` / `deref` / `aliveRef` / `EntityNotAliveError` are all stable since 0.3.0. API table entries for these symbols added.
|
|
26
|
+
|
|
27
|
+
### Build & Tooling
|
|
28
|
+
|
|
29
|
+
- Coverage gate: `@vitest/coverage-v8` installed and wired into `prepublishOnly` (replaces `npm run test`) and CI. Thresholds: statements 95 / branches 80 / functions 97 / lines 98 — the achievable bar on pristine source. The branch figure honours the `?? 0` / `noUncheckedIndexedAccess` idiom on TypedArray reads (nullish-fallback branches unreachable by design); thresholds are raised only by adding tests, never by stripping defensive guards or scattering `/* v8 ignore */`.
|
|
30
|
+
- `fast-check` property tests (`tests/properties.test.ts`): pack/unpack round-trip invariant (asserts `e >= 0` to guard the P0 regression) and ABA-deref always-null invariant.
|
|
31
|
+
- Dispose three-cycle tests, error-path tests, and observer handler-throw behaviour documented in `tests/world.test.ts` / `tests/observers.test.ts`.
|
|
32
|
+
- `scripts/check-dist-subpaths.mjs` (`npm run verify:dist`): post-build smoke test that imports `createWorld`+`createEntity` from the core subpath and calls `serializeWorld`, `addRelation`/`getRelationTargets`, and `transferableSnapshot` from their respective subpaths for both ESM (`dist/*.js`) and CJS (`dist/*.cjs`). Wired into `prepublishOnly` (after `build`) and CI.
|
|
33
|
+
|
|
9
34
|
## [Unreleased]
|
|
10
35
|
|
|
11
36
|
### Planned for 0.4+
|
|
@@ -17,7 +42,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
|
17
42
|
default `generationBits=8`, a single slot recycled 256 times wraps back to its
|
|
18
43
|
starting generation, briefly re-opening the ABA window. Safe for v0.5 shmup
|
|
19
44
|
workloads (~5000 frame to wrap a single slot at 60 fps × ~1k destroys); high-churn
|
|
20
|
-
pools should set `createWorld({ generationBits: 16 })
|
|
45
|
+
pools should set `createWorld({ indexBits: 16, generationBits: 16 })` (16 + 16 = 32 bits;
|
|
46
|
+
65 536 entities × 65 536 generations). See test
|
|
21
47
|
[tests/ref.test.ts](./tests/ref.test.ts) `generation wrap` describe block.
|
|
22
48
|
|
|
23
49
|
## [0.3.0] - 2026-05-29
|
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
Part of the [ai\*js micro-runtime ecosystem](https://github.com/yshengliao) — see also [aifsmjs](https://github.com/yshengliao/aifsmjs) (FSM) and [aibridgejs](https://github.com/yshengliao/aibridgejs) (cross-context RPC).
|
|
12
12
|
|
|
13
|
-
aiecsjs uses **archetype tables with TypedArray columns** and **bitmask queries** — the same architecture that powers piecs and wolf-ecs at the top of public benchmarks. Its API is **functional and tree-shakable**, composed with `pipe()`. Components support both Structure-of-Arrays (SoA) and Array-of-Structures (AoS) layouts.
|
|
13
|
+
aiecsjs uses **archetype tables with TypedArray columns** and **bitmask queries** — the same architecture that powers piecs and wolf-ecs at the top of public benchmarks. Its API is **functional and tree-shakable**, composed with `pipe()`. Components support both Structure-of-Arrays (SoA) and Array-of-Structures (AoS) layouts. Since 0.3, `EntityId` packs index + generation into a single 32-bit number; the ABA-safe `EntityRef` API shipped in 0.3.0.
|
|
14
14
|
|
|
15
15
|
```ts
|
|
16
16
|
import { createWorld, createEntity, defineComponent, defineQuery, pipe, forEachEntity, Types } from 'aiecsjs'
|
|
@@ -380,8 +380,13 @@ type WorldOptions = {
|
|
|
380
380
|
| `destroyEntity` | `(world: World, eid: EntityId) => void` | stable |
|
|
381
381
|
| `entityExists` | `(world: World, eid: EntityId) => boolean` | stable |
|
|
382
382
|
| `getEntityIndex` | `(eid: EntityId) => number` | stable |
|
|
383
|
-
| `getEntityGeneration` | `(eid: EntityId) => number` |
|
|
384
|
-
| `packEntity` | `(index: number, generation: number) => EntityId` |
|
|
383
|
+
| `getEntityGeneration` | `(eid: EntityId) => number` | stable (since 0.3.0) — returns the 8-bit generation field; uses default 24/8 layout |
|
|
384
|
+
| `packEntity` | `(index: number, generation: number) => EntityId` | stable (since 0.3.0) — packs index + generation using default 24/8 layout |
|
|
385
|
+
| `refOf` | `<T>(world: World, eid: EntityId) => EntityRef<T>` | stable (since 0.3.0) — creates ABA-safe ref; throws `EntityNotAliveError` if entity is dead |
|
|
386
|
+
| `deref` | `<T>(world: World, ref: EntityRef<T>) => EntityId \| null` | stable (since 0.3.0) — returns live `EntityId` or `null` if stale/cross-world; never throws |
|
|
387
|
+
| `aliveRef` | `<T>(world: World, ref: EntityRef<T>) => boolean` | stable (since 0.3.0) — boolean guard form of `deref`; never throws |
|
|
388
|
+
| `EntityRef` | `interface EntityRef<T> { id: EntityId; worldId: number }` | stable (since 0.3.0) — opaque ABA-safe reference; in-memory only |
|
|
389
|
+
| `EntityNotAliveError` | `class EntityNotAliveError extends Error { eid: number }` | stable (since 0.3.0) — thrown by `refOf` when entity is not alive |
|
|
385
390
|
|
|
386
391
|
### Component — `aiecsjs`
|
|
387
392
|
|
package/README_ZHTW.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
隸屬 [ai\*js micro-runtime 生態系](https://github.com/yshengliao) ─ 另見 [aifsmjs](https://github.com/yshengliao/aifsmjs)(FSM)與 [aibridgejs](https://github.com/yshengliao/aibridgejs)(cross-context RPC)。
|
|
12
12
|
|
|
13
|
-
aiecsjs 採用 **原型表格搭配 TypedArray 欄位** 與 **位元遮罩查詢**,這正是 piecs 與 wolf-ecs 在公開效能評測中名列前茅所採用的架構。API 為 **函式式且可 tree-shake**,以 `pipe()` 組合。元件(Component)同時支援 SoA(結構陣列)與 AoS
|
|
13
|
+
aiecsjs 採用 **原型表格搭配 TypedArray 欄位** 與 **位元遮罩查詢**,這正是 piecs 與 wolf-ecs 在公開效能評測中名列前茅所採用的架構。API 為 **函式式且可 tree-shake**,以 `pipe()` 組合。元件(Component)同時支援 SoA(結構陣列)與 AoS(結構物件)兩種佈局。自 0.3 起,`EntityId` 將 index 與 generation 打包為單一 32-bit 數字;具 ABA 安全的 `EntityRef` API 已於 0.3.0 正式推出。
|
|
14
14
|
|
|
15
15
|
```ts
|
|
16
16
|
import { createWorld, createEntity, defineComponent, defineQuery, pipe, forEachEntity, Types } from 'aiecsjs'
|
|
@@ -387,8 +387,13 @@ type WorldOptions = {
|
|
|
387
387
|
| `destroyEntity` | `(world: World, eid: EntityId) => void` | stable |
|
|
388
388
|
| `entityExists` | `(world: World, eid: EntityId) => boolean` | stable |
|
|
389
389
|
| `getEntityIndex` | `(eid: EntityId) => number` | stable |
|
|
390
|
-
| `getEntityGeneration` | `(eid: EntityId) => number` | stable |
|
|
391
|
-
| `packEntity` | `(index: number, generation: number) => EntityId` | stable |
|
|
390
|
+
| `getEntityGeneration` | `(eid: EntityId) => number` | stable(自 0.3.0)— 回傳 8-bit generation 欄位;使用預設 24/8 佈局 |
|
|
391
|
+
| `packEntity` | `(index: number, generation: number) => EntityId` | stable(自 0.3.0)— 使用預設 24/8 佈局打包 index + generation |
|
|
392
|
+
| `refOf` | `<T>(world: World, eid: EntityId) => EntityRef<T>` | stable(自 0.3.0)— 建立 ABA-safe ref;entity 已死亡時拋出 `EntityNotAliveError` |
|
|
393
|
+
| `deref` | `<T>(world: World, ref: EntityRef<T>) => EntityId \| null` | stable(自 0.3.0)— 回傳存活的 `EntityId`,否則回傳 `null`;絕不拋出 |
|
|
394
|
+
| `aliveRef` | `<T>(world: World, ref: EntityRef<T>) => boolean` | stable(自 0.3.0)— `deref` 的布林 guard 形式;絕不拋出 |
|
|
395
|
+
| `EntityRef` | `interface EntityRef<T> { id: EntityId; worldId: number }` | stable(自 0.3.0)— 不透明的 ABA-safe 參照;僅限記憶體內使用 |
|
|
396
|
+
| `EntityNotAliveError` | `class EntityNotAliveError extends Error { eid: number }` | stable(自 0.3.0)— `refOf` 在 entity 不存活時拋出 |
|
|
392
397
|
|
|
393
398
|
### Component — `aiecsjs`
|
|
394
399
|
|
package/api.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://yshengliao.github.io/aiecsjs/api-schema.json",
|
|
3
3
|
"name": "aiecsjs",
|
|
4
|
-
"version": "0.3.
|
|
5
|
-
"generated": "2026-05-
|
|
4
|
+
"version": "0.3.1",
|
|
5
|
+
"generated": "2026-05-29",
|
|
6
6
|
"stability": "experimental",
|
|
7
7
|
"license": "MIT",
|
|
8
8
|
"repository": "https://github.com/yshengliao/aiecsjs",
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunk4RPFOVQC_cjs=require('./chunk-4RPFOVQC.cjs');var C=1,f=new Map;function _(n){let e=(n.all??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),t=(n.any??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),i=(n.none??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-");return `A${e}|Y${t}|N${i}`}function q(n){let e=Array.isArray(n)?{all:n}:n;for(let o of [...e.all??[],...e.any??[],...e.none??[]])if(!o||typeof o!="object"||typeof o.__id!="number")throw new TypeError("aiecsjs: defineQuery received a non-component value");let t=_(e),i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:(e.all??[]).map(o=>o.__id),any:(e.any??[]).map(o=>o.__id),none:(e.none??[]).map(o=>o.__id),columnViewCache:[...e.all??[],...e.any??[]],reactiveKind:"normal",sourceQueryId:-1,sourceQuery:null};return f.set(t,r),r}function z(n){let e=n,t=`enter:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"enter",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function T(n){let e=n,t=`exit:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"exit",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function p(n,e){if(n.queries[e.id]===e&&n.queryMasks.has(e.id))return;let t=n.options.maskWordCount,i=chunk4RPFOVQC_cjs.b(t),r=chunk4RPFOVQC_cjs.b(t),o=chunk4RPFOVQC_cjs.b(t);for(let a of e.all){let u=b(a),d=chunk4RPFOVQC_cjs.p(n,u);chunk4RPFOVQC_cjs.c(i,d);}for(let a of e.any){let u=b(a),d=chunk4RPFOVQC_cjs.p(n,u);chunk4RPFOVQC_cjs.c(r,d);}for(let a of e.none){let u=b(a),d=chunk4RPFOVQC_cjs.p(n,u);chunk4RPFOVQC_cjs.c(o,d);}let c={withMask:i,anyMask:r,noneMask:o,anyHasBits:!chunk4RPFOVQC_cjs.d(r)};n.queryMasks.set(e.id,c),n.queries[e.id]=e,n.queryArchetypeCache[e.id]=null,n.queryArchetypeStamp[e.id]=-1;let s=[...chunk4RPFOVQC_cjs.f(i),...chunk4RPFOVQC_cjs.f(r),...chunk4RPFOVQC_cjs.f(o)];for(let a of s){let u=n.bitToQueries.get(a);u||(u=new Set,n.bitToQueries.set(a,u)),u.add(e.id);}e.reactiveKind!=="normal"&&(n.reactiveBuffers.has(e.id)||n.reactiveBuffers.set(e.id,{entered:[],exited:[]}),e.sourceQuery&&p(n,e.sourceQuery));}function v(n,e){if(p(n,e),n.queryArchetypeCache[e.id]&&n.queryArchetypeStamp[e.id]===n.queryVersion)return n.queryArchetypeCache[e.id];let t=n.queryMasks.get(e.id),i=n.options.maskWordCount,r=[];for(let o=0;o<n.archetypes.length;o++){let c=n.archetypes[o];chunk4RPFOVQC_cjs.e(c.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,i)&&r.push(o);}return n.queryArchetypeCache[e.id]=r,n.queryArchetypeStamp[e.id]=n.queryVersion,r}function $(n,e){let t=chunk4RPFOVQC_cjs.i(n),r=v(t,e),o=[];for(let c of r){let s=t.archetypes[c];o.push({id:s.id,mask:Array.from(s.mask),size:s.size});}return o}function D(n,e){let t=chunk4RPFOVQC_cjs.i(n),i=e,r=[];if(i.reactiveKind==="enter"){let c=t.reactiveBuffers.get(i.id);if(c){for(let s of c.entered)r.push(s);c.entered.length=0;}return r}if(i.reactiveKind==="exit"){let c=t.reactiveBuffers.get(i.id);if(c){for(let s of c.exited)r.push(s);c.exited.length=0;}return r}let o=v(t,i);for(let c of o){let s=t.archetypes[c];for(let a=0;a<s.size;a++)r.push(s.entities[a]);}return r}function*H(n,e){let t=chunk4RPFOVQC_cjs.i(n),i=e;if(i.reactiveKind!=="normal"){let o=t.reactiveBuffers.get(i.id);if(!o)return;let c=i.reactiveKind==="enter"?o.entered:o.exited;for(let s of c)yield s;c.length=0;return}let r=v(t,i);for(let o of r){let c=t.archetypes[o];for(let s=0;s<c.size;s++)yield c.entities[s];}}function L(n,e,t){let i=chunk4RPFOVQC_cjs.i(n),r=e;if(r.reactiveKind!=="normal"){let s=i.reactiveBuffers.get(r.id);if(!s)return;let a=r.reactiveKind==="enter"?s.entered:s.exited;if(a.length===0)return;let u=w(i,r);for(let d=0;d<a.length;d++){let y=a[d];x(t,y,u);}a.length=0;return}p(i,r);let o=v(i,r),c=w(i,r);for(let s of o){let a=i.archetypes[s],u=a.entities,d=a.size;for(let y=0;y<d;y++)x(t,u[y],c);}}function x(n,e,t){switch(t.length){case 0:n(e);break;case 1:n(e,t[0]);break;case 2:n(e,t[0],t[1]);break;case 3:n(e,t[0],t[1],t[2]);break;case 4:n(e,t[0],t[1],t[2],t[3]);break;case 5:n(e,t[0],t[1],t[2],t[3],t[4]);break;default:n(e,...t);}}function w(n,e){let t=[];for(let i of e.columnViewCache){let r=chunk4RPFOVQC_cjs.H(i),o=n.componentBitFor.get(r.id);if(o===void 0){t.push(void 0);continue}let c=n.componentStorageByBit[o];if(!c){t.push(void 0);continue}c.kind==="soa"?t.push(c.soa):c.kind==="aos"?t.push(c.aos):t.push(true);}return t}function F(n,e,t,i,r){for(let s of f.values())s.reactiveKind!=="normal"&&s.sourceQuery&&n.queries[s.sourceQuery.id]!==s.sourceQuery&&p(n,s.sourceQuery);let o=n.bitToQueries.get(t);if(!o)return;let c=n.options.maskWordCount;for(let s of o){let a=n.queries[s];if(!a||a.reactiveKind!=="normal")continue;let u=n.queryMasks.get(s);if(!u)continue;let d=chunk4RPFOVQC_cjs.e(i,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c),y=chunk4RPFOVQC_cjs.e(r,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c);!d&&y?E(n,s,"enter",e):d&&!y&&E(n,s,"exit",e);}}function E(n,e,t,i){for(let r of f.values()){if(r.sourceQueryId!==e||r.reactiveKind!==t)continue;p(n,r);let o=A(n,r.id);t==="enter"?o.entered.push(i):o.exited.push(i);}}function A(n,e){let t=n.reactiveBuffers.get(e);return t||(t={entered:[],exited:[]},n.reactiveBuffers.set(e,t)),t}function b(n){let e=W(n);if(!e)throw new Error(`aiecsjs: component id ${n} not registered`);return e}var g=null;function O(n){g=n;}function W(n){return g?g(n):void 0}exports.a=q;exports.b=z;exports.c=T;exports.d=$;exports.e=D;exports.f=H;exports.g=L;exports.h=F;exports.i=O;//# sourceMappingURL=chunk-37HMYMJG.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-37HMYMJG.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/query.ts"],"names":["nextQueryId","moduleQueryCache","descKey","d","all","c","a","b","any","none","defineQuery","arg","desc","key","cached","q","enterQuery","query","reactive","exitQuery","ensureQueryRegistered","state","ww","withMask","createMask","anyMask","noneMask","compId","info","getComponentInfoById","bit","getOrRegisterComponentBit","setBit","bundle","isMaskZero","involvedBits","listBits","s","getQueryArchetypes","words","list","i","arch","matches","queryArchetypes","world","getWorldState","ids","out","id","runQuery","buf","e","archIds","r","iterQuery","src","forEachEntity","fn","cols","buildColumnViews","callWithCols","ents","n","eid","comp","getComponentInfo","storage","recordEntityMaskChange","changedBit","prevMask","nextMask","involved","qid","wasMatch","isMatch","pushReactive","queryId","kind","ensureReactiveBuffer","componentId","lazyGetComponentInfo","_getComponentInfoFn","registerComponentLookup"],"mappings":"mEAsBA,IAAIA,EAAc,CAAA,CACZC,CAAAA,CAAmB,IAAI,GAAA,CAE7B,SAASC,CAAAA,CAAQC,CAAAA,CAA4B,CAC3C,IAAMC,GAAOD,CAAAA,CAAE,GAAA,EAAO,EAAC,EACpB,GAAA,CAAKE,GAAMA,CAAAA,CAAE,IAAI,CAAA,CACjB,IAAA,CAAK,CAACC,CAAAA,CAAGC,CAAAA,GAAMD,EAAIC,CAAC,CAAA,CACpB,KAAK,GAAG,CAAA,CACLC,CAAAA,CAAAA,CAAOL,CAAAA,CAAE,KAAO,EAAC,EACpB,IAAKE,CAAAA,EAAMA,CAAAA,CAAE,IAAI,CAAA,CACjB,IAAA,CAAK,CAACC,CAAAA,CAAGC,IAAMD,CAAAA,CAAIC,CAAC,EACpB,IAAA,CAAK,GAAG,EACLE,CAAAA,CAAAA,CAAQN,CAAAA,CAAE,IAAA,EAAQ,IACrB,GAAA,CAAKE,CAAAA,EAAMA,EA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AAG,CAEzC,GADI,CAAA,CAAE,gBAAkB4E,CAAAA,EACpB,CAAA,CAAE,eAAiBC,CAAAA,CAAM,SAE7B1D,CAAAA,CAAsBC,CAAAA,CAAO,CAAC,CAAA,CAC9B,IAAM8B,EAAM4B,CAAAA,CAAqB1D,CAAAA,CAAO,EAAE,EAAE,CAAA,CACxCyD,CAAAA,GAAS,OAAA,CAAS3B,EAAI,OAAA,CAAQ,IAAA,CAAKa,CAAa,CAAA,CAC/Cb,CAAAA,CAAI,OAAO,IAAA,CAAKa,CAAa,EACpC,CACF,CAEA,SAASe,CAAAA,CAAqB1D,EAAmBoD,CAAAA,CAA6B,CAC5E,IAAItB,CAAAA,CAAM9B,CAAAA,CAAM,eAAA,CAAgB,GAAA,CAAIoD,CAAG,CAAA,CACvC,OAAKtB,IACHA,CAAAA,CAAM,CAAE,QAAS,EAAC,CAAG,MAAA,CAAQ,EAAG,CAAA,CAChC9B,CAAAA,CAAM,gBAAgB,GAAA,CAAIoD,CAAAA,CAAKtB,CAAG,CAAA,CAAA,CAE7BA,CACT,CAIA,SAAStB,EAAqBmD,CAAAA,CAAoC,CAEhE,IAAMpD,CAAAA,CAAOqD,CAAAA,CAAqBD,CAAW,CAAA,CAC7C,GAAI,CAACpD,CAAAA,CAAM,MAAM,IAAI,KAAA,CAAM,yBAAyBoD,CAAW,CAAA,eAAA,CAAiB,EAChF,OAAOpD,CACT,CAEA,IAAIsD,EAA0E,IAAA,CACvE,SAASC,EAAwBzB,CAAAA,CAAqD,CAC3FwB,EAAsBxB,EACxB,CACA,SAASuB,CAAAA,CAAqBhC,EAAuC,CACnE,OAAOiC,EAAsBA,CAAAA,CAAoBjC,CAAE,EAAI,MACzD","file":"chunk-37HMYMJG.cjs","sourcesContent":["import { createMask, isMaskZero, listBits, matches, setBit } from './bitmask.js'\nimport { getComponentInfo } from './component.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const any = (d.any ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const none = (d.none ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [\n ...listBits(withMask),\n ...listBits(anyMask),\n ...listBits(noneMask),\n ]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (\n matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n ) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n const ents = arch.entities\n const n = arch.size\n for (let r = 0; r < n; r++) {\n callWithCols(fn, ents[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(\n fn: (eid: EntityId, ...cols: any[]) => void,\n eid: EntityId,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, cols[0])\n break\n case 2:\n fn(eid, cols[0], cols[1])\n break\n case 3:\n fn(eid, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(eid, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(eid, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(\n prevMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n const isMatch = matches(\n nextMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var O="0.3.1";function R(n){return new Uint32Array(n)}function _(n,t){let e=t>>>5;n[e]=(n[e]??0)|1<<(t&31);}function j(n,t){let e=t>>>5;n[e]=(n[e]??0)&~(1<<(t&31));}function m(n,t){let e=t>>>5;return ((n[e]??0)&1<<(t&31))!==0}function w(n){let t=new Uint32Array(n.length);for(let e=0;e<n.length;e++)t[e]=n[e]??0;return t}function v(n){let t=[];for(let e=0;e<n.length;e++)t.push((n[e]??0).toString(16));return t.join(",")}function xt(n){for(let t=0;t<n.length;t++)if((n[t]??0)!==0)return false;return true}function ht(n,t,e,o,i,s){let r=!i;for(let a=0;a<s;a++){let d=n[a]??0,c=t[a]??0,u=e[a]??0,f=o[a]??0;if((d&c)!==c||(d&f)!==0)return false;!r&&(d&u)!==0&&(r=true);}return r}function At(n){let t=[];for(let e=0;e<n.length;e++){let o=n[e]??0;for(;o!==0;){let i=(e<<5)+T(o);t.push(i),o&=o-1;}}return t}function L(n,t,e,o){for(let i=0;i<e;i++){let s=n[t+i]??0;for(;s!==0;){let r=(i<<5)+T(s);o(r),s&=s-1;}}}function wt(n,t,e,o,i,s,r){let a=!r;for(let d=0;d<e;d++){let c=n[t+d]??0,u=o[d]??0,f=i[d]??0,l=s[d]??0;if((c&u)!==u||(c&l)!==0)return false;!a&&(c&f)!==0&&(a=true);}return a}function T(n){return 31-Math.clz32(n&-n)}var C={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},Q=256,Z=1,b=new Map;function y(n){let t=b.get(n.id);if(!t)throw new Error(`aiecsjs: world ${n.id} is destroyed or unknown`);if(t.destroyed)throw new Error(`aiecsjs: world ${n.id} is destroyed`);return t}function J(n){b.set(n.id,n);}function tt(n){b.delete(n);}function Et(n){return b.has(n)}function nt(n){let t=n??{},e=t.indexBits??C.indexBits,o=t.generationBits??C.generationBits,i=Q;if(e<1||e>24)throw new Error("aiecsjs: indexBits must be in [1, 24]");if(o<0||o>16)throw new Error("aiecsjs: generationBits must be in [0, 16]");if(e+o>32)throw new Error(`aiecsjs: indexBits (${e}) + generationBits (${o}) must be <= 32`);let s=1<<e,r=Math.max(1,Math.min(t.initialCapacity??C.initialCapacity,s)),a=Math.max(r,Math.min(t.maxEntities??C.maxEntities,s));return {initialCapacity:r,maxEntities:a,indexBits:e,generationBits:o,indexMask:(1<<e)-1,generationMask:o===0?0:(1<<o)-1,maxComponents:i,maskWordCount:Math.ceil(i/32),buffer:t.buffer??null,bufferByteOffset:t.bufferByteOffset??0}}function et(n,t){return {id:0,mask:R(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(t).fill(-1),edgeRemove:new Int32Array(t).fill(-1)}}function vt(n){let t=nt(n),e=Z++,o=t.generationBits>8?Uint16Array:Uint8Array,i=new o(t.initialCapacity),s={id:e,capacity:t.initialCapacity,version:O,options:t,size:0,nextFreshIndex:1,freeList:[],generations:i,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(t.maxComponents).fill(null),componentStorageByBit:new Array(t.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(t.initialCapacity),entityMask:new Uint32Array(t.initialCapacity*t.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryMasks:new Map,queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:t.buffer,readOnly:false},r=et(t.maskWordCount,t.maxComponents);return r.id=0,s.archetypes.push(r),s.archetypeByMaskHash.set(v(r.mask),0),J(s),ot(s)}function ot(n){return {id:n.id,get capacity(){return n.capacity},version:n.version}}function St(n){let t=b.get(n.id);!t||t.destroyed||(t.destroyed=true,t.archetypes=[],t.archetypeByMaskHash.clear(),t.componentInfoByBit=[],t.componentStorageByBit=[],t.queries=[],t.queryMasks.clear(),t.queryArchetypeCache=[],t.observers=[],t.relationStorage.clear(),t.reactiveBuffers.clear(),tt(n.id));}function Wt(n){let t=y(n);t.size=0,t.nextFreshIndex=1,t.freeList=[],t.generations.fill(0),t.entityArchetype.fill(0),t.entityMask.fill(0);for(let e of t.archetypes)e.size=0,e.entityRow.clear();for(let e of t.componentStorageByBit)if(e)if(e.kind==="soa"&&e.soa)for(let o of Object.keys(e.soa))e.soa[o]?.fill(0);else e.kind==="aos"&&e.aos&&e.aos.fill(void 0);t.queryVersion++;for(let e of t.reactiveBuffers.values())e.entered.length=0,e.exited.length=0;}function Bt(n){return y(n).size}function Mt(n){return y(n).capacity}function F(n,t){if(t<=n.capacity)return;if(t>n.options.maxEntities)throw new Error(`aiecsjs: requested capacity ${t} exceeds maxEntities ${n.options.maxEntities}`);let e=n.capacity;for(;e<t;)e=Math.min(e*2,n.options.maxEntities);rt(n,e);}function rt(n,t){let e=n.generations.constructor,o=new e(t);o.set(n.generations),n.generations=o;let i=new Uint32Array(t);i.set(n.entityArchetype),n.entityArchetype=i;let s=n.options.maskWordCount,r=new Uint32Array(t*s);r.set(n.entityMask),n.entityMask=r;for(let a of n.componentStorageByBit)if(a)if(a.kind==="soa"&&a.soa){let d=n.componentInfoByBit[a.bit];d&&it(a.soa,d.fields,t);}else a.kind==="aos"&&a.aos&&(a.aos.length=t);n.capacity=t;}function it(n,t,e){for(let o of t){let i=n[o.name];if(!i)continue;let s=e*o.vectorLen;if(i.length>=s)continue;let r=new o.ctor(s);r.set(i),n[o.name]=r;}}function z(n,t){let e=v(t),o=n.archetypeByMaskHash.get(e);if(o!==void 0)return {archId:o,created:false};let i=n.archetypes.length,s={id:i,mask:w(t),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:st(t),edgeAdd:new Int32Array(n.options.maxComponents).fill(-1),edgeRemove:new Int32Array(n.options.maxComponents).fill(-1)};return n.archetypes.push(s),n.archetypeByMaskHash.set(e,i),n.queryVersion++,{archId:i,created:true}}function I(n,t){if(t<=n.capacity)return;let e=n.capacity;for(;e<t;)e*=2;let o=new Uint32Array(e);o.set(n.entities),n.entities=o,n.capacity=e;}function st(n){let t=[];for(let e=0;e<n.length;e++){let o=n[e]??0;for(;o!==0;){let i=o&-o,s=(e<<5)+(31-Math.clz32(i));t.push(s),o&=o-1;}}return t}function D(n,t){let e=n.componentBitFor.get(t.id);if(e!==void 0)return e;if(n.nextComponentBit>=n.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${n.options.maxComponents}`);let o=n.nextComponentBit++;n.componentBitFor.set(t.id,o),n.componentInfoByBit[o]=t;let i;if(t.kind==="soa"){let s={};for(let r of t.fields)s[r.name]=new r.ctor(n.capacity*r.vectorLen);i={kind:"soa",componentId:t.id,bit:o,soa:s};}else t.kind==="aos"?i={kind:"aos",componentId:t.id,bit:o,aos:new Array(n.capacity)}:i={kind:"tag",componentId:t.id,bit:o};return n.componentStorageByBit[o]=i,o}function x(n,t){let e=n.options.maskWordCount,o=new Uint32Array(e),s=(t&n.options.indexMask)*e;for(let r=0;r<e;r++)o[r]=n.entityMask[s+r]??0;return o}function N(n,t,e){let o=n.options.maskWordCount,s=(t&n.options.indexMask)*o;for(let r=0;r<o;r++)n.entityMask[s+r]=e[r]??0;}function g(n,t){return n.componentBitFor.get(t.id)}function Ut(n){if(!n||typeof n!="object")return false;let t=n;return typeof t.id!="number"||typeof t.version!="string"?false:b.has(t.id)}var W=1,at={i8:Int8Array,u8:Uint8Array,i16:Int16Array,u16:Uint16Array,i32:Int32Array,u32:Uint32Array,f32:Float32Array,f64:Float64Array,eid:Uint32Array,bool:Uint8Array},h=new Map;function Lt(n){let t=[];for(let[s,r]of Object.entries(n)){let a,d=1;if(typeof r=="string")a=r;else if(Array.isArray(r)){let[u,f]=r;a=u,d=f;}else throw new TypeError(`aiecsjs: invalid field declaration for "${s}"`);let c=at[a];if(!c)throw new TypeError(`aiecsjs: unknown field type "${a}" for field "${s}"`);t.push({name:s,type:a,vectorLen:d,ctor:c,bytesPerElement:c.BYTES_PER_ELEMENT});}let e=W++,o={id:e,kind:"soa",schema:n,fields:t,factory:null};return h.set(e,o),{__kind:"soa",__id:e,__schema:n}}function Tt(){let n=W++,t={id:n,kind:"tag",schema:null,fields:[],factory:null};return h.set(n,t),{__kind:"tag",__id:n}}function Ft(n){let t=W++,e=n??(()=>({})),o={id:t,kind:"aos",schema:null,fields:[],factory:e};return h.set(t,o),{__kind:"aos",__id:t,__factory:e}}function A(n){let t=h.get(n.__id);if(!t)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return t}function P(n,t,e,o){let i=y(n);if(i.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(i,t))throw new Error(`aiecsjs: addComponent on dead entity ${t}`);let s=A(e),r=D(i,s),a=x(i,t);if(m(a,r)){o!==void 0&&S(i,t,e,o);return}let d=w(a);_(d,r),G(i,t,d),S(i,t,e,o),ct(i,t,r),V(i,t,r,a,d);}function zt(n,t,e){let o=y(n);if(o.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(o,t))return;let i=A(e),s=g(o,i);if(s===void 0)return;let r=x(o,t);if(!m(r,s))return;let a=w(r);j(a,s),G(o,t,a),dt(o,t,s);let d=t&o.options.indexMask,c=o.componentStorageByBit[s];c?.kind==="soa"&&c.soa?q(c.soa,i.fields,d):c?.kind==="aos"&&c.aos&&(c.aos[d]=void 0),V(o,t,s,r,a);}function Dt(n,t,e){let o=y(n);if(!p(o,t))return false;let i=A(e),s=g(o,i);if(s===void 0)return false;let r=x(o,t);return m(r,s)}function Nt(n,t,e){let o=y(n);if(!p(o,t))return;let i=A(e),s=g(o,i);if(s===void 0)return;let r=x(o,t);if(!m(r,s))return;let a=o.componentStorageByBit[s];if(a){if(a.kind==="soa")return a.soa;if(a.kind==="aos"){let d=t&o.options.indexMask;return a.aos?.[d]}return true}}function Pt(n,t,e,o){let i=y(n);if(i.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(i,t))throw new Error(`aiecsjs: setComponent on dead entity ${t}`);let s=A(e),r=g(i,s);if(r===void 0){P(n,t,e,o);return}let a=x(i,t);if(!m(a,r)){P(n,t,e,o);return}S(i,t,e,o),ft(i,t,r,o);}function S(n,t,e,o){let i=A(e),s=n.componentBitFor.get(i.id);if(s===void 0)return;let r=n.componentStorageByBit[s];if(!r)return;let a=t&n.options.indexMask;if(i.kind==="soa"&&r.soa){if(o==null)return;let d=o;for(let c of i.fields){if(!(c.name in d))continue;let u=r.soa[c.name];if(!u)continue;let f=d[c.name];if(c.vectorLen===1)u[a]=typeof f=="boolean"?f?1:0:Number(f);else if(Array.isArray(f)||ArrayBuffer.isView(f)){let l=a*c.vectorLen,K=f;for(let k=0;k<c.vectorLen;k++)u[l+k]=Number(K[k]??0);}}}else if(i.kind==="aos"&&r.aos){let d=i.factory??(()=>({})),c=r.aos[a];if(c===void 0&&(c=d(),r.aos[a]=c),o&&typeof o=="object"){let u=o,f=c;for(let l of Object.keys(u))l==="__proto__"||l==="constructor"||l==="prototype"||(f[l]=u[l]);}}}function q(n,t,e){for(let o of t){let i=n[o.name];if(i)if(o.vectorLen===1)i[e]=0;else {let s=e*o.vectorLen;for(let r=0;r<o.vectorLen;r++)i[s+r]=0;}}}function $(n,t){let e=n.options.maskWordCount,o=t&n.options.indexMask,i=o*e;L(n.entityMask,i,e,s=>{let r=n.componentStorageByBit[s],a=n.componentInfoByBit[s];r?.kind==="soa"&&r.soa&&a?q(r.soa,a.fields,o):r?.kind==="aos"&&r.aos&&(r.aos[o]=void 0);});}function G(n,t,e){let o=t&n.options.indexMask,i=n.entityArchetype[o]??0,s=n.archetypes[i];if(!s)return;let a=z(n,e).archId,d=n.archetypes[a];if(d){if(a!==i){let c=s.entityRow.get(t);if(c!==void 0){let f=s.size-1;if(c!==f){let l=s.entities[f]??0;s.entities[c]=l,s.entityRow.set(l,c);}s.entities[f]=0,s.entityRow.delete(t),s.size--;}I(d,d.size+1);let u=d.size;d.entities[u]=t,d.entityRow.set(t,u),d.size++,n.entityArchetype[o]=a;}N(n,t,e);}}var E={fireAdd:()=>{},fireRemove:()=>{},fireSet:()=>{}},H=()=>{};function qt(n){H=n;}function V(n,t,e,o,i){H(n,t,e,o,i);}function $t(n){E=n;}function ct(n,t,e){E.fireAdd(n,t,e);}function dt(n,t,e){E.fireRemove(n,t,e);}function ft(n,t,e,o){E.fireSet(n,t,e,o);}function Gt(n){return h.get(n)}function Ht(){return Array.from(h.values())}var U=24,ut=8,Y=(1<<U)-1,X=(1<<ut)-1;function yt(n,t,e){return ((t&e.generationMask)<<e.indexBits|n&e.indexMask)>>>0}function Kt(n,t){return n&t.indexMask}function Qt(n,t){return n>>>t.indexBits&t.generationMask}function Zt(n){let t=y(n);if(t.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let e;if(t.freeList.length>0)e=t.freeList.pop();else {if(t.nextFreshIndex>=t.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${t.options.maxEntities}`);t.nextFreshIndex>=t.capacity&&F(t,t.nextFreshIndex+1),e=t.nextFreshIndex++;}let o=t.generations[e]??0,i=yt(e,o,t.options),s=t.archetypes[0];if(!s)throw new Error("aiecsjs: missing empty archetype");I(s,s.size+1);let r=s.size;s.entities[r]=i,s.entityRow.set(i,r),s.size++,t.entityArchetype[e]=0;let a=t.options.maskWordCount,d=e*a;for(let c=0;c<a;c++)t.entityMask[d+c]=0;return t.size++,i}function Jt(n,t){let e=y(n);if(e.readOnly)throw new Error("aiecsjs: cannot destroyEntity on a read-only world");if(!p(e,t))return;let o=t&e.options.indexMask,{dispatchDestroyObservers:i}=pt();i(e,t),mt(e,t),$(e,t);let s=e.entityArchetype[o]??0,r=e.archetypes[s];if(r){let c=r.entityRow.get(t);if(c!==void 0){let u=r.size-1;if(c!==u){let f=r.entities[u]??0;r.entities[c]=f,r.entityRow.set(f,c);}r.entities[u]=0,r.entityRow.delete(t),r.size--;}}e.entityArchetype[o]=0;let a=e.options.maskWordCount,d=o*a;for(let c=0;c<a;c++)e.entityMask[d+c]=0;e.generations[o]=(e.generations[o]??0)+1&e.options.generationMask,e.freeList.push(o),e.size--;}function lt(n,t){let e=y(n);return p(e,t)}function p(n,t){let e=t&n.options.indexMask;if(e<=0||e>=n.capacity)return false;let o=n.entityArchetype[e]??0,i=n.archetypes[o];if(!i||!i.entityRow.has(t))return false;let s=n.generations[e]??0,r=t>>>n.options.indexBits&n.options.generationMask;return s===r}function tn(n){return n&Y}function nn(n){return n>>>U&X}function en(n,t){return ((t&X)<<U|n&Y)>>>0}function on(n,t){return typeof t!="number"?false:lt(n,t)}var B=null;function rn(n){B=n;}function pt(){return B||{dispatchDestroyObservers:()=>{}}}var M=null;function sn(n){M=n;}function mt(n,t){M&&M(n,t);}exports.A=en;exports.B=on;exports.C=rn;exports.D=sn;exports.E=Lt;exports.F=Tt;exports.G=Ft;exports.H=A;exports.I=P;exports.J=zt;exports.K=Dt;exports.L=Nt;exports.M=Pt;exports.N=qt;exports.O=$t;exports.P=Gt;exports.Q=Ht;exports.a=O;exports.b=R;exports.c=_;exports.d=xt;exports.e=ht;exports.f=At;exports.g=L;exports.h=wt;exports.i=y;exports.j=Et;exports.k=vt;exports.l=St;exports.m=Wt;exports.n=Bt;exports.o=Mt;exports.p=D;exports.q=Ut;exports.r=yt;exports.s=Kt;exports.t=Qt;exports.u=Zt;exports.v=Jt;exports.w=lt;exports.x=p;exports.y=tn;exports.z=nn;//# sourceMappingURL=chunk-4RPFOVQC.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-4RPFOVQC.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/version.ts","../src/internal/bitmask.ts","../src/internal/world.ts","../src/internal/component.ts","../src/internal/entity.ts"],"names":["VERSION","createMask","wordCount","setBit","mask","bit","w","clearBit","testBit","cloneMask","src","out","i","maskHash","m","parts","isMaskZero","matches","withMask","anyMask","noneMask","anyHasBits","words","anyHit","wm","am","nm","listBits","word","ctz32","forEachSetBit","base","fn","wi","matchesEntityMask","entityMask","v","DEFAULT_OPTIONS","DEFAULT_MAX_COMPONENTS","nextWorldId","worldRegistry","getWorldState","world","state","registerWorld","unregisterWorld","id","isWorldRegistered","resolveOptions","opts","o","indexBits","generationBits","maxComponents","maxByIndex","initialCapacity","maxEntities","createEmptyArchetype","maskWordCount","createWorld","options","resolved","generationCtor","generations","empty","makePublicWorld","destroyWorld","resetWorld","arch","storage","k","buf","getWorldSize","getWorldCapacity","ensureCapacity","needed","newCap","growEntityArrays","genCtor","newGen","newArch","newMask","info","growSoAColumns","soa","fields","f","old","newLen","next","findOrCreateArchetype","key","existing","collectBits","ensureArchetypeCapacity","bits","lsb","getOrRegisterComponentBit","readEntityMask","eid","writeEntityMask","tryGetComponentBit","isWorld","x","obj","nextComponentId","TYPE_CTOR","componentInfoById","defineComponent","schema","name","decl","type","vectorLen","t","len","ctor","defineTag","defineObjectComponent","factory","fac","getComponentInfo","component","addComponent","initial","isAliveInternal","prevMask","writeInitial","migrateEntity","fireAddObservers","notifyMaskChange","removeComponent","fireRemoveObservers","idx","clearSoAEntity","hasComponent","getComponent","setComponent","value","fireSetObservers","packedEid","col","val","arr","inst","target","clearAllEntityStorages","srcArchId","srcArch","destArchId","destArch","row","lastRow","moved","newRow","_dispatch","_maskChange","registerMaskChangeDispatch","prev","registerObserverDispatch","api","getComponentByInternalId","listAllComponents","DEFAULT_INDEX_BITS","DEFAULT_GENERATION_BITS","DEFAULT_INDEX_MASK","DEFAULT_GENERATION_MASK","packEid","gen","unpackIdx","unpackGen","createEntity","destroyEntity","dispatchDestroyObservers","lazyObservers","cleanupRelationsOnDestroy","archId","entityExists","storedGen","refGen","getEntityIndex","getEntityGeneration","packEntity","index","generation","isEntity","_observersAPI","registerObserversAPI","_relationsCleanup","registerRelationsCleanup"],"mappings":"aAAO,IAAMA,CAAAA,CAAU,QCEhB,SAASC,CAAAA,CAAWC,EAAgC,CACzD,OAAO,IAAI,WAAA,CAAYA,CAAS,CAClC,CAEO,SAASC,CAAAA,CAAOC,EAAmBC,CAAAA,CAAmB,CAC3D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,CAAA,CAClBD,CAAAA,CAAKE,CAAC,CAAA,CAAA,CAAKF,EAAKE,CAAC,CAAA,EAAK,GAAM,CAAA,GAAMD,CAAAA,CAAM,IAC1C,CAEO,SAASE,CAAAA,CAASH,CAAAA,CAAmBC,CAAAA,CAAmB,CAC7D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,EAClBD,CAAAA,CAAKE,CAAC,GAAKF,CAAAA,CAAKE,CAAC,CAAA,EAAK,CAAA,EAAK,EAAE,CAAA,GAAMD,EAAM,EAAA,CAAA,EAC3C,CAEO,SAASG,CAAAA,CAAQJ,CAAAA,CAAmBC,EAAsB,CAC/D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,CAAA,CAClB,OAAA,CAAA,CAASD,EAAKE,CAAC,CAAA,EAAK,GAAM,CAAA,GAAMD,CAAAA,CAAM,OAAU,CAClD,CAOO,SAASI,CAAAA,CAAUC,CAAAA,CAA+B,CACvD,IAAMC,CAAAA,CAAM,IAAI,YAAYD,CAAAA,CAAI,MAAM,EACtC,I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O,SAASoB,EAAAA,CAAS/I,CAAAA,CAAc6D,CAAAA,CAA2B,CAChE,OAAI,OAAOA,CAAAA,EAAM,SAAiB,KAAA,CAC3B0E,EAAAA,CAAavI,EAAO6D,CAAa,CAC1C,CAOA,IAAImF,CAAAA,CAAqC,IAAA,CAClC,SAASC,EAAAA,CAAqB3B,CAAAA,CAAyB,CAC5D0B,CAAAA,CAAgB1B,EAClB,CACA,SAASc,EAAAA,EAA8B,CACrC,OAAKY,CAAAA,EACI,CAAE,yBAA0B,IAAM,CAAC,CAAE,CAGhD,CAEA,IAAIE,CAAAA,CAAyE,IAAA,CACtE,SAASC,EAAAA,CAAyB7J,CAAAA,CAAsD,CAC7F4J,EAAoB5J,EACtB,CACA,SAAS+I,EAAAA,CAA0BpI,CAAAA,CAAmBwD,CAAAA,CAAqB,CACrEyF,CAAAA,EAAmBA,CAAAA,CAAkBjJ,CAAAA,CAAOwD,CAAG,EACrD","file":"chunk-4RPFOVQC.cjs","sourcesContent":["export const VERSION = '0.3.1'\n","// Multi-word Uint32 bitmask helpers.\n\nexport function createMask(wordCount: number): Uint32Array {\n return new Uint32Array(wordCount)\n}\n\nexport function setBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) | (1 << (bit & 31))\n}\n\nexport function clearBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) & ~(1 << (bit & 31))\n}\n\nexport function testBit(mask: Uint32Array, bit: number): boolean {\n const w = bit >>> 5\n return ((mask[w] ?? 0) & (1 << (bit & 31))) !== 0\n}\n\nexport function copyMask(dst: Uint32Array, src: Uint32Array): void {\n const n = src.length\n for (let i = 0; i < n; i++) dst[i] = src[i] ?? 0\n}\n\nexport function cloneMask(src: Uint32Array): Uint32Array {\n const out = new Uint32Array(src.length)\n for (let i = 0; i < src.length; i++) out[i] = src[i] ?? 0\n return out\n}\n\nexport function maskEquals(a: Uint32Array, b: Uint32Array): boolean {\n const n = a.length\n if (b.length !== n) return false\n for (let i = 0; i < n; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return false\n return true\n}\n\nexport function maskHash(m: Uint32Array): string {\n // Stable string key for Map lookups. Hex-joined.\n const parts: string[] = []\n for (let i = 0; i < m.length; i++) {\n parts.push((m[i] ?? 0).toString(16))\n }\n return parts.join(',')\n}\n\nexport function isMaskZero(m: Uint32Array): boolean {\n for (let i = 0; i < m.length; i++) if ((m[i] ?? 0) !== 0) return false\n return true\n}\n\nexport function unionMask(a: Uint32Array, b: Uint32Array): Uint32Array {\n const out = new Uint32Array(a.length)\n for (let i = 0; i < a.length; i++) out[i] = (a[i] ?? 0) | (b[i] ?? 0)\n return out\n}\n\n/**\n * Test whether an archetype's mask matches a query.\n * - withMask: all of these bits must be present\n * - anyMask: if anyHasBits, at least one of these bits must be present\n * - noneMask: none of these bits may be present\n */\nexport function matches(\n mask: Uint32Array,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n words: number,\n): boolean {\n let anyHit = !anyHasBits\n for (let w = 0; w < words; w++) {\n const m = mask[w] ?? 0\n const wm = withMask[w] ?? 0\n const am = anyMask[w] ?? 0\n const nm = noneMask[w] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nexport function listBits(mask: Uint32Array): number[] {\n const out: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const bit = (w << 5) + ctz32(word)\n out.push(bit)\n word &= word - 1\n }\n }\n return out\n}\n\n// Iterate set bits in a slice of a larger Uint32Array starting at `base`.\n// Shared by destroy paths and storage cleanup so the bit-extraction maths\n// lives in exactly one place.\nexport function forEachSetBit(\n mask: Uint32Array,\n base: number,\n words: number,\n fn: (bit: number) => void,\n): void {\n for (let wi = 0; wi < words; wi++) {\n let word = mask[base + wi] ?? 0\n while (word !== 0) {\n const bit = (wi << 5) + ctz32(word)\n fn(bit)\n word &= word - 1\n }\n }\n}\n\n// Match a query against an entity's mask stored as a slice inside a larger\n// Uint32Array. Reading directly from the parent array avoids the temporary\n// Uint32Array allocation on every observer dispatch.\nexport function matchesEntityMask(\n entityMask: Uint32Array,\n base: number,\n words: number,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n): boolean {\n let anyHit = !anyHasBits\n for (let i = 0; i < words; i++) {\n const m = entityMask[base + i] ?? 0\n const wm = withMask[i] ?? 0\n const am = anyMask[i] ?? 0\n const nm = noneMask[i] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nfunction ctz32(v: number): number {\n // Count trailing zeros in a 32-bit integer (assumes v !== 0)\n return 31 - Math.clz32(v & -v)\n}\n","import { VERSION } from '../version.js'\nimport { cloneMask, copyMask, createMask, maskHash } from './bitmask.js'\nimport type {\n ArchetypeState,\n ComponentInfo,\n FieldInfo,\n ResolvedWorldOptions,\n World,\n WorldComponentStorage,\n WorldOptions,\n WorldState,\n} from './types.js'\n\nexport const WORLD_BRAND = Symbol.for('aiecsjs.world')\n\nconst DEFAULT_OPTIONS: Required<Omit<WorldOptions, 'buffer' | 'bufferByteOffset'>> = {\n initialCapacity: 1024,\n maxEntities: 1_000_000,\n indexBits: 24,\n generationBits: 8,\n}\n\nconst DEFAULT_MAX_COMPONENTS = 256\n\nlet nextWorldId = 1\nconst worldRegistry = new Map<number, WorldState>()\n\nexport function getWorldState(world: World): WorldState {\n const state = worldRegistry.get(world.id)\n if (!state) throw new Error(`aiecsjs: world ${world.id} is destroyed or unknown`)\n if (state.destroyed) throw new Error(`aiecsjs: world ${world.id} is destroyed`)\n return state\n}\n\nexport function registerWorld(state: WorldState): void {\n worldRegistry.set(state.id, state)\n}\n\nexport function unregisterWorld(id: number): void {\n worldRegistry.delete(id)\n}\n\nexport function isWorldRegistered(id: number): boolean {\n return worldRegistry.has(id)\n}\n\nfunction resolveOptions(opts: WorldOptions | undefined): ResolvedWorldOptions {\n const o = opts ?? {}\n const indexBits = o.indexBits ?? DEFAULT_OPTIONS.indexBits\n const generationBits = o.generationBits ?? DEFAULT_OPTIONS.generationBits\n const maxComponents = DEFAULT_MAX_COMPONENTS\n if (indexBits < 1 || indexBits > 24) {\n throw new Error('aiecsjs: indexBits must be in [1, 24]')\n }\n if (generationBits < 0 || generationBits > 16) {\n throw new Error('aiecsjs: generationBits must be in [0, 16]')\n }\n if (indexBits + generationBits > 32) {\n throw new Error(\n `aiecsjs: indexBits (${indexBits}) + generationBits (${generationBits}) must be <= 32`,\n )\n }\n const maxByIndex = 1 << indexBits\n const initialCapacity = Math.max(\n 1,\n Math.min(o.initialCapacity ?? DEFAULT_OPTIONS.initialCapacity, maxByIndex),\n )\n const maxEntities = Math.max(\n initialCapacity,\n Math.min(o.maxEntities ?? DEFAULT_OPTIONS.maxEntities, maxByIndex),\n )\n return {\n initialCapacity,\n maxEntities,\n indexBits,\n generationBits,\n indexMask: (1 << indexBits) - 1,\n generationMask: generationBits === 0 ? 0 : (1 << generationBits) - 1,\n maxComponents,\n maskWordCount: Math.ceil(maxComponents / 32),\n buffer: o.buffer ?? null,\n bufferByteOffset: o.bufferByteOffset ?? 0,\n }\n}\n\nexport function createEmptyArchetype(maskWordCount: number, maxComponents: number): ArchetypeState {\n return {\n id: 0,\n mask: createMask(maskWordCount),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: [],\n edgeAdd: new Int32Array(maxComponents).fill(-1),\n edgeRemove: new Int32Array(maxComponents).fill(-1),\n }\n}\n\nexport function createWorld(options?: WorldOptions): World {\n const resolved = resolveOptions(options)\n const id = nextWorldId++\n\n const generationCtor = resolved.generationBits > 8 ? Uint16Array : Uint8Array\n const generations = new generationCtor(resolved.initialCapacity)\n\n const state: WorldState = {\n id,\n capacity: resolved.initialCapacity,\n version: VERSION,\n options: resolved,\n size: 0,\n nextFreshIndex: 1, // 0 reserved\n freeList: [],\n generations,\n destroyed: false,\n componentBitFor: new Map<number, number>(),\n componentInfoByBit: new Array(resolved.maxComponents).fill(null),\n componentStorageByBit: new Array(resolved.maxComponents).fill(null),\n nextComponentBit: 0,\n entityArchetype: new Uint32Array(resolved.initialCapacity),\n entityMask: new Uint32Array(resolved.initialCapacity * resolved.maskWordCount),\n archetypes: [],\n archetypeByMaskHash: new Map<string, number>(),\n queryVersion: 0,\n queries: [],\n queryMasks: new Map(),\n queryArchetypeCache: [],\n queryArchetypeStamp: [],\n bitToQueries: new Map<number, Set<number>>(),\n reactiveBuffers: new Map(),\n observers: [],\n relationStorage: new Map(),\n sab: resolved.buffer,\n readOnly: false,\n }\n\n // Seed archetype 0 (the empty mask)\n const empty = createEmptyArchetype(resolved.maskWordCount, resolved.maxComponents)\n empty.id = 0\n state.archetypes.push(empty)\n state.archetypeByMaskHash.set(maskHash(empty.mask), 0)\n\n registerWorld(state)\n return makePublicWorld(state)\n}\n\nexport function makePublicWorld(state: WorldState): World {\n return {\n id: state.id,\n get capacity() {\n return state.capacity\n },\n version: state.version,\n } as World\n}\n\nexport function destroyWorld(world: World): void {\n const state = worldRegistry.get(world.id)\n if (!state || state.destroyed) return\n state.destroyed = true\n // Clear large buffers to help GC\n state.archetypes = []\n state.archetypeByMaskHash.clear()\n state.componentInfoByBit = []\n state.componentStorageByBit = []\n state.queries = []\n state.queryMasks.clear()\n state.queryArchetypeCache = []\n state.observers = []\n state.relationStorage.clear()\n state.reactiveBuffers.clear()\n unregisterWorld(world.id)\n}\n\nexport function resetWorld(world: World): void {\n const state = getWorldState(world)\n // Keep capacity and registered components; clear entities and per-entity state.\n state.size = 0\n state.nextFreshIndex = 1\n state.freeList = []\n state.generations.fill(0)\n state.entityArchetype.fill(0)\n state.entityMask.fill(0)\n // Wipe archetype memberships but keep archetype graph for stability.\n for (const arch of state.archetypes) {\n arch.size = 0\n arch.entityRow.clear()\n }\n // Clear SoA columns and AoS instances; storage allocation is preserved.\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n for (const k of Object.keys(storage.soa)) {\n storage.soa[k]?.fill(0)\n }\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.fill(undefined as unknown as never)\n }\n }\n state.queryVersion++\n for (const buf of state.reactiveBuffers.values()) {\n buf.entered.length = 0\n buf.exited.length = 0\n }\n}\n\nexport function getWorldSize(world: World): number {\n return getWorldState(world).size\n}\n\nexport function getWorldCapacity(world: World): number {\n return getWorldState(world).capacity\n}\n\n// --- Capacity growth ---\n\nexport function ensureCapacity(state: WorldState, needed: number): void {\n if (needed <= state.capacity) return\n if (needed > state.options.maxEntities) {\n throw new Error(\n `aiecsjs: requested capacity ${needed} exceeds maxEntities ${state.options.maxEntities}`,\n )\n }\n let newCap = state.capacity\n while (newCap < needed) newCap = Math.min(newCap * 2, state.options.maxEntities)\n growEntityArrays(state, newCap)\n}\n\nfunction growEntityArrays(state: WorldState, newCap: number): void {\n // generations\n const genCtor: any = state.generations.constructor\n const newGen = new genCtor(newCap) as Uint8Array | Uint16Array\n ;(newGen as Uint8Array).set(state.generations as Uint8Array)\n state.generations = newGen\n\n // entityArchetype\n const newArch = new Uint32Array(newCap)\n newArch.set(state.entityArchetype)\n state.entityArchetype = newArch\n\n // entityMask\n const wordCount = state.options.maskWordCount\n const newMask = new Uint32Array(newCap * wordCount)\n newMask.set(state.entityMask)\n state.entityMask = newMask\n\n // Component storages (SoA columns + AoS arrays)\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n const info = state.componentInfoByBit[storage.bit]\n if (info) growSoAColumns(storage.soa, info.fields, newCap)\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.length = newCap\n }\n }\n\n state.capacity = newCap\n}\n\nfunction growSoAColumns(soa: Record<string, any>, fields: FieldInfo[], newCap: number): void {\n for (const f of fields) {\n const old = soa[f.name]\n if (!old) continue\n const newLen = newCap * f.vectorLen\n if (old.length >= newLen) continue\n const next = new f.ctor(newLen)\n next.set(old)\n soa[f.name] = next\n }\n}\n\n// --- Archetype management ---\n\nexport function findOrCreateArchetype(\n state: WorldState,\n mask: Uint32Array,\n): { archId: number; created: boolean } {\n const key = maskHash(mask)\n const existing = state.archetypeByMaskHash.get(key)\n if (existing !== undefined) return { archId: existing, created: false }\n\n const id = state.archetypes.length\n const arch: ArchetypeState = {\n id,\n mask: cloneMask(mask),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: collectBits(mask),\n edgeAdd: new Int32Array(state.options.maxComponents).fill(-1),\n edgeRemove: new Int32Array(state.options.maxComponents).fill(-1),\n }\n state.archetypes.push(arch)\n state.archetypeByMaskHash.set(key, id)\n state.queryVersion++\n return { archId: id, created: true }\n}\n\nexport function ensureArchetypeCapacity(arch: ArchetypeState, needed: number): void {\n if (needed <= arch.capacity) return\n let newCap = arch.capacity\n while (newCap < needed) newCap *= 2\n const next = new Uint32Array(newCap)\n next.set(arch.entities)\n arch.entities = next\n arch.capacity = newCap\n}\n\nfunction collectBits(mask: Uint32Array): number[] {\n const bits: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (w << 5) + (31 - Math.clz32(lsb))\n bits.push(bit)\n word &= word - 1\n }\n }\n return bits\n}\n\n// --- Component registration in a world ---\n\nexport function getOrRegisterComponentBit(state: WorldState, info: ComponentInfo): number {\n const existing = state.componentBitFor.get(info.id)\n if (existing !== undefined) return existing\n\n if (state.nextComponentBit >= state.options.maxComponents) {\n throw new Error(`aiecsjs: world reached maxComponents=${state.options.maxComponents}`)\n }\n const bit = state.nextComponentBit++\n state.componentBitFor.set(info.id, bit)\n state.componentInfoByBit[bit] = info\n\n // Create storage\n let storage: WorldComponentStorage\n if (info.kind === 'soa') {\n const soa: Record<string, any> = {}\n for (const f of info.fields) {\n soa[f.name] = new f.ctor(state.capacity * f.vectorLen)\n }\n storage = { kind: 'soa', componentId: info.id, bit, soa }\n } else if (info.kind === 'aos') {\n storage = { kind: 'aos', componentId: info.id, bit, aos: new Array(state.capacity) }\n } else {\n storage = { kind: 'tag', componentId: info.id, bit }\n }\n state.componentStorageByBit[bit] = storage\n return bit\n}\n\n// Read a bitmask out of state.entityMask[] into a fresh Uint32Array.\nexport function readEntityMask(state: WorldState, eid: number): Uint32Array {\n const w = state.options.maskWordCount\n const out = new Uint32Array(w)\n const idx = eid & state.options.indexMask\n const base = idx * w\n for (let i = 0; i < w; i++) out[i] = state.entityMask[base + i] ?? 0\n return out\n}\n\nexport function writeEntityMask(state: WorldState, eid: number, mask: Uint32Array): void {\n const w = state.options.maskWordCount\n const idx = eid & state.options.indexMask\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = mask[i] ?? 0\n}\n\n// Get the bit of a component within a world without registering.\nexport function tryGetComponentBit(state: WorldState, info: ComponentInfo): number | undefined {\n return state.componentBitFor.get(info.id)\n}\n\nexport function isWorld(x: unknown): x is World {\n if (!x || typeof x !== 'object') return false\n const obj = x as { id?: unknown; version?: unknown }\n if (typeof obj.id !== 'number') return false\n if (typeof obj.version !== 'string') return false\n return worldRegistry.has(obj.id)\n}\n","import { clearBit, cloneMask, forEachSetBit, setBit, testBit } from './bitmask.js'\nimport { isAliveInternal } from './entity.js'\nimport type {\n AoSComponent,\n ComponentInfo,\n ComponentInit,\n ComponentLike,\n EntityId,\n FieldInfo,\n SoAColumns,\n SoAComponent,\n SoASchema,\n TagComponent,\n TypedArrayConstructor,\n World,\n WorldComponentStorage,\n WorldState,\n} from './types.js'\nimport {\n ensureArchetypeCapacity,\n findOrCreateArchetype,\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n writeEntityMask,\n} from './world.js'\n\n// --- Component factories ---\n\nlet nextComponentId = 1\n\nconst TYPE_CTOR: Record<string, TypedArrayConstructor> = {\n i8: Int8Array,\n u8: Uint8Array,\n i16: Int16Array,\n u16: Uint16Array,\n i32: Int32Array,\n u32: Uint32Array,\n f32: Float32Array,\n f64: Float64Array,\n eid: Uint32Array,\n bool: Uint8Array,\n}\n\nconst componentInfoById = new Map<number, ComponentInfo>()\n\nexport function defineComponent<S extends SoASchema>(schema: S): SoAComponent<S> {\n const fields: FieldInfo[] = []\n for (const [name, decl] of Object.entries(schema)) {\n let type: keyof typeof TYPE_CTOR\n let vectorLen = 1\n if (typeof decl === 'string') {\n type = decl\n } else if (Array.isArray(decl)) {\n const [t, len] = decl\n type = t\n vectorLen = len\n } else {\n throw new TypeError(`aiecsjs: invalid field declaration for \"${name}\"`)\n }\n const ctor = TYPE_CTOR[type]\n if (!ctor) throw new TypeError(`aiecsjs: unknown field type \"${type}\" for field \"${name}\"`)\n fields.push({\n name,\n type: type as any,\n vectorLen,\n ctor,\n bytesPerElement: (ctor as any).BYTES_PER_ELEMENT,\n })\n }\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'soa', schema, fields, factory: null }\n componentInfoById.set(id, info)\n const handle: SoAComponent<S> = {\n __kind: 'soa',\n __id: id,\n __schema: schema,\n }\n return handle\n}\n\nexport function defineTag(): TagComponent {\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'tag', schema: null, fields: [], factory: null }\n componentInfoById.set(id, info)\n return { __kind: 'tag', __id: id }\n}\n\nexport function defineObjectComponent<T>(factory?: () => T): AoSComponent<T> {\n const id = nextComponentId++\n const fac = factory ?? (() => ({}) as T)\n const info: ComponentInfo = { id, kind: 'aos', schema: null, fields: [], factory: fac as any }\n componentInfoById.set(id, info)\n return { __kind: 'aos', __id: id, __factory: fac }\n}\n\nexport function getComponentInfo(component: ComponentLike): ComponentInfo {\n const info = componentInfoById.get(component.__id)\n if (!info)\n throw new Error(\n 'aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)',\n )\n return info\n}\n\n// --- Component ops on entities ---\n\nexport function addComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n initial?: ComponentInit<C>,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) {\n throw new Error(`aiecsjs: addComponent on dead entity ${eid}`)\n }\n const info = getComponentInfo(component)\n const bit = getOrRegisterComponentBit(state, info)\n\n const prevMask = readEntityMask(state, eid)\n if (testBit(prevMask, bit)) {\n if (initial !== undefined) writeInitial(state, eid as number, component, initial)\n return\n }\n const newMask = cloneMask(prevMask)\n setBit(newMask, bit)\n migrateEntity(state, eid as number, newMask)\n\n writeInitial(state, eid as number, component, initial)\n\n fireAddObservers(state, eid, bit)\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function removeComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) return\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return\n const prevMask = readEntityMask(state, eid)\n if (!testBit(prevMask, bit)) return\n\n // Write the new mask BEFORE firing observers so query-targeted observers\n // reading `state.entityMask` see the post-removal state (and thus correctly\n // detect \"entity left this query\"). Without this reorder, a query that\n // requires the removed component would still match during dispatch and the\n // remove observer would never fire. Component-targeted observers receive the\n // bit directly and don't depend on mask timing. addComponent already follows\n // this \"mutate then fire\" order; keeping removeComponent consistent.\n const newMask = cloneMask(prevMask)\n clearBit(newMask, bit)\n migrateEntity(state, eid as number, newMask)\n\n fireRemoveObservers(state, eid, bit)\n\n const idx = (eid as number) & state.options.indexMask\n const storage = state.componentStorageByBit[bit]\n if (storage?.kind === 'soa' && storage.soa) {\n clearSoAEntity(storage.soa, info.fields, idx)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[idx] = undefined\n }\n\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function hasComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n): boolean {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return false\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return false\n const mask = readEntityMask(state, eid)\n return testBit(mask, bit)\n}\n\nexport function getComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n): unknown {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return undefined\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return undefined\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) return undefined\n const storage = state.componentStorageByBit[bit]\n if (!storage) return undefined\n if (storage.kind === 'soa') return storage.soa\n if (storage.kind === 'aos') {\n const idx = (eid as number) & state.options.indexMask\n return storage.aos?.[idx]\n }\n return true // tag\n}\n\nexport function setComponent<C extends ComponentLike, V>(\n world: World,\n eid: EntityId,\n component: C,\n value: V,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) throw new Error(`aiecsjs: setComponent on dead entity ${eid}`)\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) {\n // Adding via set\n addComponent(world, eid, component, value as any)\n return\n }\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) {\n addComponent(world, eid, component, value as any)\n return\n }\n writeInitial(state, eid as number, component, value as any)\n fireSetObservers(state, eid, bit, value)\n}\n\n// --- Internals ---\n\nfunction writeInitial(\n state: WorldState,\n packedEid: number,\n component: ComponentLike,\n initial: unknown,\n): void {\n const info = getComponentInfo(component)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) return\n const storage = state.componentStorageByBit[bit]\n if (!storage) return\n // Unpack to raw index for storage access\n const idx = packedEid & state.options.indexMask\n if (info.kind === 'soa' && storage.soa) {\n if (initial == null) return\n const obj = initial as Record<string, unknown>\n for (const f of info.fields) {\n if (!(f.name in obj)) continue\n const col = storage.soa[f.name]\n if (!col) continue\n const val = obj[f.name]\n if (f.vectorLen === 1) {\n col[idx] = typeof val === 'boolean' ? (val ? 1 : 0) : Number(val)\n } else if (Array.isArray(val) || ArrayBuffer.isView(val)) {\n const base = idx * f.vectorLen\n const arr = val as ArrayLike<number>\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = Number(arr[i] ?? 0)\n }\n }\n } else if (info.kind === 'aos' && storage.aos) {\n const factory = info.factory ?? (() => ({}))\n let inst = storage.aos[idx]\n if (inst === undefined) {\n inst = factory()\n storage.aos[idx] = inst\n }\n if (initial && typeof initial === 'object') {\n // SECURITY: do NOT use `Object.assign(inst, initial)` here. When `initial`\n // comes from `JSON.parse(untrustedBytes)` — e.g. via `fromJSON`,\n // `deserializeWorld`, or app code piping a bridge payload — the parsed\n // object can carry an OWN `__proto__` property, and `Object.assign` uses\n // [[Set]] semantics which would trigger the proto setter and clobber the\n // instance's prototype chain. Explicit own-key copy with a deny-list\n // closes the prototype-pollution path.\n const src = initial as Record<string, unknown>\n const target = inst as Record<string, unknown>\n for (const key of Object.keys(src)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue\n target[key] = src[key]\n }\n }\n }\n // tag: nothing\n}\n\nfunction clearSoAEntity(soa: SoAColumns, fields: FieldInfo[], eid: number): void {\n for (const f of fields) {\n const col = soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n col[eid] = 0\n } else {\n const base = eid * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = 0\n }\n }\n}\n\n// Clear every component-storage slot that the entity currently owns.\n// Walks the entity's mask; for each set bit, zeroes the SoA columns or\n// undefines the AoS slot at the entity index. Tag storages are bit-only.\n// Caller (e.g. destroyEntity) is expected to clear the mask separately.\nexport function clearAllEntityStorages(state: WorldState, eid: EntityId): void {\n const wordCount = state.options.maskWordCount\n const idx = (eid as number) & state.options.indexMask\n const base = idx * wordCount\n forEachSetBit(state.entityMask, base, wordCount, (bit) => {\n const storage = state.componentStorageByBit[bit]\n const info = state.componentInfoByBit[bit]\n if (storage?.kind === 'soa' && storage.soa && info) {\n clearSoAEntity(storage.soa, info.fields, idx)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[idx] = undefined\n }\n })\n}\n\nfunction migrateEntity(state: WorldState, packedEid: number, newMask: Uint32Array): void {\n // Unpack to raw index for sparse-array lookups\n const idx = packedEid & state.options.indexMask\n const srcArchId = state.entityArchetype[idx] ?? 0\n const srcArch = state.archetypes[srcArchId]\n if (!srcArch) return\n\n const found = findOrCreateArchetype(state, newMask)\n const destArchId = found.archId\n const destArch = state.archetypes[destArchId]\n if (!destArch) return\n\n if (destArchId !== srcArchId) {\n // Swap-pop from src (arch.entities / entityRow use packed eid as key)\n const row = srcArch.entityRow.get(packedEid)\n if (row !== undefined) {\n const lastRow = srcArch.size - 1\n if (row !== lastRow) {\n const moved = srcArch.entities[lastRow] ?? 0\n srcArch.entities[row] = moved\n srcArch.entityRow.set(moved, row)\n }\n srcArch.entities[lastRow] = 0\n srcArch.entityRow.delete(packedEid)\n srcArch.size--\n }\n\n // Append to dest (store packed eid)\n ensureArchetypeCapacity(destArch, destArch.size + 1)\n const newRow = destArch.size\n destArch.entities[newRow] = packedEid\n destArch.entityRow.set(packedEid, newRow)\n destArch.size++\n\n state.entityArchetype[idx] = destArchId\n }\n\n writeEntityMask(state, packedEid, newMask)\n}\n\n// --- Observer dispatch (lazy-bound) ---\n\ninterface ObserversDispatchAPI {\n fireAdd(state: WorldState, eid: EntityId, bit: number): void\n fireRemove(state: WorldState, eid: EntityId, bit: number): void\n fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void\n}\nlet _dispatch: ObserversDispatchAPI = {\n fireAdd: () => {},\n fireRemove: () => {},\n fireSet: () => {},\n}\n\ntype MaskChangeFn = (\n state: WorldState,\n eid: EntityId,\n bit: number,\n prev: Uint32Array,\n next: Uint32Array,\n) => void\nlet _maskChange: MaskChangeFn = () => {}\nexport function registerMaskChangeDispatch(fn: MaskChangeFn): void {\n _maskChange = fn\n}\nfunction notifyMaskChange(\n state: WorldState,\n eid: number,\n bit: number,\n prev: Uint32Array,\n next: Uint32Array,\n): void {\n _maskChange(state, eid as EntityId, bit, prev, next)\n}\nexport function registerObserverDispatch(api: ObserversDispatchAPI): void {\n _dispatch = api\n}\nfunction fireAddObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireAdd(state, eid as EntityId, bit)\n}\nfunction fireRemoveObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireRemove(state, eid as EntityId, bit)\n}\nfunction fireSetObservers(state: WorldState, eid: number, bit: number, value: unknown): void {\n _dispatch.fireSet(state, eid as EntityId, bit, value)\n}\n\n// --- Helper for serialize/worker ---\n\nexport function getComponentByInternalId(id: number): ComponentInfo | undefined {\n return componentInfoById.get(id)\n}\n\nexport function listAllComponents(): ComponentInfo[] {\n return Array.from(componentInfoById.values())\n}\n\nexport function _resetComponentRegistry_FOR_TESTS_ONLY(): void {\n componentInfoById.clear()\n nextComponentId = 1\n}\n","import { clearAllEntityStorages } from './component.js'\nimport type { EntityId, ResolvedWorldOptions, World, WorldState } from './types.js'\nimport { ensureArchetypeCapacity, ensureCapacity, getWorldState } from './world.js'\n\n// --- Default bit layout constants (used by public getEntityIndex / getEntityGeneration / packEntity) ---\n// These use the default 24/8 split. See §4.4 limitation: callers using non-default\n// createWorld({ indexBits, generationBits }) should not rely on these functions for unpacking.\nexport const DEFAULT_INDEX_BITS = 24\nexport const DEFAULT_GENERATION_BITS = 8\nexport const DEFAULT_INDEX_MASK = (1 << DEFAULT_INDEX_BITS) - 1\nexport const DEFAULT_GENERATION_MASK = (1 << DEFAULT_GENERATION_BITS) - 1\n\n// --- Internal pack/unpack helpers (world-options-aware) ---\n\nexport function packEid(idx: number, gen: number, opts: ResolvedWorldOptions): EntityId {\n // `>>> 0` normalises to unsigned: for generation ≥ 128 (default 8-bit gen) the\n // signed `<<`/`|` would yield a negative number that diverges from the unsigned\n // value stored in `arch.entities` (Uint32Array), breaking entityRow lookups for\n // query-iterated high-generation entities. Keep EntityId a non-negative int32.\n return ((((gen & opts.generationMask) << opts.indexBits) | (idx & opts.indexMask)) >>>\n 0) as EntityId\n}\n\nexport function unpackIdx(eid: number, opts: ResolvedWorldOptions): number {\n return eid & opts.indexMask\n}\n\nexport function unpackGen(eid: number, opts: ResolvedWorldOptions): number {\n return (eid >>> opts.indexBits) & opts.generationMask\n}\n\nexport function createEntity(world: World): EntityId {\n const state = getWorldState(world)\n if (state.readOnly) {\n throw new Error('aiecsjs: cannot createEntity on a read-only world (worker-attached)')\n }\n\n let idx: number\n if (state.freeList.length > 0) {\n idx = state.freeList.pop()!\n } else {\n if (state.nextFreshIndex >= state.options.maxEntities) {\n throw new Error(`aiecsjs: reached maxEntities ${state.options.maxEntities}`)\n }\n if (state.nextFreshIndex >= state.capacity) {\n ensureCapacity(state, state.nextFreshIndex + 1)\n }\n idx = state.nextFreshIndex++\n }\n\n const gen = state.generations[idx] ?? 0\n const eid = packEid(idx, gen, state.options)\n\n // Move into the empty archetype (0)\n const arch = state.archetypes[0]\n if (!arch) throw new Error('aiecsjs: missing empty archetype')\n ensureArchetypeCapacity(arch, arch.size + 1)\n const row = arch.size\n arch.entities[row] = eid\n arch.entityRow.set(eid, row)\n arch.size++\n\n state.entityArchetype[idx] = 0\n // Reset entityMask row for this idx\n const w = state.options.maskWordCount\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n\n state.size++\n return eid\n}\n\nexport function destroyEntity(world: World, eid: EntityId): void {\n const state = getWorldState(world)\n if (state.readOnly) {\n throw new Error('aiecsjs: cannot destroyEntity on a read-only world')\n }\n if (!isAliveInternal(state, eid)) return\n\n const idx = eid & state.options.indexMask\n\n // Fire onRemove for every component the entity has, plus reactive exit\n // (Late-bound to avoid circular imports — done via observers module.)\n const { dispatchDestroyObservers } = lazyObservers()\n dispatchDestroyObservers(state, eid)\n\n // Clean up relations referring to this entity\n cleanupRelationsOnDestroy(state, eid)\n\n // Zero the SoA columns / undefine the AoS slots the entity owned, before\n // the mask is cleared. Without this, destroyed entities leave stale data\n // visible to snapshots and serialisation.\n clearAllEntityStorages(state, eid)\n\n // Swap-pop from its archetype\n const archId = state.entityArchetype[idx] ?? 0\n const arch = state.archetypes[archId]\n if (arch) {\n const row = arch.entityRow.get(eid)\n if (row !== undefined) {\n const lastRow = arch.size - 1\n if (row !== lastRow) {\n const moved = arch.entities[lastRow] ?? 0\n arch.entities[row] = moved\n arch.entityRow.set(moved, row)\n }\n arch.entities[lastRow] = 0\n arch.entityRow.delete(eid)\n arch.size--\n }\n }\n\n // Wipe state\n state.entityArchetype[idx] = 0\n const w = state.options.maskWordCount\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n // Bump generation — use generationMask so non-default generationBits wraps correctly\n state.generations[idx] = ((state.generations[idx] ?? 0) + 1) & state.options.generationMask\n\n // freeList stores raw idx (not packed); createEntity packs on re-use\n state.freeList.push(idx)\n state.size--\n}\n\nexport function entityExists(world: World, eid: EntityId): boolean {\n const state = getWorldState(world)\n return isAliveInternal(state, eid)\n}\n\nexport function isAliveInternal(state: WorldState, eid: number): boolean {\n const idx = eid & state.options.indexMask\n if (idx <= 0) return false\n if (idx >= state.capacity) return false\n const archId = state.entityArchetype[idx] ?? 0\n const arch = state.archetypes[archId]\n if (!arch) return false\n if (!arch.entityRow.has(eid)) return false\n // Generation comparison: packed eid must match stored generation\n const storedGen = state.generations[idx] ?? 0\n const refGen = (eid >>> state.options.indexBits) & state.options.generationMask\n return storedGen === refGen\n}\n\n/**\n * Extract the index portion of a packed entity ID.\n *\n * Uses the default 24-bit index layout. If you created the world with a\n * non-default `indexBits`, use `EntityRef` + `deref` instead.\n */\nexport function getEntityIndex(eid: EntityId): number {\n return (eid as number) & DEFAULT_INDEX_MASK\n}\n\n/**\n * Extract the generation portion of a packed entity ID.\n *\n * Uses the default 8-bit generation layout. If you created the world with a\n * non-default `generationBits`, use `EntityRef` + `deref` instead.\n */\nexport function getEntityGeneration(eid: EntityId): number {\n return ((eid as number) >>> DEFAULT_INDEX_BITS) & DEFAULT_GENERATION_MASK\n}\n\n/**\n * Pack an index and generation into an EntityId using the default 24/8 bit layout.\n *\n * Uses the default `indexBits=24, generationBits=8`. If you created the world\n * with non-default bit sizes, this will produce values with incorrect layout.\n * Use `EntityRef` and `deref` for portable cross-world identity matching.\n */\nexport function packEntity(index: number, generation: number): EntityId {\n // `>>> 0` normalises to unsigned — see packEid. Keeps EntityId a non-negative int32.\n return ((((generation & DEFAULT_GENERATION_MASK) << DEFAULT_INDEX_BITS) |\n (index & DEFAULT_INDEX_MASK)) >>>\n 0) as EntityId\n}\n\nexport function isEntity(world: World, x: unknown): x is EntityId {\n if (typeof x !== 'number') return false\n return entityExists(world, x as EntityId)\n}\n\n// --- Lazy loaders to break import cycles ---\n\ninterface ObserversAPI {\n dispatchDestroyObservers(state: WorldState, eid: EntityId): void\n}\nlet _observersAPI: ObserversAPI | null = null\nexport function registerObserversAPI(api: ObserversAPI): void {\n _observersAPI = api\n}\nfunction lazyObservers(): ObserversAPI {\n if (!_observersAPI) {\n return { dispatchDestroyObservers: () => {} }\n }\n return _observersAPI\n}\n\nlet _relationsCleanup: ((state: WorldState, eid: EntityId) => void) | null = null\nexport function registerRelationsCleanup(fn: (state: WorldState, eid: EntityId) => void): void {\n _relationsCleanup = fn\n}\nfunction cleanupRelationsOnDestroy(state: WorldState, eid: EntityId): void {\n if (_relationsCleanup) _relationsCleanup(state, eid)\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunk4RPFOVQC_cjs=require('./chunk-4RPFOVQC.cjs');var d="AIEC",B=1;function P(n,o){let e=D(n);return o?.components&&(e.entities=e.entities.map(t=>({eid:t.eid,components:t.components.filter(i=>o.components.some(c=>c.__id===i.id))}))),x(e)}function Q(n,o){let e=N(n,o);return J(e)}function D(n){let o=chunk4RPFOVQC_cjs.i(n),e=[];for(let t=1;t<o.capacity;t++){let i=o.entityArchetype[t]??0;if(i===0)continue;let c=o.archetypes[i];if(!c)continue;let r=o.generations[t]??0,a=chunk4RPFOVQC_cjs.r(t,r,o.options);if(!c.entityRow.has(a))continue;let s=o.options.maskWordCount,l=t*s,p=[];for(let m=0;m<s;m++){let u=o.entityMask[l+m]??0;for(;u!==0;){let b=u&-u,_=(m<<5)+(31-Math.clz32(b)),f=o.componentInfoByBit[_];if(f){let S=o.componentStorageByBit[_],w=null;if(f.kind==="soa"&&S?.soa){let y={};for(let h of f.fields){let g=S.soa[h.name];if(g)if(h.vectorLen===1)y[h.name]=g[t];else {let L=[],M=t*h.vectorLen;for(let C=0;C<h.vectorLen;C++)L.push(g[M+C]??0);y[h.name]=L;}}w=y;}else f.kind==="aos"&&S?.aos?w=S.aos[t]??null:w=true;p.push({kind:f.kind,id:f.id,data:w});}u&=u-1;}}e.push({eid:t,components:p});}return {version:o.version,capacity:o.capacity,entities:e}}function J(n){let o=chunk4RPFOVQC_cjs.k({initialCapacity:n.capacity}),e=new Map;for(let t of n.entities){let i=chunk4RPFOVQC_cjs.u(o);e.set(t.eid,i);}for(let t of n.entities){let i=e.get(t.eid);for(let c of t.components){let r=chunk4RPFOVQC_cjs.P(c.id);if(!r)continue;let a=A(r);a&&chunk4RPFOVQC_cjs.I(o,i,a,c.data);}}return o}function A(n){if(n.kind==="soa")return {__kind:"soa",__id:n.id,__schema:n.schema??{}};if(n.kind==="aos"){let o=n.factory??(()=>({}));return {__kind:"aos",__id:n.id,__factory:o}}return {__kind:"tag",__id:n.id}}function x(n){let o=JSON.stringify(n),e=new TextEncoder().encode(o),t=new TextEncoder().encode(chunk4RPFOVQC_cjs.a),c=12+t.length+4+e.length,r=new Uint8Array(c),a=new DataView(r.buffer),s=0;return r[s++]=d.charCodeAt(0),r[s++]=d.charCodeAt(1),r[s++]=d.charCodeAt(2),r[s++]=d.charCodeAt(3),a.setUint32(s,B,true),s+=4,a.setUint32(s,t.length,true),s+=4,r.set(t,s),s+=t.length,a.setUint32(s,e.length,true),s+=4,r.set(e,s),r}function N(n,o){if(n.length<12)throw new Error("aiecsjs: bytes too short to be a valid snapshot");let e=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n[0]!==d.charCodeAt(0)||n[1]!==d.charCodeAt(1)||n[2]!==d.charCodeAt(2)||n[3]!==d.charCodeAt(3))throw new Error("aiecsjs: invalid magic bytes");let t=4,i=e.getUint32(t,true);t+=4;let c=o?.onUnknownVersion??"throw";if(i!==B&&c==="throw")throw new Error(`aiecsjs: format version ${i} not supported`);let r=64*1024*1024;if(t+4>n.length)throw new Error("aiecsjs: snapshot truncated before verLen");let a=e.getUint32(t,true);if(t+=4,a>r||t+a>n.length)throw new Error(`aiecsjs: snapshot verLen=${a} out of bounds`);if(t+=a,t+4>n.length)throw new Error("aiecsjs: snapshot truncated before jsonLen");let s=e.getUint32(t,true);if(t+=4,s>r||t+s>n.length)throw new Error(`aiecsjs: snapshot jsonLen=${s} out of bounds`);let l=n.subarray(t,t+s),p=new TextDecoder().decode(l);return JSON.parse(p)}function Y(n,o){let e={world:n,components:o?.components??chunk4RPFOVQC_cjs.Q().map(t=>A(t)).filter(Boolean),lastSnapshot:null};return {capture(){let t=D(e.world),i;return e.lastSnapshot?i=V(e.lastSnapshot,t):i=t,e.lastSnapshot=t,x(i)},apply(t,i){let c=N(i),r=chunk4RPFOVQC_cjs.i(t);for(let a of c.entities)if(!(a.eid>=r.capacity)){if(!chunk4RPFOVQC_cjs.w(t,a.eid))for(;r.size<a.eid;)chunk4RPFOVQC_cjs.u(t);for(let s of a.components){let l=chunk4RPFOVQC_cjs.P(s.id);if(!l)continue;let p=A(l);p&&chunk4RPFOVQC_cjs.I(t,a.eid,p,s.data);}}},reset(){e.lastSnapshot=null;}}}function V(n,o){let e=new Map(n.entities.map(i=>[i.eid,i])),t=[];for(let i of o.entities){let c=e.get(i.eid);if(!c){t.push(i);continue}let r=JSON.stringify(c.components),a=JSON.stringify(i.components);r!==a&&t.push(i);}return {version:o.version,capacity:o.capacity,entities:t}}exports.a=P;exports.b=Q;exports.c=D;exports.d=J;exports.e=Y;//# sourceMappingURL=chunk-AGHSWLNQ.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-AGHSWLNQ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/serialize.ts"],"names":["MAGIC","FORMAT_VERSION","serializeWorld","world","options","snapshot","toJSON","e","c","comp","packBinary","deserializeWorld","bytes","unpackBinary","fromJSON","state","getWorldState","entities","idx","archId","arch","gen","packedEid","packEid","w","base","components","wi","word","lsb","bit","info","storage","data","obj","f","col","arr","baseI","i","createWorld","eidMap","eid","createEntity","getComponentByInternalId","handle","getComponentHandle","addComponent","factory","json","jsonBytes","versionBytes","VERSION","total","out","view","off","formatVersion","onUnknown","MAX_FIELD_LEN","verLen","jsonLen","createDeltaSerializer","listAllComponents","current","delta","computeDelta","targetWorld","deltaBytes","targetState","entityExists","prev","curr","prevByEid","changed","prevE","prevSig","currSig"],"mappings":"mEA0BA,IAAMA,CAAAA,CAAQ,MAAA,CACRC,CAAAA,CAAiB,CAAA,CAEhB,SAASC,EAAeC,CAAAA,CAAcC,CAAAA,CAAwC,CACnF,IAAMC,CAAAA,CAAWC,CAAAA,CAAOH,CAAK,CAAA,CAC7B,OAAIC,CAAAA,EAAS,UAAA,GACXC,CAAAA,CAAS,QAAA,CAAWA,CAAAA,CAAS,QAAA,CAAS,GAAA,CAAKE,CAAAA,GAAO,CAChD,GAAA,CAAKA,CAAAA,CAAE,GAAA,CACP,WAAYA,CAAAA,CAAE,UAAA,CAAW,MAAA,CAAQC,CAAAA,EAC/BJ,CAAAA,CAAQ,UAAA,CAAY,IAAA,CAAMK,CAAAA,EAASA,CAAAA,CAAK,IAAA,GAASD,CAAAA,CAAE,EAAE,CACvD,CACF,EAAE,CAAA,CAAA,CAEGE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sourcesContent":["// aiecsjs/serialize — binary, JSON, and delta serializers.\n\nimport { testBit } from './internal/bitmask.js'\nimport {\n addComponent,\n defineComponent,\n defineObjectComponent,\n defineTag,\n getComponentByInternalId,\n getComponentInfo,\n listAllComponents,\n} from './internal/component.js'\nimport { createEntity, destroyEntity, entityExists, packEid } from './internal/entity.js'\nimport type {\n ComponentInfo,\n ComponentLike,\n DeltaSerializer,\n DeserializeOptions,\n EntityId,\n SerializeOptions,\n World,\n WorldSnapshot,\n} from './internal/types.js'\nimport { createWorld, getWorldState } from './internal/world.js'\nimport { VERSION } from './version.js'\n\nconst MAGIC = 'AIEC'\nconst FORMAT_VERSION = 1\n\nexport function serializeWorld(world: World, options?: SerializeOptions): Uint8Array {\n const snapshot = toJSON(world)\n if (options?.components) {\n snapshot.entities = snapshot.entities.map((e) => ({\n eid: e.eid,\n components: e.components.filter((c) =>\n options.components!.some((comp) => comp.__id === c.id),\n ),\n }))\n }\n return packBinary(snapshot)\n}\n\nexport function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World {\n const snapshot = unpackBinary(bytes, options)\n return fromJSON(snapshot)\n}\n\n/**\n * Serialize a world snapshot to a plain JSON-compatible object.\n *\n * Note: `EntityRef` is in-memory only — not preserved across serialize/deserialize.\n * Generation counters reset on world load. Stale refs from before serialization\n * will deref to null after loading the snapshot into a new world.\n */\nexport function toJSON(world: World): WorldSnapshot {\n const state = getWorldState(world)\n const entities: WorldSnapshot['entities'] = []\n // Iterate by raw slot index; snapshot stores raw idx in the `eid` field\n // (wire format unchanged — idx is used for load-side entity re-creation).\n for (let idx = 1; idx < state.capacity; idx++) {\n const archId = state.entityArchetype[idx] ?? 0\n if (archId === 0) continue // slot unused\n\n const arch = state.archetypes[archId]\n if (!arch) continue\n\n // Build the packed eid from idx + current generation to do alive check\n const gen = state.generations[idx] ?? 0\n const packedEid = packEid(idx, gen, state.options)\n if (!arch.entityRow.has(packedEid)) continue\n\n const w = state.options.maskWordCount\n const base = idx * w\n const components: WorldSnapshot['entities'][0]['components'] = []\n for (let wi = 0; wi < w; wi++) {\n let word = state.entityMask[base + wi] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (wi << 5) + (31 - Math.clz32(lsb))\n const info = state.componentInfoByBit[bit]\n if (info) {\n const storage = state.componentStorageByBit[bit]\n let data: unknown = null\n if (info.kind === 'soa' && storage?.soa) {\n const obj: Record<string, unknown> = {}\n for (const f of info.fields) {\n const col = storage.soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n obj[f.name] = col[idx]\n } else {\n const arr: number[] = []\n const baseI = idx * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) arr.push(col[baseI + i] ?? 0)\n obj[f.name] = arr\n }\n }\n data = obj\n } else if (info.kind === 'aos' && storage?.aos) {\n data = storage.aos[idx] ?? null\n } else {\n data = true\n }\n components.push({ kind: info.kind, id: info.id, data })\n }\n word &= word - 1\n }\n }\n // Wire format stores raw idx (not packed) for cross-session portability\n entities.push({ eid: idx, components })\n }\n return {\n version: state.version,\n capacity: state.capacity,\n entities,\n }\n}\n\nexport function fromJSON(snapshot: WorldSnapshot): World {\n const world = createWorld({ initialCapacity: snapshot.capacity })\n const eidMap = new Map<number, EntityId>()\n for (const e of snapshot.entities) {\n const eid = createEntity(world)\n eidMap.set(e.eid, eid)\n }\n for (const e of snapshot.entities) {\n const eid = eidMap.get(e.eid)!\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) {\n // Component missing — silently skip; future version may throw based on options\n continue\n }\n const handle = getComponentHandle(info)\n if (handle) {\n addComponent(world, eid, handle, comp.data as any)\n }\n }\n }\n return world\n}\n\n// Reconstruct a component handle from its ComponentInfo. Since defineComponent\n// returns plain handles { __kind, __id, __schema }, we can synthesize them.\nfunction getComponentHandle(info: ComponentInfo): ComponentLike | null {\n if (info.kind === 'soa') {\n return { __kind: 'soa', __id: info.id, __schema: info.schema ?? {} } as ComponentLike\n }\n if (info.kind === 'aos') {\n const factory = info.factory ?? (() => ({}))\n return { __kind: 'aos', __id: info.id, __factory: factory } as ComponentLike\n }\n return { __kind: 'tag', __id: info.id } as ComponentLike\n}\n\n// --- Binary packing (wrapped JSON for 0.1) ---\n\nfunction packBinary(snapshot: WorldSnapshot): Uint8Array {\n const json = JSON.stringify(snapshot)\n const jsonBytes = new TextEncoder().encode(json)\n const versionBytes = new TextEncoder().encode(VERSION)\n const headerSize = 4 + 4 + 4 + versionBytes.length + 4\n const total = headerSize + jsonBytes.length\n const out = new Uint8Array(total)\n const view = new DataView(out.buffer)\n let off = 0\n out[off++] = MAGIC.charCodeAt(0)\n out[off++] = MAGIC.charCodeAt(1)\n out[off++] = MAGIC.charCodeAt(2)\n out[off++] = MAGIC.charCodeAt(3)\n view.setUint32(off, FORMAT_VERSION, true)\n off += 4\n view.setUint32(off, versionBytes.length, true)\n off += 4\n out.set(versionBytes, off)\n off += versionBytes.length\n view.setUint32(off, jsonBytes.length, true)\n off += 4\n out.set(jsonBytes, off)\n return out\n}\n\nfunction unpackBinary(bytes: Uint8Array, options?: DeserializeOptions): WorldSnapshot {\n if (bytes.length < 12) throw new Error('aiecsjs: bytes too short to be a valid snapshot')\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n if (\n bytes[0] !== MAGIC.charCodeAt(0) ||\n bytes[1] !== MAGIC.charCodeAt(1) ||\n bytes[2] !== MAGIC.charCodeAt(2) ||\n bytes[3] !== MAGIC.charCodeAt(3)\n ) {\n throw new Error('aiecsjs: invalid magic bytes')\n }\n let off = 4\n const formatVersion = view.getUint32(off, true)\n off += 4\n const onUnknown = options?.onUnknownVersion ?? 'throw'\n if (formatVersion !== FORMAT_VERSION && onUnknown === 'throw') {\n throw new Error(`aiecsjs: format version ${formatVersion} not supported`)\n }\n\n // SECURITY: explicit bounds checks on every length field. DataView itself\n // throws on out-of-range reads, but an attacker who controls the bytes can\n // still craft a `verLen` that skips past data of their choosing — we make\n // each step's invariant explicit and impose a sane cap to short-circuit\n // pathological payloads early.\n const MAX_FIELD_LEN = 64 * 1024 * 1024 // 64 MiB\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before verLen')\n }\n const verLen = view.getUint32(off, true)\n off += 4\n if (verLen > MAX_FIELD_LEN || off + verLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot verLen=${verLen} out of bounds`)\n }\n off += verLen // skip the aiecsjs version string\n\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before jsonLen')\n }\n const jsonLen = view.getUint32(off, true)\n off += 4\n if (jsonLen > MAX_FIELD_LEN || off + jsonLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot jsonLen=${jsonLen} out of bounds`)\n }\n const jsonBytes = bytes.subarray(off, off + jsonLen)\n const json = new TextDecoder().decode(jsonBytes)\n return JSON.parse(json) as WorldSnapshot\n}\n\n// --- Delta serializer ---\n\ninterface DeltaState {\n world: World\n components: ComponentLike[]\n lastSnapshot: WorldSnapshot | null\n}\n\nexport function createDeltaSerializer(world: World, options?: SerializeOptions): DeltaSerializer {\n const state: DeltaState = {\n world,\n components:\n options?.components ??\n listAllComponents()\n .map((i) => getComponentHandle(i)!)\n .filter(Boolean),\n lastSnapshot: null,\n }\n return {\n capture(): Uint8Array {\n const current = toJSON(state.world)\n let delta: WorldSnapshot\n if (!state.lastSnapshot) {\n delta = current\n } else {\n // Compute simple delta: entities with changed components\n delta = computeDelta(state.lastSnapshot, current)\n }\n state.lastSnapshot = current\n return packBinary(delta)\n },\n apply(targetWorld: World, deltaBytes: Uint8Array): void {\n const snapshot = unpackBinary(deltaBytes)\n // Apply: ensure entities exist, then add/update their components\n const targetState = getWorldState(targetWorld)\n for (const e of snapshot.entities) {\n if (e.eid >= targetState.capacity) continue\n if (!entityExists(targetWorld, e.eid as EntityId)) {\n // Create the entity. For simplicity, we just spawn until we have enough.\n while (targetState.size < e.eid) {\n createEntity(targetWorld)\n }\n }\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) continue\n const handle = getComponentHandle(info)\n if (handle) addComponent(targetWorld, e.eid as EntityId, handle, comp.data as any)\n }\n }\n },\n reset(): void {\n state.lastSnapshot = null\n },\n }\n}\n\nfunction computeDelta(prev: WorldSnapshot, curr: WorldSnapshot): WorldSnapshot {\n const prevByEid = new Map(prev.entities.map((e) => [e.eid, e]))\n const changed: WorldSnapshot['entities'] = []\n for (const e of curr.entities) {\n const prevE = prevByEid.get(e.eid)\n if (!prevE) {\n changed.push(e)\n continue\n }\n const prevSig = JSON.stringify(prevE.components)\n const currSig = JSON.stringify(e.components)\n if (prevSig !== currSig) changed.push(e)\n }\n return { version: curr.version, capacity: curr.capacity, entities: changed }\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {i,H as H$1,e,b as b$1,p as p$1,c,d,f as f$1}from'./chunk-L5CMKMIP.js';var C=1,f=new Map;function _(n){let e=(n.all??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),t=(n.any??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),i=(n.none??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-");return `A${e}|Y${t}|N${i}`}function q(n){let e=Array.isArray(n)?{all:n}:n;for(let o of [...e.all??[],...e.any??[],...e.none??[]])if(!o||typeof o!="object"||typeof o.__id!="number")throw new TypeError("aiecsjs: defineQuery received a non-component value");let t=_(e),i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:(e.all??[]).map(o=>o.__id),any:(e.any??[]).map(o=>o.__id),none:(e.none??[]).map(o=>o.__id),columnViewCache:[...e.all??[],...e.any??[]],reactiveKind:"normal",sourceQueryId:-1,sourceQuery:null};return f.set(t,r),r}function z(n){let e=n,t=`enter:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"enter",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function T(n){let e=n,t=`exit:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"exit",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function p(n,e){if(n.queries[e.id]===e&&n.queryMasks.has(e.id))return;let t=n.options.maskWordCount,i=b$1(t),r=b$1(t),o=b$1(t);for(let a of e.all){let u=b(a),d=p$1(n,u);c(i,d);}for(let a of e.any){let u=b(a),d=p$1(n,u);c(r,d);}for(let a of e.none){let u=b(a),d=p$1(n,u);c(o,d);}let c$1={withMask:i,anyMask:r,noneMask:o,anyHasBits:!d(r)};n.queryMasks.set(e.id,c$1),n.queries[e.id]=e,n.queryArchetypeCache[e.id]=null,n.queryArchetypeStamp[e.id]=-1;let s=[...f$1(i),...f$1(r),...f$1(o)];for(let a of s){let u=n.bitToQueries.get(a);u||(u=new Set,n.bitToQueries.set(a,u)),u.add(e.id);}e.reactiveKind!=="normal"&&(n.reactiveBuffers.has(e.id)||n.reactiveBuffers.set(e.id,{entered:[],exited:[]}),e.sourceQuery&&p(n,e.sourceQuery));}function v(n,e$1){if(p(n,e$1),n.queryArchetypeCache[e$1.id]&&n.queryArchetypeStamp[e$1.id]===n.queryVersion)return n.queryArchetypeCache[e$1.id];let t=n.queryMasks.get(e$1.id),i=n.options.maskWordCount,r=[];for(let o=0;o<n.archetypes.length;o++){let c=n.archetypes[o];e(c.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,i)&&r.push(o);}return n.queryArchetypeCache[e$1.id]=r,n.queryArchetypeStamp[e$1.id]=n.queryVersion,r}function $(n,e){let t=i(n),r=v(t,e),o=[];for(let c of r){let s=t.archetypes[c];o.push({id:s.id,mask:Array.from(s.mask),size:s.size});}return o}function D(n,e){let t=i(n),i$1=e,r=[];if(i$1.reactiveKind==="enter"){let c=t.reactiveBuffers.get(i$1.id);if(c){for(let s of c.entered)r.push(s);c.entered.length=0;}return r}if(i$1.reactiveKind==="exit"){let c=t.reactiveBuffers.get(i$1.id);if(c){for(let s of c.exited)r.push(s);c.exited.length=0;}return r}let o=v(t,i$1);for(let c of o){let s=t.archetypes[c];for(let a=0;a<s.size;a++)r.push(s.entities[a]);}return r}function*H(n,e){let t=i(n),i$1=e;if(i$1.reactiveKind!=="normal"){let o=t.reactiveBuffers.get(i$1.id);if(!o)return;let c=i$1.reactiveKind==="enter"?o.entered:o.exited;for(let s of c)yield s;c.length=0;return}let r=v(t,i$1);for(let o of r){let c=t.archetypes[o];for(let s=0;s<c.size;s++)yield c.entities[s];}}function L(n,e,t){let i$1=i(n),r=e;if(r.reactiveKind!=="normal"){let s=i$1.reactiveBuffers.get(r.id);if(!s)return;let a=r.reactiveKind==="enter"?s.entered:s.exited;if(a.length===0)return;let u=w(i$1,r);for(let d=0;d<a.length;d++){let y=a[d];x(t,y,u);}a.length=0;return}p(i$1,r);let o=v(i$1,r),c=w(i$1,r);for(let s of o){let a=i$1.archetypes[s],u=a.entities,d=a.size;for(let y=0;y<d;y++)x(t,u[y],c);}}function x(n,e,t){switch(t.length){case 0:n(e);break;case 1:n(e,t[0]);break;case 2:n(e,t[0],t[1]);break;case 3:n(e,t[0],t[1],t[2]);break;case 4:n(e,t[0],t[1],t[2],t[3]);break;case 5:n(e,t[0],t[1],t[2],t[3],t[4]);break;default:n(e,...t);}}function w(n,e){let t=[];for(let i of e.columnViewCache){let r=H$1(i),o=n.componentBitFor.get(r.id);if(o===void 0){t.push(void 0);continue}let c=n.componentStorageByBit[o];if(!c){t.push(void 0);continue}c.kind==="soa"?t.push(c.soa):c.kind==="aos"?t.push(c.aos):t.push(true);}return t}function F(n,e$1,t,i,r){for(let s of f.values())s.reactiveKind!=="normal"&&s.sourceQuery&&n.queries[s.sourceQuery.id]!==s.sourceQuery&&p(n,s.sourceQuery);let o=n.bitToQueries.get(t);if(!o)return;let c=n.options.maskWordCount;for(let s of o){let a=n.queries[s];if(!a||a.reactiveKind!=="normal")continue;let u=n.queryMasks.get(s);if(!u)continue;let d=e(i,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c),y=e(r,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c);!d&&y?E(n,s,"enter",e$1):d&&!y&&E(n,s,"exit",e$1);}}function E(n,e,t,i){for(let r of f.values()){if(r.sourceQueryId!==e||r.reactiveKind!==t)continue;p(n,r);let o=A(n,r.id);t==="enter"?o.entered.push(i):o.exited.push(i);}}function A(n,e){let t=n.reactiveBuffers.get(e);return t||(t={entered:[],exited:[]},n.reactiveBuffers.set(e,t)),t}function b(n){let e=W(n);if(!e)throw new Error(`aiecsjs: component id ${n} not registered`);return e}var g=null;function O(n){g=n;}function W(n){return g?g(n):void 0}export{q as a,z as b,T as c,$ as d,D as e,H as f,L as g,F as h,O as i};//# sourceMappingURL=chunk-FDXCXNZK.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-FDXCXNZK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/query.ts"],"names":["nextQueryId","moduleQueryCache","descKey","d","all","c","a","b","any","none","defineQuery","arg","desc","key","cached","q","enterQuery","query","reactive","exitQuery","ensureQueryRegistered","state","ww","withMask","createMask","anyMask","noneMask","compId","info","getComponentInfoById","bit","getOrRegisterComponentBit","setBit","bundle","isMaskZero","involvedBits","listBits","s","getQueryArchetypes","words","list","i","arch","matches","queryArchetypes","world","getWorldState","ids","out","id","runQuery","buf","e","archIds","r","iterQuery","src","forEachEntity","fn","cols","buildColumnViews","callWithCols","ents","n","eid","comp","getComponentInfo","storage","recordEntityMaskChange","changedBit","prevMask","nextMask","involved","qid","wasMatch","isMatch","pushReactive","queryId","kind","ensureReactiveBuffer","componentId","lazyGetComponentInfo","_getComponentInfoFn","registerComponentLookup"],"mappings":"8EAsBA,IAAIA,EAAc,CAAA,CACZC,CAAAA,CAAmB,IAAI,GAAA,CAE7B,SAASC,CAAAA,CAAQC,CAAAA,CAA4B,CAC3C,IAAMC,GAAOD,CAAAA,CAAE,GAAA,EAAO,EAAC,EACpB,GAAA,CAAKE,GAA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iB,EAChF,OAAOpD,CACT,CAEA,IAAIsD,EAA0E,IAAA,CACvE,SAASC,EAAwBzB,CAAAA,CAAqD,CAC3FwB,EAAsBxB,EACxB,CACA,SAASuB,CAAAA,CAAqBhC,EAAuC,CACnE,OAAOiC,EAAsBA,CAAAA,CAAoBjC,CAAE,EAAI,MACzD","file":"chunk-FDXCXNZK.js","sourcesContent":["import { createMask, isMaskZero, listBits, matches, setBit } from './bitmask.js'\nimport { getComponentInfo } from './component.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const any = (d.any ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const none = (d.none ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [\n ...listBits(withMask),\n ...listBits(anyMask),\n ...listBits(noneMask),\n ]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (\n matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n ) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n const ents = arch.entities\n const n = arch.size\n for (let r = 0; r < n; r++) {\n callWithCols(fn, ents[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(\n fn: (eid: EntityId, ...cols: any[]) => void,\n eid: EntityId,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, cols[0])\n break\n case 2:\n fn(eid, cols[0], cols[1])\n break\n case 3:\n fn(eid, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(eid, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(eid, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(\n prevMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n const isMatch = matches(\n nextMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n"]}
|