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(native): boot the real SDK World over the native core (Stage A complete)

yhh107f2aea1ce6
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 45dc69ebd..9cac53e0f 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1327 stable · 22 beta · 0 deprecated
+Symbols: 1328 stable · 22 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -8443,6 +8443,11 @@ Plugin
(scope?: Record<string, unknown>): CppRegistry
```
+## createNativeWorld — function
+```
+(scope?: Record<string, unknown>): World
+```
+
## createProgress — function
```
(opts: ProgressOptions): ProgressHandle
diff --git a/sdk/src/ecs/nativeRegistry.ts b/sdk/src/ecs/nativeRegistry.ts
index e19b8a944..6cbd70d2e 100644
--- a/sdk/src/ecs/nativeRegistry.ts
+++ b/sdk/src/ecs/nativeRegistry.ts
@@ -29,17 +29,52 @@ function views(buf: ArrayBuffer): [Float32Array, Uint32Array, Uint8Array] {
return [new Float32Array(buf), new Uint32Array(buf), new Uint8Array(buf)];
}
+/** Invoke a host-provided global by name (throws a clear error if the host did not
+ * bind it — these are part of the native registry contract, not optional). */
+function hostCall(scope: Record<string, unknown>, name: string, args: unknown[]): unknown {
+ const fn = scope[name];
+ if (typeof fn !== 'function') {
+ throw new Error(`native host binding "${name}" is missing`);
+ }
+ return (fn as (...a: unknown[]) => unknown)(...args);
+}
+
+/** Present a JS array as the embind VectorEntity interface World.getChildren
+ * returns (size()/get(i)/delete()), so despawn iterates it the same on both
+ * backends. Native memory is JS-owned here, so delete() is a no-op. */
+function vectorEntity(arr: readonly Entity[]): { size(): number; get(i: number): Entity; delete(): void } {
+ return { size: () => arr.length, get: (i: number) => arr[i], delete: () => { /* nothing to free */ } };
+}
+
/**
- * Build a CppRegistry over the host's native component bindings. `scope` holds the
- * generated `es_<Component>_buffer` / `_has` / `_remove` globals (the QuickJS
- * global object on a device; a plain object in tests). Only components whose three
- * bindings are present get methods, so a host that binds a subset still connects.
+ * Build the full CppRegistry over the host's native bindings — entity lifecycle +
+ * hierarchy (es_createEntity / es_destroyEntity / es_setParent / …) plus, per
+ * component, the generated es_<Component>_buffer / _has / _remove. `scope` holds
+ * those globals (the QuickJS global object on a device; a plain object in tests).
+ * Only components whose three bindings are present get component methods, so a host
+ * that binds a subset still connects.
*/
export function createNativeRegistry(
scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
): CppRegistry {
const reg: Record<string, unknown> = {};
+ // Entity lifecycle + hierarchy — the base Registry surface World drives (spawn,
+ // despawn, parent/child). These are not per-component; the host binds them by
+ // hand (the native siblings of the embind Registry's entity ops).
+ reg.create = (): Entity => hostCall(scope, 'es_createEntity', []) as Entity;
+ reg.destroy = (e: Entity): void => { hostCall(scope, 'es_destroyEntity', [e]); };
+ reg.hasParent = (e: Entity): boolean => !!hostCall(scope, 'es_hasParent', [e]);
+ reg.setParent = (child: Entity, parent: Entity): void => {
+ hostCall(scope, 'es_setParent', [child, parent]);
+ };
+ reg.removeParent = (e: Entity): void => { hostCall(scope, 'es_removeParent', [e]); };
+ reg.hasChildren = (e: Entity): boolean => !!hostCall(scope, 'es_hasChildren', [e]);
+ reg.getChildren = (e: Entity) => ({
+ entities: vectorEntity((hostCall(scope, 'es_getChildren', [e]) as Entity[] | undefined) ?? []),
+ });
+ reg.delete = (): void => {};
+
for (const cppName of Object.keys(PTR_ACCESSORS)) {
const accessor = PTR_ACCESSORS[cppName];
const bufFn = scope[`es_${cppName}_buffer`] as BufferFn | undefined; // getOrEmplace = add
diff --git a/sdk/src/ecs/nativeRuntime.ts b/sdk/src/ecs/nativeRuntime.ts
new file mode 100644
index 000000000..da01b030f
--- /dev/null
+++ b/sdk/src/ecs/nativeRuntime.ts
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Boot the real SDK ECS World over the native (embedded-Dawn) core.
+//
+// On web the World is connected to the wasm module's embind Registry; here it is
+// connected to the native registry + memory backend, both composed from the host's
+// generated bindings (createNativeRegistry / NativeMemoryProvider). The result is
+// the SAME World class the web build uses — spawn / insert / get / query / parent
+// authoring runs in the JS engine, writing the native C++ ECS, which the native
+// host renders. No wasm module: entity generations fall back to World's JS path.
+
+import { World } from '../world';
+import { ensureBuiltinComponentsRegistered } from '../component';
+import { createNativeRegistry } from './nativeRegistry';
+import { NativeMemoryProvider } from './memoryProvider';
+
+/**
+ * Create a World bound to the native core. `scope` is where the host installed its
+ * bindings (the QuickJS global object on a device; a plain object in tests). The
+ * returned World is the real SDK World — the game script authors entities and
+ * components through it, and the native host reads the resulting ECS each frame.
+ */
+export function createNativeWorld(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): World {
+ // Idempotent: register every engine component so a scene can't silently drop one
+ // (the native entry does this too, but keep the boot self-contained for hosts /
+ // tests that call this directly).
+ ensureBuiltinComponentsRegistered();
+
+ const world = new World();
+ world.connectCpp(createNativeRegistry(scope), undefined, {
+ memory: new NativeMemoryProvider(scope),
+ });
+ return world;
+}
diff --git a/sdk/src/index.native.ts b/sdk/src/index.native.ts
index 388e14e7e..00484c9a4 100644
--- a/sdk/src/index.native.ts
+++ b/sdk/src/index.native.ts
@@ -49,6 +49,10 @@ export type { MemoryProvider, ComponentHeap, NativeComponentBufferFn } from './e
// _remove bindings; pass to BuiltinBridge.connect as the cppRegistry.
export { createNativeRegistry } from './ecs/nativeRegistry';
+// Boot the real SDK ECS World over the native core — the host's entry point for
+// running the actual SDK (spawn/insert/query authoring) against native C++ ECS.
+export { createNativeWorld } from './ecs/nativeRuntime';
+
// ABI layout hash of the component schema this bundle was generated from — the
// native shell compares it against the wasm build it loads (same as the editor).
export { ABI_LAYOUT_HASH } from './component.generated';
diff --git a/sdk/tests/native-world.test.ts b/sdk/tests/native-world.test.ts
new file mode 100644
index 000000000..4808bfca0
--- /dev/null
+++ b/sdk/tests/native-world.test.ts
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file native-world.test.ts
+ * @brief The real SDK World, booted over the native core (Stage A finale). A
+ * mock native ECS backs the host bindings (entity alloc + hierarchy +
+ * per-component storage) so the ACTUAL World class — spawn / insert /
+ * get / has / remove / setParent / cascading despawn — drives the native
+ * registry + memory backend end-to-end, headless, no device.
+ */
+import { describe, expect, it } from 'vitest';
+import { createNativeWorld } from '../src/ecs/nativeRuntime';
+import { PTR_ACCESSORS } from '../src/ecs/ptrAccessors.generated';
+import { Sprite, Transform } from '../src/component';
+
+/** A self-contained fake native ECS + the host bindings createNativeWorld expects. */
+function mockNativeEcs() {
+ let nextId = 1;
+ const alive = new Set<number>();
+ const parents = new Map<number, number>(); // child -> parent
+ const children = new Map<number, Set<number>>(); // parent -> children
+ const comps = new Map<string, Map<number, ArrayBuffer>>();
+ const store = (cpp: string) => {
+ let m = comps.get(cpp);
+ if (!m) { m = new Map(); comps.set(cpp, m); }
+ return m;
+ };
+
+ const scope: Record<string, unknown> = {
+ es_createEntity: () => { const e = nextId++; alive.add(e); return e; },
+ es_destroyEntity: (e: number) => {
+ alive.delete(e);
+ for (const m of comps.values()) m.delete(e);
+ const p = parents.get(e);
+ if (p !== undefined) children.get(p)?.delete(e);
+ parents.delete(e);
+ children.delete(e);
+ },
+ es_hasParent: (e: number) => parents.has(e),
+ es_setParent: (c: number, p: number) => {
+ parents.set(c, p);
+ let s = children.get(p);
+ if (!s) { s = new Set(); children.set(p, s); }
+ s.add(c);
+ },
+ es_removeParent: (e: number) => {
+ const p = parents.get(e);
+ if (p !== undefined) children.get(p)?.delete(e);
+ parents.delete(e);
+ },
+ es_hasChildren: (e: number) => (children.get(e)?.size ?? 0) > 0,
+ es_getChildren: (e: number) => [...(children.get(e) ?? [])],
+ };
+ for (const cppName of Object.keys(PTR_ACCESSORS)) {
+ scope[`es_${cppName}_buffer`] = (e: number) => {
+ const m = store(cppName);
+ let b = m.get(e);
+ if (!b) { b = new ArrayBuffer(256); m.set(e, b); }
+ return b;
+ };
+ scope[`es_${cppName}_has`] = (e: number) => store(cppName).has(e);
+ scope[`es_${cppName}_remove`] = (e: number) => { store(cppName).delete(e); };
+ }
+ return { scope, alive, comps };
+}
+
+describe('createNativeWorld', () => {
+ it('spawns, authors components, and reads them back through the real World', () => {
+ const { scope, alive } = mockNativeEcs();
+ const world = createNativeWorld(scope);
+
+ const e = world.spawn();
+ expect(alive.has(e)).toBe(true); // native entity really created
+ expect(world.valid(e)).toBe(true);
+
+ world.insert(e, Sprite, {
+ color: { r: 0.5, g: 0.25, b: 0.125, a: 1 },
+ size: { x: 20, y: 40 },
+ lit: true,
+ });
+ expect(world.has(e, Sprite)).toBe(true);
+
+ const sprite = world.get(e, Sprite);
+ expect(sprite.color.r).toBeCloseTo(0.5);
+ expect(sprite.color.g).toBeCloseTo(0.25);
+ expect(sprite.color.b).toBeCloseTo(0.125);
+ expect(sprite.size).toMatchObject({ x: 20, y: 40 });
+ expect(sprite.lit).toBe(true);
+
+ world.insert(e, Transform, { position: { x: 3, y: 4, z: 5 } });
+ expect(world.get(e, Transform).position).toMatchObject({ x: 3, y: 4, z: 5 });
+
+ world.remove(e, Sprite);
+ expect(world.has(e, Sprite)).toBe(false);
+ expect(world.has(e, Transform)).toBe(true); // unaffected
+ });
+
+ it('drives hierarchy + cascading despawn through the native registry', () => {
+ const { scope, alive } = mockNativeEcs();
+ const world = createNativeWorld(scope);
+
+ const parent = world.spawn();
+ const child = world.spawn();
+ world.setParent(child, parent);
+ expect(alive.has(parent)).toBe(true);
+ expect(alive.has(child)).toBe(true);
+
+ world.despawn(parent); // cascades via es_getChildren
+ expect(world.valid(parent)).toBe(false);
+ expect(world.valid(child)).toBe(false); // child despawned with the subtree
+ expect(alive.has(parent)).toBe(false); // native destroy really ran
+ expect(alive.has(child)).toBe(false);
+ });
+
+ it('keeps distinct entities independent', () => {
+ const { scope } = mockNativeEcs();
+ const world = createNativeWorld(scope);
+
+ const a = world.spawn();
+ const b = world.spawn();
+ world.insert(a, Sprite, { lit: true });
+ world.insert(b, Sprite, { lit: false });
+
+ expect(world.get(a, Sprite).lit).toBe(true);
+ expect(world.get(b, Sprite).lit).toBe(false);
+ expect(a).not.toBe(b);
+ });
+});