Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(ecs): a script component is rows, so compiled code has an address to read

yhh54f6c59eff27
diff --git a/compiler/tests/pool-layout.test.ts b/compiler/tests/pool-layout.test.ts
new file mode 100644
index 000000000..7ea554fc4
--- /dev/null
+++ b/compiler/tests/pool-layout.test.ts
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file pool-layout.test.ts
+ * @brief The engine's rows and the compiler's offsets are one layout.
+ *
+ * @details A compiled system loads a script component's field at the offset this
+ * compiler emitted. The engine writes it at the offset `ScriptPool`
+ * chose. Those are two authors for one number, and the way that ends is
+ * a read of a different field — the same failure EHT's table exists to
+ * prevent for engine components.
+ *
+ * So this holds them together over a real `defineComponent` shape. It
+ * is the script-side counterpart of the `offsetof` checks in
+ * tests/aot/test_aot_host.cpp.
+ */
+import { describe, it, expect } from 'vitest';
+import { resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { lowerProgram } from '../src/frontend';
+import { builtinShapes } from '../src/builtins';
+import { packLayout } from '../src/abi';
+import { encBytes } from '../src/eir';
+import { ScriptPool, poolShape, POOL_SLOT_BYTES } from '../../sdk/src/ecs/ScriptPool';
+
+const FIXTURE = resolve(fileURLToPath(new URL('./fixtures/in-subset.ts', import.meta.url)));
+
+/** The literal `defineComponent` passes, as the SDK holds it in `_default`. */
+const DRIFT_DEFAULTS = { rate: 40, wrap: 100, enabled: true };
+
+const { module } = lowerProgram([FIXTURE], builtinShapes());
+const layout = packLayout(module.comps);
+
+describe('a script component has one layout, not two', () => {
+ it('the compiler and the pool agree field by field', () => {
+ const shape = layout.comps.get('FixtureDrift');
+ expect(shape, 'the fixture stopped declaring FixtureDrift').toBeDefined();
+ const pool = new ScriptPool(poolShape(DRIFT_DEFAULTS)!);
+
+ expect(pool.stride).toBe(shape!.stride);
+ pool.fields.forEach((f, i) => {
+ const leaf = shape!.leaves.get(f.name);
+ expect(leaf, `the compiler has no field '${f.name}'`).toBeDefined();
+ expect(leaf!.byteOffset, `'${f.name}' sits in two places`).toBe(i * POOL_SLOT_BYTES);
+ // A host record is f64 throughout, which is what makes one slot per
+ // field the whole story.
+ expect(encBytes(leaf!.enc)).toBe(POOL_SLOT_BYTES);
+ });
+ });
+
+ it('and on the field ORDER, which is what a slot index means', () => {
+ // Declaration order is the only thing tying slot 1 to `wrap`. If the two
+ // sides ever sort differently, every field still exists and every one is
+ // the wrong one.
+ expect(new ScriptPool(poolShape(DRIFT_DEFAULTS)!).fields.map((f) => f.name))
+ .toEqual([...layout.comps.get('FixtureDrift')!.leaves.keys()]);
+ });
+
+ it('a shape the pool refuses is a shape the compiler refuses', () => {
+ // Both sides admit exactly the all-scalar shapes, and they have to: a
+ // component the compiler lowers but the engine cannot lay out flat is a
+ // system that compiles and then has nowhere to read from.
+ expect(poolShape({ label: 'hi' })).toBeNull();
+ expect(module.comps.get('FixtureDrift')!.storage).toBe('host');
+ for (const [, spec] of module.comps.get('FixtureDrift')!.fields) {
+ expect(spec.enc).toBe('f64');
+ expect(spec.offset, 'a host record is laid out by the ABI, not by EHT').toBeNull();
+ }
+ });
+});
diff --git a/sdk/src/ecs/ScriptPool.ts b/sdk/src/ecs/ScriptPool.ts
new file mode 100644
index 000000000..93d99d266
--- /dev/null
+++ b/sdk/src/ecs/ScriptPool.ts
@@ -0,0 +1,197 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ScriptPool.ts
+ * @brief Flat storage for a script component whose fields are all scalars.
+ *
+ * @details A `defineComponent` component is a JS object per entity, which is
+ * fine for the interpreter and impossible for compiled code: a compiled
+ * system reaches a component by ADDRESS, and a JS object has none. So a
+ * component whose defaults are entirely numbers and booleans is stored
+ * in one Float64Array instead, and what callers hold is a live view
+ * onto a row of it.
+ *
+ * The layout is the ABI's, not one chosen here: declaration order, one
+ * f64 per field, which is what `packLayout` gives a `host` shape. That
+ * agreement is a contract with the compiler and a test holds it.
+ *
+ * A view is LIVE, and for script components that changes nothing: the
+ * query already yields the stored object itself and `writeMutBack_`
+ * only records a Changed tick for them. Writing through a setter is the
+ * same write it always was, one indirection later.
+ */
+
+import type { Entity } from '../types';
+
+/** What a pooled field holds. Booleans are 0/1 in the slot, `true`/`false` out. */
+export type PoolKind = 'number' | 'boolean';
+
+export interface PoolField {
+ readonly name: string;
+ readonly kind: PoolKind;
+}
+
+/** One f64 per field: what the ABI gives a host record (REARCH_AOT_ABI §2.4). */
+export const POOL_SLOT_BYTES = 8;
+
+/**
+ * The fields a pool can back, or null when the defaults are not all scalars.
+ * Anything else — a string, an asset ref, a nested object, an array — has no
+ * fixed-width encoding, and a component holding one keeps the JS object path.
+ */
+export function poolShape(defaults: unknown): PoolField[] | null {
+ if (defaults === null || typeof defaults !== 'object' || Array.isArray(defaults)) return null;
+ const fields: PoolField[] = [];
+ for (const [name, v] of Object.entries(defaults as Record<string, unknown>)) {
+ if (typeof v === 'number') fields.push({ name, kind: 'number' });
+ else if (typeof v === 'boolean') fields.push({ name, kind: 'boolean' });
+ else return null;
+ }
+ return fields.length > 0 ? fields : null;
+}
+
+/**
+ * Rows of one component, and a view per live entity. Slots come from a free list
+ * rather than being compacted, so a view stays valid while its entity carries
+ * the component: an index that moved under a held view is a bug that surfaces
+ * three frames later. Iteration order lives in the map that holds the views.
+ */
+export class ScriptPool {
+ readonly fields: readonly PoolField[];
+ /** Bytes per row, and what the ABI's `stride` must agree with. */
+ readonly stride: number;
+
+ private slots_: Float64Array;
+ private capacity_: number;
+ private readonly slotOf_ = new Map<Entity, number>();
+ private readonly views_ = new Map<Entity, Record<string, unknown>>();
+ private readonly free_: number[] = [];
+ private next_ = 0;
+
+ constructor(fields: readonly PoolField[], capacity = 64) {
+ this.fields = fields;
+ this.stride = fields.length * POOL_SLOT_BYTES;
+ this.capacity_ = Math.max(1, capacity);
+ this.slots_ = new Float64Array(this.capacity_ * fields.length);
+ }
+
+ /** The backing store. Its byteOffset moves when the pool grows, so an
+ * address taken from `baseOf` is valid only until the next `add`. */
+ get buffer(): Float64Array {
+ return this.slots_;
+ }
+
+ get size(): number {
+ return this.slotOf_.size;
+ }
+
+ /** Byte offset of `entity`'s row inside `buffer`, for a host to hand over. */
+ baseOf(entity: Entity): number | undefined {
+ const slot = this.slotOf_.get(entity);
+ return slot === undefined ? undefined : slot * this.stride;
+ }
+
+ has(entity: Entity): boolean {
+ return this.slotOf_.has(entity);
+ }
+
+ /** The live view, or undefined when the entity does not carry this. */
+ get(entity: Entity): Record<string, unknown> | undefined {
+ return this.views_.get(entity);
+ }
+
+ /**
+ * Give `entity` a row seeded from `defaults` and overlaid with `data`, or
+ * overwrite the fields `data` names on the row it already has. Returns the
+ * view either way, and whether the row is new.
+ */
+ put(entity: Entity, defaults: Record<string, unknown>, data?: Record<string, unknown>):
+ { view: Record<string, unknown>; isNew: boolean } {
+ let slot = this.slotOf_.get(entity);
+ const isNew = slot === undefined;
+ if (slot === undefined) {
+ slot = this.claim_();
+ this.slotOf_.set(entity, slot);
+ this.views_.set(entity, this.makeView_(slot));
+ // A fresh row is seeded whole; an existing one keeps the fields the
+ // caller did not name, which is what `world.set` has always done.
+ this.writeAll_(slot, defaults);
+ }
+ if (data) this.writeSome_(slot, data);
+ return { view: this.views_.get(entity)!, isNew };
+ }
+
+ delete(entity: Entity): boolean {
+ const slot = this.slotOf_.get(entity);
+ if (slot === undefined) return false;
+ this.slotOf_.delete(entity);
+ this.views_.delete(entity);
+ this.free_.push(slot);
+ return true;
+ }
+
+ entities(): IterableIterator<Entity> {
+ return this.slotOf_.keys();
+ }
+
+ // -------------------------------------------------------------------------
+
+ private claim_(): number {
+ const reused = this.free_.pop();
+ if (reused !== undefined) return reused;
+ if (this.next_ >= this.capacity_) this.grow_();
+ return this.next_++;
+ }
+
+ private grow_(): void {
+ this.capacity_ *= 2;
+ const wider = new Float64Array(this.capacity_ * this.fields.length);
+ wider.set(this.slots_);
+ this.slots_ = wider;
+ // Views hold a slot index, not a reference into the old array, so they
+ // survive this. An ADDRESS taken before it does not, which is why
+ // `baseOf` says so.
+ for (const [entity, slot] of this.slotOf_) {
+ this.views_.set(entity, this.makeView_(slot));
+ }
+ }
+
+ private writeAll_(slot: number, from: Record<string, unknown>): void {
+ const base = slot * this.fields.length;
+ this.fields.forEach((f, i) => {
+ this.slots_[base + i] = toSlot(from[f.name]);
+ });
+ }
+
+ private writeSome_(slot: number, from: Record<string, unknown>): void {
+ const base = slot * this.fields.length;
+ this.fields.forEach((f, i) => {
+ const v = from[f.name];
+ if (v !== undefined) this.slots_[base + i] = toSlot(v);
+ });
+ }
+
+ /** One object per entity, with an accessor per field onto its row. */
+ private makeView_(slot: number): Record<string, unknown> {
+ const base = slot * this.fields.length;
+ const view: Record<string, unknown> = {};
+ this.fields.forEach((f, i) => {
+ const at = base + i;
+ Object.defineProperty(view, f.name, {
+ enumerable: true,
+ configurable: true,
+ get: f.kind === 'boolean'
+ ? (): boolean => this.slots_[at] !== 0
+ : (): number => this.slots_[at]!,
+ set: (v: unknown): void => { this.slots_[at] = toSlot(v); },
+ });
+ });
+ return view;
+ }
+}
+
+/** A slot holds a number; a boolean is the 0/1 the ABI stores it as. */
+function toSlot(v: unknown): number {
+ if (typeof v === 'boolean') return v ? 1 : 0;
+ return typeof v === 'number' ? v : 0;
+}
diff --git a/sdk/src/ecs/ScriptStorage.ts b/sdk/src/ecs/ScriptStorage.ts
index 16d523eb4..6e3ad22a3 100644
--- a/sdk/src/ecs/ScriptStorage.ts
+++ b/sdk/src/ecs/ScriptStorage.ts
@@ -10,6 +10,7 @@ import { ComponentDef } from './component';
import { validateComponentData, formatValidationErrors, assetFieldNames } from '../util/validation';
import { log } from '../util/logger';
import { reorderMapByRank, type RankOf } from './entityOrder';
+import { ScriptPool, poolShape } from './ScriptPool';
export interface InsertResult<T> {
value: T;
@@ -19,6 +20,36 @@ export interface InsertResult<T> {
export class ScriptStorage {
private tsStorage_ = new Map<symbol, Map<Entity, unknown>>();
private entityComponents_ = new Map<Entity, Set<symbol>>();
+ /**
+ * Components held as rows rather than objects, by id. A component qualifies
+ * when its defaults are all scalars, which is exactly the set a compiled
+ * system can reach — a compiled system addresses a component, and a JS
+ * object has no address (docs/REARCH_AOT_ABI.md §2.4).
+ */
+ private pools_ = new Map<symbol, ScriptPool>();
+
+ /** @internal The rows behind `component`, or undefined if it has none. */
+ poolFor(id: symbol): ScriptPool | undefined {
+ return this.pools_.get(id);
+ }
+
+ /**
+ * The pool `component` uses, creating it on first sight. `null` once for a
+ * shape that cannot be flat, and remembered as null so the check is not
+ * repeated per insert.
+ */
+ private pool_(component: ComponentDef<any>): ScriptPool | null {
+ const held = this.pools_.get(component._id);
+ if (held) return held;
+ if (this.notPooled_.has(component._id)) return null;
+ const fields = poolShape(component._default);
+ if (!fields) { this.notPooled_.add(component._id); return null; }
+ const pool = new ScriptPool(fields);
+ this.pools_.set(component._id, pool);
+ return pool;
+ }
+
+ private notPooled_ = new Set<symbol>();
insert<T>(entity: Entity, component: ComponentDef<T>, data?: unknown): InsertResult<T> {
let filtered: Partial<T> | undefined;
@@ -41,8 +72,20 @@ export class ScriptStorage {
filtered = clean as Partial<T>;
}
- const value = component.create(filtered);
const storage = this.getStorage(component);
+ const pool = this.pool_(component);
+ if (pool) {
+ // Defaults then the caller's fields, into the row. `create` would
+ // give the same object for an all-scalar shape, one allocation and
+ // one address short of what a compiled system needs.
+ const { view, isNew } = pool.put(
+ entity, component._default as Record<string, unknown>,
+ filtered as Record<string, unknown> | undefined);
+ storage.set(entity, view);
+ this.note_(entity, component);
+ return { value: view as T, isNew };
+ }
+ const value = component.create(filtered);
const isNew = !storage.has(entity);
storage.set(entity, value);
this.note_(entity, component);
@@ -79,6 +122,7 @@ export class ScriptStorage {
remove<T>(entity: Entity, component: ComponentDef<T>): void {
const storage = this.tsStorage_.get(component._id);
storage?.delete(entity);
+ this.pools_.get(component._id)?.delete(entity);
const ids = this.entityComponents_.get(entity);
if (ids) {
ids.delete(component._id);
@@ -104,6 +148,15 @@ export class ScriptStorage {
}
}
const storage = this.getStorage(component);
+ const pool = this.pool_(component);
+ if (pool) {
+ const { view, isNew } = pool.put(
+ entity, component._default as Record<string, unknown>,
+ (data ?? undefined) as Record<string, unknown> | undefined);
+ storage.set(entity, view);
+ this.note_(entity, component);
+ return { isNew };
+ }
const isNew = !storage.has(entity);
storage.set(entity, data);
this.note_(entity, component);
@@ -139,6 +192,7 @@ export class ScriptStorage {
const removed: symbol[] = [];
for (const id of ids) {
this.tsStorage_.get(id)?.delete(entity);
+ this.pools_.get(id)?.delete(entity);
removed.push(id);
}
this.entityComponents_.delete(entity);
diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.ts
index e35554b7c..3236a94aa 100644
--- a/sdk/src/ecs/world.ts
+++ b/sdk/src/ecs/world.ts
@@ -886,9 +886,12 @@ export class World {
}
return (e, d) => methods.add(e, convertForWasm(d as Record<string, unknown>, colorKeys));
}
+ // Through ScriptStorage, not into the map: a pooled component's stored
+ // value is a live view onto its row, and replacing it with a plain
+ // object would leave the row behind.
const storage = this.scripts_.getStorageById(component._id);
if (!storage) return null;
- return (e, d) => storage.set(e, d);
+ return (e, d) => { this.scripts_.set(e, component as ComponentDef<any>, d); };
}
// =========================================================================
diff --git a/sdk/tests/script-pool.test.ts b/sdk/tests/script-pool.test.ts
new file mode 100644
index 000000000..dd297e841
--- /dev/null
+++ b/sdk/tests/script-pool.test.ts
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file script-pool.test.ts
+ * @brief A script component held as rows, and the view onto one.
+ *
+ * @details Rows exist so a compiled system can be handed an ADDRESS, which a JS
+ * object does not have. Views exist so nothing above has to know.
+ *
+ * Both halves are checked here: the bytes sit where the ABI says, and a
+ * component still reads and writes as an object.
+ */
+import { describe, it, expect } from 'vitest';
+import { ScriptPool, poolShape, POOL_SLOT_BYTES } from '../src/ecs/ScriptPool';
+import type { Entity } from '../src/types';
+
+const e = (n: number): Entity => n as unknown as Entity;
+const DEFAULTS = { speed: 100, directionX: 0, directionY: 0, enabled: true };
+
+describe('which shapes can be rows at all', () => {
+ it('takes numbers and booleans, in declaration order', () => {
+ expect(poolShape(DEFAULTS)).toEqual([
+ { name: 'speed', kind: 'number' },
+ { name: 'directionX', kind: 'number' },
+ { name: 'directionY', kind: 'number' },
+ { name: 'enabled', kind: 'boolean' },
+ ]);
+ });
+
+ it('refuses anything with no fixed width', () => {
+ // Each of these is a component the compiler also refuses, and for the
+ // same reason: there is no offset to give it.
+ expect(poolShape({ name: 'hero' })).toBeNull();
+ expect(poolShape({ target: null })).toBeNull();
+ expect(poolShape({ nested: { x: 1 } })).toBeNull();
+ expect(poolShape({ path: [1, 2] })).toBeNull();
+ expect(poolShape({})).toBeNull();
+ });
+});
+
+describe('a row, and the view onto it', () => {
+ it('seeds from the defaults and lays them out one slot each', () => {
+ const pool = new ScriptPool(poolShape(DEFAULTS)!);
+ expect(pool.stride).toBe(4 * POOL_SLOT_BYTES);
+ const { view, isNew } = pool.put(e(1), DEFAULTS);
+ expect(isNew).toBe(true);
+ expect(pool.baseOf(e(1))).toBe(0);
+ expect({ ...view }).toEqual(DEFAULTS);
+ });
+
+ it('a view is LIVE: writing through it changes the bytes', () => {
+ const pool = new ScriptPool(poolShape(DEFAULTS)!);
+ const { view } = pool.put(e(1), DEFAULTS);
+ view['speed'] = 250;
+ view['enabled'] = false;
+ // Read back through the pool, not through the same object, so this is
+ // about the storage rather than about the object remembering.
+ expect(pool.buffer[0]).toBe(250);
+ expect(pool.buffer[3]).toBe(0);
+ expect(pool.get(e(1))!['speed']).toBe(250);
+ expect(pool.get(e(1))!['enabled']).toBe(false);
+ });
+
+ it('a boolean is 0/1 in the slot and true/false out', () => {
+ const pool = new ScriptPool(poolShape(DEFAULTS)!);
+ const { view } = pool.put(e(1), DEFAULTS);
+ expect(view['enabled']).toBe(true);
+ view['enabled'] = false;
+ expect(view['enabled']).toBe(false);
+ // Not 0: a component that started answering 0 where it answered false
+ // would pass `if (c.enabled)` and fail `c.enabled === false`.
+ expect(view['enabled']).not.toBe(0);
+ });
+
+ it('overwriting names some fields and leaves the rest', () => {
+ const pool = new ScriptPool(poolShape(DEFAULTS)!);
+ pool.put(e(1), DEFAULTS);
+ const { view, isNew } = pool.put(e(1), DEFAULTS, { speed: 7 });
+ expect(isNew).toBe(false);
+ expect(view['speed']).toBe(7);
+ expect(view['directionX']).toBe(0);
+ expect(view['enabled']).toBe(true);
+ });
+
+ it('the same entity keeps the same object across writes', () => {
+ const pool = new ScriptPool(poolShape(DEFAULTS)!);
+ const first = pool.put(e(1), DEFAULTS).view;
+ const again = pool.put(e(1), DEFAULTS, { speed: 3 }).view;
+ // A system that held the component across a `world.set` would otherwise
+ // be writing into an object nothing reads.
+ expect(again).toBe(first);
+ expect(first['speed']).toBe(3);
+ });
+
+ it('a freed slot is reused, and the reused row is seeded fresh', () => {
+ const pool = new ScriptPool(poolShape(DEFAULTS)!);
+ pool.put(e(1), DEFAULTS, { speed: 999 });
+ const at = pool.baseOf(e(1));
+ expect(pool.delete(e(1))).toBe(true);
+ expect(pool.get(e(1))).toBeUndefined();
+ expect(pool.has(e(1))).toBe(false);
+
+ pool.put(e(2), DEFAULTS);
+ expect(pool.baseOf(e(2))).toBe(at);
+ // Left at 999 it would be the previous entity's data under a new name.
+ expect(pool.get(e(2))!['speed']).toBe(100);
+ });
+
+ it('growing keeps every row, and every view keeps working', () => {
+ const pool = new ScriptPool(poolShape(DEFAULTS)!, 2);
+ const views: Record<string, unknown>[] = [];
+ for (let i = 1; i <= 40; i++) views.push(pool.put(e(i), DEFAULTS, { speed: i }).view);
+ expect(pool.size).toBe(40);
+ for (let i = 1; i <= 40; i++) {
+ expect(pool.get(e(i))!['speed'], `entity ${i}`).toBe(i);
+ }
+ // The views handed out before the growth still address their own rows.
+ views[0]!['speed'] = -1;
+ expect(pool.get(e(1))!['speed']).toBe(-1);
+ expect(pool.get(e(2))!['speed']).toBe(2);
+ });
+
+ it('rows are contiguous, which is the whole reason for them', () => {
+ const pool = new ScriptPool(poolShape(DEFAULTS)!);
+ for (let i = 1; i <= 4; i++) pool.put(e(i), DEFAULTS, { speed: i * 10 });
+ expect([...pool.buffer.slice(0, 16)].filter((_, k) => k % 4 === 0))
+ .toEqual([10, 20, 30, 40]);
+ expect(pool.baseOf(e(3))! - pool.baseOf(e(2))!).toBe(pool.stride);
+ });
+});