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): backend-neutral MemoryProvider — real SDK marshalling on the native core

yhh5984e9ae49cd
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 7406da83e..5073d5300 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: 1322 stable · 22 beta · 0 deprecated
+Symbols: 1326 stable · 22 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1603,6 +1603,14 @@ spineFields: SpineFieldMeta | undefined
transient: boolean
```
+## ComponentHeap — interface
+```
+f32: Float32Array<ArrayBufferLike>
+ptr: number
+u32: Uint32Array<ArrayBufferLike>
+u8: Uint8Array<ArrayBufferLike>
+```
+
## ComponentMetadata — interface
```
animatableFields: string[] | undefined
@@ -3763,6 +3771,11 @@ static new (opts: MeasuredLinearLayoutOptions): MeasuredLinearLayoutProvider
static prototype: MeasuredLinearLayoutProvider
```
+## MemoryProvider — interface
+```
+resolveComponentHeap: (cppName: string) => ComponentHeapResolver | null
+```
+
## MemoryTransport — class
```
dropPending: () => void
@@ -3928,6 +3941,11 @@ storageKeys: () => string[]
writeCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined
```
+## NativeComponentBufferFn — type
+```
+(entity: number) => ArrayBuffer | null | undefined
+```
+
## NativeFetchResult — interface @beta
```
arrayBuffer: ArrayBuffer | undefined
@@ -3948,6 +3966,13 @@ onTouchMove: (id: number, x: number, y: number) => void
onTouchStart: (id: number, x: number, y: number) => void
```
+## NativeMemoryProvider — class
+```
+resolveComponentHeap: (cppName: string) => ComponentHeapResolver | null
+static new (scope?: Record<string, unknown>): NativeMemoryProvider
+static prototype: NativeMemoryProvider
+```
+
## NativePlatformAdapter — class @beta
```
bindInputEvents: (callbacks: InputEventCallbacks) => void
diff --git a/sdk/src/ecs/BuiltinBridge.ts b/sdk/src/ecs/BuiltinBridge.ts
index ccd94e5d9..f66d9c1a8 100644
--- a/sdk/src/ecs/BuiltinBridge.ts
+++ b/sdk/src/ecs/BuiltinBridge.ts
@@ -12,8 +12,11 @@ import { validateComponentData, formatValidationErrors, assetFieldNames } from '
import { handleWasmError } from '../wasmError';
import { installAbortGuard, throwIfModuleAborted, isModuleAborted, WasmModuleAborted } from '../moduleHealth';
import { COMPONENT_META, ABI_LAYOUT_HASH } from '../component.generated';
-import { PTR_LAYOUTS } from '../ptrLayouts.generated';
import { PTR_ACCESSORS } from './ptrAccessors.generated';
+import {
+ type MemoryProvider, type ComponentHeap,
+ WasmMemoryProvider, resolveWasmPtrFn,
+} from './memoryProvider';
// =============================================================================
// Color conversion helpers
@@ -262,6 +265,14 @@ export interface BridgeConnectOptions {
* partial mock registries used in unit tests working unchanged.
*/
readonly strict?: boolean;
+
+ /**
+ * Fast-path memory backend. Omit on web/emscripten: `connect` derives a
+ * {@link WasmMemoryProvider} from `module`. The native (embedded-Dawn) runtime
+ * injects a {@link NativeMemoryProvider} here — there is no wasm module, so the
+ * bridge reaches components through the host's `es_<Component>_buffer` bindings.
+ */
+ readonly memory?: MemoryProvider;
}
const METHOD_PREFIXES = ['add', 'get', 'has', 'remove'] as const;
@@ -301,6 +312,7 @@ function formatBridgeDiagnostic(v: BridgeVerification): string {
export class BuiltinBridge {
private cppRegistry_: CppRegistry | null = null;
private module_: ESEngineModule | null = null;
+ private memory_: MemoryProvider | null = null;
private builtinMethodCache_ = new Map<string, BuiltinMethods>();
private builtinEntitySets_ = new Map<string, Set<Entity>>();
@@ -324,6 +336,11 @@ export class BuiltinBridge {
): void {
this.cppRegistry_ = cppRegistry;
this.module_ = module ?? null;
+ // Web derives a wasm-HEAP backend from the module; the native runtime
+ // injects its own (es_<Component>_buffer). No module and no override => no
+ // fast path (resolvePtr* return null), exactly as before.
+ this.memory_ = options.memory
+ ?? (module ? new WasmMemoryProvider(module, cppRegistry) : null);
this.builtinMethodCache_.clear();
this.builtinEntitySets_.clear();
@@ -343,6 +360,7 @@ export class BuiltinBridge {
if (verification.abiMismatch || (options.strict && !verification.ok)) {
this.cppRegistry_ = null;
this.module_ = null;
+ this.memory_ = null;
this.builtinMethodCache_.clear();
throw new Error(formatBridgeDiagnostic(verification));
}
@@ -351,6 +369,7 @@ export class BuiltinBridge {
disconnect(): void {
this.cppRegistry_ = null;
this.module_ = null;
+ this.memory_ = null;
this.builtinMethodCache_.clear();
this.builtinEntitySets_.clear();
}
@@ -603,27 +622,25 @@ export class BuiltinBridge {
this.builtinEntitySets_.get(component._cppName)?.delete(entity);
}
+ /**
+ * The wasm-exported pointer function for `cppName` — `(entity) => byte offset
+ * of that entity's component in the wasm heap`. Web/emscripten only (there is
+ * no such numeric address on native); the fast path itself goes through the
+ * {@link MemoryProvider}, so this is a lower-level convenience.
+ */
resolvePtrFn(cppName: string): ((entity: Entity) => number) | null {
- const layout = PTR_LAYOUTS[cppName];
- if (!layout) return null;
- const mod = this.module_ as Record<string, unknown> | null;
- if (!mod) return null;
- const fn = mod[layout.ptrFn] as ((r: CppRegistry, e: number) => number) | undefined;
- if (!fn) return null;
- const reg = this.cppRegistry_!;
- return (e: Entity) => fn(reg, e);
+ return resolveWasmPtrFn(this.module_, this.cppRegistry_, cppName);
}
resolvePtrSetter(cppName: string): ((entity: Entity, data: unknown) => void) | null {
const accessor = PTR_ACCESSORS[cppName];
if (!accessor) return null;
- const getPtrFn = this.resolvePtrFn(cppName);
- if (!getPtrFn) return null;
- const mod = this.module_!;
+ const resolveHeap = this.memory_?.resolveComponentHeap(cppName);
+ if (!resolveHeap) return null;
+ const heap: ComponentHeap = SCRATCH_HEAP();
return (e: Entity, data: unknown) => {
- const ptr = getPtrFn(e);
- if (!ptr) return;
- accessor.write(mod.HEAPF32, mod.HEAPU32, mod.HEAPU8, ptr, data);
+ if (!resolveHeap(e, heap)) return;
+ accessor.write(heap.f32, heap.u32, heap.u8, heap.ptr, data);
};
}
@@ -634,15 +651,23 @@ export class BuiltinBridge {
resolvePtrGetter(cppName: string): ((entity: Entity) => unknown) | null {
const accessor = PTR_ACCESSORS[cppName];
if (!accessor) return null;
- const getPtrFn = this.resolvePtrFn(cppName);
- if (!getPtrFn) return null;
- const mod = this.module_!;
+ const resolveHeap = this.memory_?.resolveComponentHeap(cppName);
+ if (!resolveHeap) return null;
+ const heap: ComponentHeap = SCRATCH_HEAP();
const cached = accessor.create();
return (e: Entity) => {
- const ptr = getPtrFn(e);
- if (!ptr) return null;
- accessor.fill(mod.HEAPF32, mod.HEAPU32, mod.HEAPU8, ptr, cached);
+ if (!resolveHeap(e, heap)) return null;
+ accessor.fill(heap.f32, heap.u32, heap.u8, heap.ptr, cached);
return cached;
};
}
}
+
+// A fresh reusable ComponentHeap for one resolver. Its views are overwritten on
+// every successful resolve, so the empty initial arrays are never observed.
+function SCRATCH_HEAP(): ComponentHeap {
+ return { f32: EMPTY_F32, u32: EMPTY_U32, u8: EMPTY_U8, ptr: 0 };
+}
+const EMPTY_F32 = new Float32Array(0);
+const EMPTY_U32 = new Uint32Array(0);
+const EMPTY_U8 = new Uint8Array(0);
diff --git a/sdk/src/ecs/memoryProvider.ts b/sdk/src/ecs/memoryProvider.ts
new file mode 100644
index 000000000..77657b4c9
--- /dev/null
+++ b/sdk/src/ecs/memoryProvider.ts
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Backend-neutral fast-path component memory.
+//
+// The generated ptrAccessors (ptrAccessors.generated.ts) read and write a
+// component's fields against three typed-array views + a base byte offset. Where
+// those views come from is the one thing that differs between backends, so it is
+// the only thing abstracted here — the accessor logic itself is shared verbatim:
+//
+// * web (WasmMemoryProvider): the whole wasm HEAP as F32/U32/U8 views, and a
+// per-entity byte offset from the wasm-exported ptr function.
+// * native (NativeMemoryProvider): a zero-copy ArrayBuffer over one native ECS
+// component (the host's generated `es_<Component>_buffer(entity)` binding),
+// viewed as F32/U32/U8, with offset 0.
+//
+// Same generated accessors, same POD layout (wasm32/arm64 layout-identical, per
+// the EHT ABI hash), two memory backends — this is the seam that lets the real
+// SDK component API run unchanged on both.
+
+import type { Entity } from '../types';
+import type { CppRegistry, ESEngineModule } from '../wasm';
+import { PTR_LAYOUTS } from '../ptrLayouts.generated';
+
+/**
+ * Heap views + base byte offset for one component instance. The resolver reuses a
+ * single instance across calls (it only ever writes the four fields), so callers
+ * must consume it immediately and never retain it.
+ */
+export interface ComponentHeap {
+ f32: Float32Array;
+ u32: Uint32Array;
+ u8: Uint8Array;
+ ptr: number;
+}
+
+/** Fills `out` with the heap views + base ptr for `entity`'s component; returns
+ * false when the entity has no live component (skip the read/write). */
+export type ComponentHeapResolver = (entity: Entity, out: ComponentHeap) => boolean;
+
+/**
+ * Where the fast path gets a component's memory. One implementation per engine
+ * backend; the BuiltinBridge holds one and both `resolvePtrSetter` and
+ * `resolvePtrGetter` go through it.
+ */
+export interface MemoryProvider {
+ /**
+ * Resolve a per-entity heap-view filler for `cppName`, or null if this backend
+ * has no fast-path binding for the component (the bridge then falls back to the
+ * method-based path).
+ */
+ resolveComponentHeap(cppName: string): ComponentHeapResolver | null;
+}
+
+/**
+ * Resolve the wasm-exported pointer function for `cppName` — `(entity) => byte
+ * offset of that entity's component in the wasm heap`, or null if the module lacks
+ * the export or the component has no layout. Shared by WasmMemoryProvider and the
+ * bridge's (web-only) resolvePtrFn.
+ */
+export function resolveWasmPtrFn(
+ module: ESEngineModule | null,
+ cppRegistry: CppRegistry | null,
+ cppName: string,
+): ((entity: Entity) => number) | null {
+ const layout = PTR_LAYOUTS[cppName];
+ if (!layout || !module || !cppRegistry) return null;
+ const mod = module as unknown as Record<string, unknown>;
+ const fn = mod[layout.ptrFn] as ((r: CppRegistry, e: number) => number) | undefined;
+ if (!fn) return null;
+ return (e: Entity) => fn(cppRegistry, e);
+}
+
+/**
+ * Web/emscripten backend: the whole wasm HEAP, indexed by a per-entity byte
+ * offset. Behaviourally identical to the pre-abstraction inline path — same
+ * ptr function, same `mod.HEAP*` views, same "skip when ptr is 0".
+ */
+export class WasmMemoryProvider implements MemoryProvider {
+ constructor(
+ private readonly module: ESEngineModule,
+ private readonly cppRegistry: CppRegistry,
+ ) {}
+
+ resolveComponentHeap(cppName: string): ComponentHeapResolver | null {
+ const getPtrFn = resolveWasmPtrFn(this.module, this.cppRegistry, cppName);
+ if (!getPtrFn) return null;
+ const mod = this.module;
+ return (entity: Entity, out: ComponentHeap): boolean => {
+ const ptr = getPtrFn(entity);
+ if (!ptr) return false;
+ // HEAP* views are re-read each call: emscripten swaps them out on heap
+ // growth, so a cached reference can go stale.
+ out.f32 = mod.HEAPF32;
+ out.u32 = mod.HEAPU32;
+ out.u8 = mod.HEAPU8;
+ out.ptr = ptr;
+ return true;
+ };
+ }
+}
+
+/** A host-injected zero-copy accessor: `entity -> ArrayBuffer` over the native
+ * ECS component, or a nullish value when the entity has no live component. */
+export type NativeComponentBufferFn = (entity: number) => ArrayBuffer | null | undefined;
+
+/**
+ * Native (embedded-Dawn) backend: each component is reached through the host's
+ * generated `es_<Component>_buffer(entity)` binding, which hands back a zero-copy
+ * ArrayBuffer over that entity's native component. The accessors then write it at
+ * offset 0. `scope` is where those globals live (the QuickJS global object on a
+ * device; a plain object in tests).
+ *
+ * The buffer is re-fetched on every access on purpose: a SparseSet growth moves
+ * the dense array, invalidating any previously handed-out ArrayBuffer.
+ */
+export class NativeMemoryProvider implements MemoryProvider {
+ constructor(
+ private readonly scope: Record<string, unknown> =
+ globalThis as unknown as Record<string, unknown>,
+ ) {}
+
+ resolveComponentHeap(cppName: string): ComponentHeapResolver | null {
+ const bufFn = this.scope[`es_${cppName}_buffer`] as NativeComponentBufferFn | undefined;
+ if (typeof bufFn !== 'function') return null;
+ return (entity: Entity, out: ComponentHeap): boolean => {
+ const buf = bufFn(entity);
+ if (!buf) return false;
+ out.f32 = new Float32Array(buf);
+ out.u32 = new Uint32Array(buf);
+ out.u8 = new Uint8Array(buf);
+ out.ptr = 0;
+ return true;
+ };
+ }
+}
diff --git a/sdk/src/index.native.ts b/sdk/src/index.native.ts
index 677e8d417..f52be1739 100644
--- a/sdk/src/index.native.ts
+++ b/sdk/src/index.native.ts
@@ -37,6 +37,13 @@ export * from './webAppFactory';
export { NativePlatformAdapter, installNativePlatform } from './platform/native';
export type { NativeBridge, NativeInputListener, NativeFetchResult } from './platform/native';
+// Fast-path memory backend for the native core. The shell builds one over its
+// host-injected `es_<Component>_buffer` bindings and passes it to the bridge
+// (BuiltinBridge.connect's `memory` option), so the real SDK component API reads
+// and writes native ECS memory through the same generated ptrAccessors as web.
+export { NativeMemoryProvider } from './ecs/memoryProvider';
+export type { MemoryProvider, ComponentHeap, NativeComponentBufferFn } from './ecs/memoryProvider';
+
// 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/memory-provider.test.ts b/sdk/tests/memory-provider.test.ts
new file mode 100644
index 000000000..9d7a257f8
--- /dev/null
+++ b/sdk/tests/memory-provider.test.ts
@@ -0,0 +1,149 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file memory-provider.test.ts
+ * @brief The fast-path memory backend seam. The generated ptrAccessors are the
+ * one marshalling path; only where the heap views come from differs by
+ * backend. These tests drive resolvePtrSetter/Getter through both:
+ * * WasmMemoryProvider — whole wasm HEAP + a per-entity byte offset;
+ * * NativeMemoryProvider — a zero-copy ArrayBuffer over one native
+ * component (the host's es_<Component>_buffer), offset 0.
+ * The parity test proves both write byte-identical component memory for
+ * the same input — the crux of "one SDK, two backends". No device.
+ */
+import { describe, expect, it } from 'vitest';
+import { BuiltinBridge } from '../src/ecs/BuiltinBridge';
+import { NativeMemoryProvider } from '../src/ecs/memoryProvider';
+import { PTR_LAYOUTS } from '../src/ptrLayouts.generated';
+import { PTR_ACCESSORS } from '../src/ecs/ptrAccessors.generated';
+import type { CppRegistry, ESEngineModule } from '../src/wasm';
+
+const CPP = 'Sprite';
+const layout = PTR_LAYOUTS[CPP];
+const accessor = PTR_ACCESSORS[CPP];
+
+// resolvePtr* never call registry methods, so any non-null value is enough.
+const REG = {} as unknown as CppRegistry;
+
+// A byte window comfortably larger than a Sprite (~92 B), used as both the native
+// component buffer and the web heap slot so the two are directly comparable.
+const SLOT = 256;
+
+/** Representative data spanning color / vec2 / bool, over the generated defaults.
+ * Values are exactly representable in f32 so the stored-and-read round-trip is
+ * exact (component fields are f32; e.g. 0.1 would round). */
+function sampleData(): Record<string, unknown> {
+ const d = accessor.create() as Record<string, unknown>;
+ d.color = { r: 0.5, g: 0.25, b: 0.125, a: 1 };
+ d.size = { x: 12, y: 34 };
+ d.lit = true;
+ return d;
+}
+
+/** A fake ESEngineModule: HEAP views over `heap` + the wasm ptr export returning
+ * a fixed byte offset for the (single) test entity. */
+function wasmModule(heap: ArrayBuffer, offset: number): ESEngineModule {
+ return {
+ HEAPF32: new Float32Array(heap),
+ HEAPU32: new Uint32Array(heap),
+ HEAPU8: new Uint8Array(heap),
+ [layout.ptrFn]: (_reg: unknown, _e: number) => offset,
+ } as unknown as ESEngineModule;
+}
+
+describe('MemoryProvider', () => {
+ it('has the Sprite fixture (layout + accessor)', () => {
+ expect(layout).toBeDefined();
+ expect(accessor).toBeDefined();
+ });
+
+ it('WasmMemoryProvider (derived from module) writes/reads at the entity ptr offset', () => {
+ const heap = new ArrayBuffer(1024);
+ const offset = SLOT; // pretend the component lives here
+ const bridge = new BuiltinBridge();
+ bridge.connect(REG, wasmModule(heap, offset));
+
+ const set = bridge.resolvePtrSetter(CPP);
+ const get = bridge.resolvePtrGetter(CPP);
+ expect(set).toBeTypeOf('function');
+ expect(get).toBeTypeOf('function');
+
+ const data = sampleData();
+ set!(1, data);
+ const read = get!(1) as Record<string, unknown>;
+ expect(read.color).toEqual(data.color);
+ expect(read.size).toEqual(data.size);
+ expect(read.lit).toBe(true);
+
+ // Wrote at the offset, not at 0.
+ expect([...new Uint8Array(heap, 0, 8)]).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
+ });
+
+ it('NativeMemoryProvider round-trips through es_<C>_buffer with the same accessors', () => {
+ const comp = new ArrayBuffer(SLOT); // one native Sprite component
+ const scope = { [`es_${CPP}_buffer`]: (_e: number) => comp };
+ const bridge = new BuiltinBridge();
+ bridge.connect(REG, undefined, { memory: new NativeMemoryProvider(scope) });
+
+ const set = bridge.resolvePtrSetter(CPP);
+ const get = bridge.resolvePtrGetter(CPP);
+ expect(set).toBeTypeOf('function');
+
+ const data = sampleData();
+ set!(7, data);
+ const read = get!(7) as Record<string, unknown>;
+ expect(read.color).toEqual(data.color);
+ expect(read.size).toEqual(data.size);
+ expect(read.lit).toBe(true);
+ });
+
+ it('web and native backends write byte-identical component memory', () => {
+ const data = sampleData();
+
+ // web: component at offset SLOT within a larger heap.
+ const heap = new ArrayBuffer(SLOT * 2);
+ const web = new BuiltinBridge();
+ web.connect(REG, wasmModule(heap, SLOT));
+ web.resolvePtrSetter(CPP)!(1, data);
+ const webBytes = [...new Uint8Array(heap, SLOT, SLOT)];
+
+ // native: component at offset 0 of its own buffer.
+ const comp = new ArrayBuffer(SLOT);
+ const native = new BuiltinBridge();
+ native.connect(REG, undefined, {
+ memory: new NativeMemoryProvider({ [`es_${CPP}_buffer`]: () => comp }),
+ });
+ native.resolvePtrSetter(CPP)!(1, data);
+ const nativeBytes = [...new Uint8Array(comp)];
+
+ expect(nativeBytes).toEqual(webBytes);
+ });
+
+ it('NativeMemoryProvider skips an entity with no live component (nullish buffer)', () => {
+ const scope = { [`es_${CPP}_buffer`]: (_e: number) => null };
+ const bridge = new BuiltinBridge();
+ bridge.connect(REG, undefined, { memory: new NativeMemoryProvider(scope) });
+ const get = bridge.resolvePtrGetter(CPP);
+ expect(get).toBeTypeOf('function');
+ expect(get!(1)).toBeNull(); // no throw, no read
+ });
+
+ it('no module and no memory override => no fast path (unchanged web fallback)', () => {
+ const bridge = new BuiltinBridge();
+ bridge.connect(REG); // no module, no memory
+ expect(bridge.resolvePtrSetter(CPP)).toBeNull();
+ expect(bridge.resolvePtrGetter(CPP)).toBeNull();
+ expect(bridge.resolvePtrFn(CPP)).toBeNull();
+ });
+
+ it('disconnect tears down the fast path', () => {
+ const comp = new ArrayBuffer(SLOT);
+ const bridge = new BuiltinBridge();
+ bridge.connect(REG, undefined, {
+ memory: new NativeMemoryProvider({ [`es_${CPP}_buffer`]: () => comp }),
+ });
+ expect(bridge.resolvePtrSetter(CPP)).toBeTypeOf('function');
+ bridge.disconnect();
+ expect(bridge.resolvePtrSetter(CPP)).toBeNull();
+ });
+});