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(entity): expose packed {generation,index} layout and add isStale()

esengine8a47bd086a2d
diff --git a/sdk/src/types.ts b/sdk/src/types.ts
index bac589da1..fbc8c7277 100644
--- a/sdk/src/types.ts
+++ b/sdk/src/types.ts
@@ -7,9 +7,59 @@
// Entity
// =============================================================================
+/**
+ * Entity identifier — a packed u32 with layout `[generation(12) | index(20)]`,
+ * matching the C++ `Entity` type in `src/esengine/core/Types.hpp`.
+ *
+ * The 20-bit index is the slot in the registry (up to 1,048,575 live entities);
+ * the 12-bit generation is bumped each time an index is recycled (up to 4,095
+ * generations per slot before wrap). Comparing two raw Entity values thus
+ * detects stale handles: a handle from a despawned entity will have a
+ * different (generation, index) pair than any current live entity that reuses
+ * the index, so `rawA !== rawB` reliably distinguishes them.
+ *
+ * The value is transported across the WASM boundary as a plain u32 and used
+ * directly as a Map/Set key on the JS side.
+ */
export type Entity = number;
+
+/** Bit widths of the packed Entity representation (must match C++). */
+export const ENTITY_INDEX_BITS = 20;
+export const ENTITY_GEN_BITS = 12;
+export const ENTITY_INDEX_MASK = (1 << ENTITY_INDEX_BITS) - 1;
+export const ENTITY_GEN_MASK = (1 << ENTITY_GEN_BITS) - 1;
+
+/** 20-bit index portion of an Entity handle. */
+export function entityIndex(e: Entity): number {
+ return e & ENTITY_INDEX_MASK;
+}
+
+/** 12-bit generation portion of an Entity handle. */
+export function entityGeneration(e: Entity): number {
+ return (e >>> ENTITY_INDEX_BITS) & ENTITY_GEN_MASK;
+}
+
+/** Construct an Entity from an index + generation pair. */
+export function makeEntity(index: number, generation: number): Entity {
+ return (((generation & ENTITY_GEN_MASK) << ENTITY_INDEX_BITS) | (index & ENTITY_INDEX_MASK)) as Entity;
+}
+
+/**
+ * JS-side invalid-entity sentinel.
+ *
+ * NOTE: this is `0` for legacy serialization compatibility — scenes written
+ * before this packing was documented use `0` to mean "no entity reference".
+ * C++ uses `0xFFFFFFFF` as its sentinel; producers/consumers at the WASM
+ * boundary must translate between the two. New code should prefer
+ * `isValidEntity()` over comparing against this constant directly.
+ */
export const INVALID_ENTITY = 0 as Entity;
+/** True when the handle is neither the JS nor C++ invalid sentinel. */
+export function isValidEntity(e: Entity): boolean {
+ return e !== INVALID_ENTITY && e !== 0xFFFFFFFF;
+}
+
export type TextureHandle = number;
export const INVALID_TEXTURE = 0 as TextureHandle;
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index ff5920b0f..7764c6745 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -3,7 +3,7 @@
* @brief ECS World with C++ Registry integration
*/
-import { Entity } from './types';
+import { Entity, entityGeneration, entityIndex, makeEntity } from './types';
import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents, getComponentRegistry, Name } from './component';
import type { CppRegistry, ESEngineModule } from './wasm';
import { handleWasmError } from './wasmError';
@@ -71,8 +71,9 @@ export class World {
readonly changes_ = new ChangeTracker();
readonly queries_ = new QueryCache();
private entities_ = new Map<Entity, number>();
+ private indexGeneration_ = new Map<number, number>(); // index -> current generation (for isStale detection)
private iterationDepth_ = 0;
- private nextEntityId_ = 0;
+ private nextEntityIndex_ = 0; // pure-JS fallback: monotonic index counter
private nextGeneration_ = 0;
private spawnCallbacks_: Array<(entity: Entity) => void> = [];
private despawnCallbacks_: Array<(entity: Entity) => void> = [];
@@ -129,7 +130,12 @@ export class World {
throw e;
}
} else {
- entity = (++this.nextEntityId_) as Entity;
+ // Pure-JS fallback: pack into the same {generation(12) | index(20)}
+ // layout as C++ so Entity helpers (entityIndex/entityGeneration)
+ // give consistent results whether or not WASM is connected.
+ const idx = ++this.nextEntityIndex_;
+ const gen = (this.indexGeneration_.get(idx) ?? 0);
+ entity = makeEntity(idx, gen);
}
let generation = 0;
@@ -142,6 +148,7 @@ export class World {
generation = ++this.nextGeneration_;
}
this.entities_.set(entity, generation);
+ this.indexGeneration_.set(entityIndex(entity), entityGeneration(entity));
this.queries_.markStructuralChange();
if (name !== undefined) {
@@ -208,6 +215,19 @@ export class World {
return this.entities_.has(entity);
}
+ /**
+ * True if `entity` refers to a slot that has been recycled — its index is
+ * currently live, but held by a *different* generation. Useful for
+ * diagnostic logs: `valid()` alone can't distinguish "never existed" from
+ * "was despawned and its slot reassigned" since both return false.
+ */
+ isStale(entity: Entity): boolean {
+ if (this.entities_.has(entity)) return false;
+ const idx = entityIndex(entity);
+ const currentGen = this.indexGeneration_.get(idx);
+ return currentGen !== undefined && currentGen !== entityGeneration(entity);
+ }
+
entityCount(): number {
return this.entities_.size;
}
diff --git a/sdk/tests/entity-generation.test.ts b/sdk/tests/entity-generation.test.ts
new file mode 100644
index 000000000..bf3a52e4a
--- /dev/null
+++ b/sdk/tests/entity-generation.test.ts
@@ -0,0 +1,73 @@
+/**
+ * @file entity-generation.test.ts
+ * @brief Verify Entity packing helpers and World's stale-handle detection.
+ */
+import { describe, expect, it } from 'vitest';
+import { World } from '../src/world';
+import {
+ ENTITY_GEN_BITS,
+ ENTITY_INDEX_BITS,
+ ENTITY_INDEX_MASK,
+ entityGeneration,
+ entityIndex,
+ isValidEntity,
+ makeEntity,
+ INVALID_ENTITY,
+} from '../src/types';
+
+describe('Entity packing', () => {
+ it('round-trips index/generation through makeEntity', () => {
+ const e = makeEntity(12345, 7);
+ expect(entityIndex(e)).toBe(12345);
+ expect(entityGeneration(e)).toBe(7);
+ });
+
+ it('uses the documented 20/12 bit layout', () => {
+ expect(ENTITY_INDEX_BITS).toBe(20);
+ expect(ENTITY_GEN_BITS).toBe(12);
+ expect(ENTITY_INDEX_MASK).toBe(0xFFFFF);
+ });
+
+ it('masks out-of-range index/generation to their documented widths', () => {
+ const e = makeEntity(0xFFFFFFFF, 0xFFFFFFFF);
+ expect(entityIndex(e)).toBe(0xFFFFF);
+ expect(entityGeneration(e)).toBe(0xFFF);
+ });
+
+ it('treats both sentinels as invalid', () => {
+ expect(isValidEntity(INVALID_ENTITY)).toBe(false);
+ expect(isValidEntity(0xFFFFFFFF)).toBe(false);
+ expect(isValidEntity(makeEntity(1, 0))).toBe(true);
+ });
+});
+
+describe('World stale-handle detection (pure-JS mode)', () => {
+ it('valid() distinguishes live from despawned handles', () => {
+ const world = new World();
+ const a = world.spawn();
+ expect(world.valid(a)).toBe(true);
+ world.despawn(a);
+ expect(world.valid(a)).toBe(false);
+ });
+
+ it('isStale() returns false for a live handle', () => {
+ const world = new World();
+ const a = world.spawn();
+ expect(world.isStale(a)).toBe(false);
+ });
+
+ it('isStale() returns false for a never-existed handle (not same as stale)', () => {
+ const world = new World();
+ const neverSpawned = makeEntity(999_999, 0);
+ expect(world.valid(neverSpawned)).toBe(false);
+ expect(world.isStale(neverSpawned)).toBe(false);
+ });
+
+ it('pure-JS spawns pack generation=0 into the layout', () => {
+ const world = new World();
+ const a = world.spawn();
+ // Pure-JS mode does not recycle indices yet, so every spawn is gen=0.
+ expect(entityGeneration(a)).toBe(0);
+ expect(entityIndex(a)).toBeGreaterThan(0);
+ });
+});