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.

refactor(ui): the UI runs on whichever core is present, not on the wasm module

yhha401b2caa2c0
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1feb6f695..957380af3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -261,6 +261,7 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
src/esengine/bindings/EngineContext.cpp
src/esengine/bindings/ResourceManagerBindings.cpp
src/esengine/bindings/RendererBindings.cpp
+ src/esengine/bindings/UIBindings.cpp
src/esengine/bindings/ImmediateDrawBindings.cpp
src/esengine/bindings/GeometryBindings.cpp
${GENERATED_WEB_BINDINGS}
diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.js
index ff3900e23..27f0a9bf7 100644
--- a/build-tools/tasks/native.js
+++ b/build-tools/tasks/native.js
@@ -39,7 +39,7 @@ async function generateNativeBindings(rootDir, genDir, python) {
// the binding TUs themselves, which this build compiles (see ESEngineSources).
async function generateNativeFunctionBindings(rootDir, genDir, python) {
const out = path.join(genDir, 'NativeFunctionBindings.generated.cpp');
- const headers = ['RendererBindings.hpp'].map(
+ const headers = ['RendererBindings.hpp', 'UIBindings.hpp'].map(
(h) => path.join(rootDir, 'src', 'esengine', 'bindings', h));
await runCommand(python, [
path.join(rootDir, 'tools', 'eht.py'),
diff --git a/cmake/ESEngineSources.cmake b/cmake/ESEngineSources.cmake
index 52bf9c95f..ce536d0aa 100644
--- a/cmake/ESEngineSources.cmake
+++ b/cmake/ESEngineSources.cmake
@@ -58,6 +58,7 @@ endif()
if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
list(APPEND ESENGINE_SOURCES
${ESENGINE_ROOT}/src/esengine/bindings/RendererBindings.cpp
+ ${ESENGINE_ROOT}/src/esengine/bindings/UIBindings.cpp
# activeCtx()'s unset fallback. A host that installs its own context (the
# native one does, at boot) never reaches it, but the inline accessor
# references it, so the definition has to link.
diff --git a/native/host_js/host_core.cpp b/native/host_js/host_core.cpp
index 2e768257b..1981f5bfd 100644
--- a/native/host_js/host_core.cpp
+++ b/native/host_js/host_core.cpp
@@ -811,6 +811,14 @@ void logJsError(JSContext* ctx, const char* where) {
const char* s = JS_ToCString(ctx, e);
LOGE("JS error in %s: %s", where, s ? s : "?");
if (s) JS_FreeCString(ctx, s);
+ // The stack too: a bare message ("Maximum call stack size exceeded") says
+ // nothing about which SDK path produced it, and a device is where you find out.
+ JSValue stack = JS_GetPropertyStr(ctx, e, "stack");
+ if (!JS_IsUndefined(stack) && !JS_IsException(stack)) {
+ const char* st = JS_ToCString(ctx, stack);
+ if (st) { LOGE(" stack: %s", st); JS_FreeCString(ctx, st); }
+ }
+ JS_FreeValue(ctx, stack);
JS_FreeValue(ctx, e);
}
void evalJs(App& a, const char* src, const char* name) {
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 25660a269..0f6eb28ea 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1334 stable · 17 beta · 1 deprecated
+Symbols: 1335 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -2472,6 +2472,11 @@ Point = 0
Rectangle = 2
```
+## EngineApi — type
+```
+NativeEngineApi
+```
+
## Entity — type
```
number
@@ -10088,7 +10093,7 @@ TrailPlugin
## uiHitTestWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
```
## uiInteractionPlugin — const
@@ -10113,12 +10118,12 @@ UIMaskPlugin
## uiPickAllWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity[]
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity[]
```
## uiPickWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity | null
```
## uiPlugin — const
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 9eb4e7518..1b2eb1bc9 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: 1353 stable · 22 beta · 1 deprecated
+Symbols: 1354 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -2480,6 +2480,11 @@ Point = 0
Rectangle = 2
```
+## EngineApi — type
+```
+NativeEngineApi
+```
+
## Entity — type
```
number
@@ -10295,7 +10300,7 @@ TrailPlugin
## uiHitTestWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
```
## uiInteractionPlugin — const
@@ -10320,12 +10325,12 @@ UIMaskPlugin
## uiPickAllWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity[]
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity[]
```
## uiPickWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity | null
```
## uiPlugin — const
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 7b0b5a060..fe7a0cb0f 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1333 stable · 19 beta · 1 deprecated
+Symbols: 1334 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2467,6 +2467,11 @@ Point = 0
Rectangle = 2
```
+## EngineApi — type
+```
+NativeEngineApi
+```
+
## Entity — type
```
number
@@ -10093,7 +10098,7 @@ TrailPlugin
## uiHitTestWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
```
## uiInteractionPlugin — const
@@ -10118,12 +10123,12 @@ UIMaskPlugin
## uiPickAllWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity[]
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity[]
```
## uiPickWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity | null
```
## uiPlugin — const
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 81a062d16..9d06b6532 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1354 stable · 17 beta · 1 deprecated
+Symbols: 1355 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2467,6 +2467,11 @@ Point = 0
Rectangle = 2
```
+## EngineApi — type
+```
+NativeEngineApi
+```
+
## Entity — type
```
number
@@ -10313,7 +10318,7 @@ TrailPlugin
## uiHitTestWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
```
## uiInteractionPlugin — const
@@ -10338,12 +10343,12 @@ UIMaskPlugin
## uiPickAllWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity[]
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity[]
```
## uiPickWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity | null
```
## uiPlugin — const
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index a13c1ccd4..aabaf479b 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1344 stable · 17 beta · 1 deprecated
+Symbols: 1345 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2467,6 +2467,11 @@ Point = 0
Rectangle = 2
```
+## EngineApi — type
+```
+NativeEngineApi
+```
+
## Entity — type
```
number
@@ -10112,7 +10117,7 @@ TrailPlugin
## uiHitTestWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number, mouseDown?: boolean, mousePressed?: boolean, mouseReleased?: boolean): Entity | null
```
## uiInteractionPlugin — const
@@ -10137,12 +10142,12 @@ UIMaskPlugin
## uiPickAllWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity[]
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity[]
```
## uiPickWorld — function
```
-(module: ESEngineModule, registry: CppRegistry, worldX: number, worldY: number): Entity | null
+(engine: EngineApi | null, registry: CppRegistry, worldX: number, worldY: number): Entity | null
```
## uiPlugin — const
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index a3759b878..eac36e7ef 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -259,6 +259,11 @@ export {
export { corePlugin, DEFAULT_UI_CAMERA_INFO } from './corePlugin';
+// The engine entry points a plugin may call, from whichever core is present (the
+// wasm module on the web, a native host's bindings on a device) — the parameter
+// type the UI pick helpers take. @beta while the native host is unshipped.
+export type { EngineApi } from './ecs/engineApi';
+
// =============================================================================
// App Context
// =============================================================================
diff --git a/sdk/src/ecs/engineApi.ts b/sdk/src/ecs/engineApi.ts
new file mode 100644
index 000000000..62943b946
--- /dev/null
+++ b/sdk/src/ecs/engineApi.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ecs/engineApi.ts
+ * @brief Whichever engine core is present, by one set of names.
+ *
+ * A plugin that drives the engine — UI layout, hit testing, render order — used
+ * to reach it as `app.wasmModule.uiLayout_update(...)`, which is a statement
+ * about HOW the core is embedded, not about what the plugin wants. On a device
+ * there is no wasm module, so every such plugin was web-only by construction.
+ *
+ * `engineApi(app)` answers with the module on the web and with the native host's
+ * bindings on a device. Both spell the entry points the same way, because both
+ * come from the same C++ declarations: embind registers them for the module, and
+ * EHT generates the native side (see nativeEngineApi.generated.ts).
+ *
+ * Members are optional — a core answers what it compiles — so call sites read
+ * `api.uiLayout_update?.(…)`, which is also how they treat an engine build that
+ * left a subsystem out.
+ */
+
+import type { App } from '../app';
+import type { NativeEngineApi } from './nativeEngineApi.generated';
+
+/** The engine surface a plugin may call, from either core. */
+export type EngineApi = NativeEngineApi;
+
+let native_: NativeEngineApi | null = null;
+
+/** Install the native host's engine API (by the native runtime); null clears it. */
+export function setNativeEngineApi(api: NativeEngineApi | null): void {
+ native_ = api;
+}
+
+/**
+ * The engine entry points for this app: the wasm module when there is one, else
+ * the native host's bindings. Null only when neither exists (a pure logic host),
+ * which every call site already handles by optional-chaining its call.
+ */
+export function engineApi(app: App): EngineApi | null {
+ return (app.wasmModule as EngineApi | null) ?? native_;
+}
diff --git a/sdk/src/ecs/nativeEngineApi.generated.ts b/sdk/src/ecs/nativeEngineApi.generated.ts
new file mode 100644
index 000000000..83cf146bb
--- /dev/null
+++ b/sdk/src/ecs/nativeEngineApi.generated.ts
@@ -0,0 +1,209 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Auto-generated by EHT (native_functions) — DO NOT EDIT.
+//
+// The engine entry points a native (embedded-Dawn) host binds, named as the
+// wasm module names them — so an SDK plugin calls `api.uiLayout_update(...)`
+// and reaches whichever core is present. Generated from the SAME bindings
+// headers embind registers from, so the two surfaces cannot drift.
+//
+// Every member is optional: a core answers what it compiles. Entry points that
+// take a heap pointer are NOT here — those need a real backend that decides how
+// bytes cross (see RendererBackend), not a name forwarded.
+
+export interface NativeEngineApi {
+ engine_setCpuProfiling?(on: boolean): void;
+ getUINodeComputedHeight?(registry: unknown, entity: number): number;
+ getUINodeComputedWidth?(registry: unknown, entity: number): number;
+ getUINodeHiddenInTree?(registry: unknown, entity: number): boolean;
+ gl_enableErrorCheck?(enabled: boolean): void;
+ particle_getAliveCount?(entity: number): number;
+ particle_play?(registry: unknown, entity: number): void;
+ particle_reset?(registry: unknown, entity: number): void;
+ particle_stop?(registry: unknown, entity: number): void;
+ particle_update?(registry: unknown, dt: number): void;
+ registry_getCanvasEntity?(registry: unknown): number;
+ registry_getGeneration?(registry: unknown, entity: number): number;
+ renderFrame?(registry: unknown, viewportWidth: number, viewportHeight: number): void;
+ renderer_beginFrame?(elapsedSec: number): void;
+ renderer_captureNextFrame?(): void;
+ renderer_clearAllClipRects?(): void;
+ renderer_clearAllStencilMasks?(): void;
+ renderer_clearEntityClipRect?(entity: number): void;
+ renderer_clearEntityStencilMask?(entity: number): void;
+ renderer_createTarget?(width: number, height: number, flags: number): number;
+ renderer_diagnose?(): void;
+ renderer_end?(): void;
+ renderer_flush?(): void;
+ renderer_getCapturedCameraCount?(): number;
+ renderer_getCapturedEntityCount?(): number;
+ renderer_getCapturedFrameSize?(): number;
+ renderer_getCulled?(): number;
+ renderer_getDrawCalls?(): number;
+ renderer_getGpuTimeMs?(): number;
+ renderer_getMeshes?(): number;
+ renderer_getPreviewHeight?(): number;
+ renderer_getPreviewSize?(): number;
+ renderer_getPreviewWidth?(): number;
+ renderer_getSnapshotHeight?(): number;
+ renderer_getSnapshotSize?(): number;
+ renderer_getSnapshotWidth?(): number;
+ renderer_getSpine?(): number;
+ renderer_getSprites?(): number;
+ renderer_getTargetDepthTexture?(handle: number): number;
+ renderer_getTargetTexture?(handle: number): number;
+ renderer_getText?(): number;
+ renderer_getTextureBytes?(): number;
+ renderer_getTriangles?(): number;
+ renderer_hasCapturedData?(): boolean;
+ renderer_init?(width: number, height: number): void;
+ renderer_pollPreviewReadback?(): number;
+ renderer_pollSnapshotReadback?(): number;
+ renderer_releaseTarget?(handle: number): void;
+ renderer_renderMaterialPreview?(materialId: number, w: number, h: number): void;
+ renderer_replayToDrawCall?(drawCallIndex: number): void;
+ renderer_resize?(width: number, height: number): void;
+ renderer_setClearColor?(r: number, g: number, b: number, a: number): void;
+ renderer_setColorSpace?(linear: number): void;
+ renderer_setEntityClipRect?(entity: number, x: number, y: number, w: number, h: number): void;
+ renderer_setEntityStencilMask?(entity: number, refValue: number): void;
+ renderer_setEntityStencilTest?(entity: number, refValue: number): void;
+ renderer_setStage?(stage: number): void;
+ renderer_setTextureParams?(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void;
+ renderer_setViewport?(x: number, y: number, w: number, h: number): void;
+ renderer_setYSortLayers?(mask: number): void;
+ renderer_submitAll?(registry: unknown, skipFlags: number, vpX: number, vpY: number, vpW: number, vpH: number): void;
+ renderer_submitBitmapText?(registry: unknown): void;
+ renderer_submitParticles?(registry: unknown): void;
+ renderer_submitShapes?(registry: unknown): void;
+ renderer_submitSpine?(registry: unknown): void;
+ renderer_submitSprites?(registry: unknown): void;
+ renderer_submitUIElements?(registry: unknown): void;
+ renderer_updateTransforms?(registry: unknown): void;
+ trail_clear?(registry: unknown, entity: number): void;
+ trail_update?(registry: unknown, dt: number): void;
+ transform_patchPosition?(registry: unknown, entity: number, x: number, y: number, z: number): void;
+ transform_update?(registry: unknown): void;
+ uiFlexLayout_update?(registry: unknown): void;
+ uiHitTest_getHitEntity?(): number;
+ uiHitTest_getHitEntityPrev?(): number;
+ uiHitTest_pick?(registry: unknown, worldX: number, worldY: number): number;
+ uiHitTest_pickAll?(registry: unknown, worldX: number, worldY: number): number;
+ uiHitTest_pickResult?(index: number): number;
+ uiHitTest_update?(registry: unknown, mouseWorldX: number, mouseWorldY: number, mouseDown: boolean, mousePressed: boolean, mouseReleased: boolean): void;
+ uiLayout_update?(registry: unknown, camLeft: number, camBottom: number, camRight: number, camTop: number, propertyDirty: boolean): void;
+ uiNode_computedHeight?(registry: unknown, entity: number): number;
+ uiNode_computedWidth?(registry: unknown, entity: number): number;
+ uiRenderOrder_update?(registry: unknown): void;
+ uiTree_markAllDirty?(): void;
+ uiTree_markDirty?(entity: number): void;
+ uiTree_markStructureDirty?(): void;
+ ui_getRenderOrder?(registry: unknown, entity: number): number;
+}
+
+// Not forwarded (they take a heap pointer): mesh2d_setGeometry, particle_set_color_lut, particle_set_size_lut, registry_batchSyncPhysicsTransforms, renderFrameWithMatrix, renderer_begin, renderer_submitSpineBatch, renderer_submitSpineBatchByEntity, renderer_submitTextBatch.
+
+/** Build the API over a host scope (the QuickJS global object; a plain object
+ * in tests). A name the host did not bind simply stays absent. */
+export function createNativeEngineApi(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): NativeEngineApi {
+ const api: Record<string, unknown> = {};
+ const bind = (name: string, host: string, dropFirst: boolean): void => {
+ const fn = scope[host];
+ if (typeof fn !== 'function') return;
+ const call = fn as (...a: unknown[]) => unknown;
+ api[name] = dropFirst
+ ? (_registry: unknown, ...args: unknown[]) => call(...args)
+ : (...args: unknown[]) => call(...args);
+ };
+ bind('engine_setCpuProfiling', 'es_engine_setCpuProfiling', false);
+ bind('getUINodeComputedHeight', 'es_getUINodeComputedHeight', true);
+ bind('getUINodeComputedWidth', 'es_getUINodeComputedWidth', true);
+ bind('getUINodeHiddenInTree', 'es_getUINodeHiddenInTree', true);
+ bind('gl_enableErrorCheck', 'es_gl_enableErrorCheck', false);
+ bind('particle_getAliveCount', 'es_particle_getAliveCount', false);
+ bind('particle_play', 'es_particle_play', true);
+ bind('particle_reset', 'es_particle_reset', true);
+ bind('particle_stop', 'es_particle_stop', true);
+ bind('particle_update', 'es_particle_update', true);
+ bind('registry_getCanvasEntity', 'es_registry_getCanvasEntity', true);
+ bind('registry_getGeneration', 'es_registry_getGeneration', true);
+ bind('renderFrame', 'es_renderFrame', true);
+ bind('renderer_beginFrame', 'es_renderer_beginFrame', false);
+ bind('renderer_captureNextFrame', 'es_renderer_captureNextFrame', false);
+ bind('renderer_clearAllClipRects', 'es_renderer_clearAllClipRects', false);
+ bind('renderer_clearAllStencilMasks', 'es_renderer_clearAllStencilMasks', false);
+ bind('renderer_clearEntityClipRect', 'es_renderer_clearEntityClipRect', false);
+ bind('renderer_clearEntityStencilMask', 'es_renderer_clearEntityStencilMask', false);
+ bind('renderer_createTarget', 'es_renderer_createTarget', false);
+ bind('renderer_diagnose', 'es_renderer_diagnose', false);
+ bind('renderer_end', 'es_renderer_end', false);
+ bind('renderer_flush', 'es_renderer_flush', false);
+ bind('renderer_getCapturedCameraCount', 'es_renderer_getCapturedCameraCount', false);
+ bind('renderer_getCapturedEntityCount', 'es_renderer_getCapturedEntityCount', false);
+ bind('renderer_getCapturedFrameSize', 'es_renderer_getCapturedFrameSize', false);
+ bind('renderer_getCulled', 'es_renderer_getCulled', false);
+ bind('renderer_getDrawCalls', 'es_renderer_getDrawCalls', false);
+ bind('renderer_getGpuTimeMs', 'es_renderer_getGpuTimeMs', false);
+ bind('renderer_getMeshes', 'es_renderer_getMeshes', false);
+ bind('renderer_getPreviewHeight', 'es_renderer_getPreviewHeight', false);
+ bind('renderer_getPreviewSize', 'es_renderer_getPreviewSize', false);
+ bind('renderer_getPreviewWidth', 'es_renderer_getPreviewWidth', false);
+ bind('renderer_getSnapshotHeight', 'es_renderer_getSnapshotHeight', false);
+ bind('renderer_getSnapshotSize', 'es_renderer_getSnapshotSize', false);
+ bind('renderer_getSnapshotWidth', 'es_renderer_getSnapshotWidth', false);
+ bind('renderer_getSpine', 'es_renderer_getSpine', false);
+ bind('renderer_getSprites', 'es_renderer_getSprites', false);
+ bind('renderer_getTargetDepthTexture', 'es_renderer_getTargetDepthTexture', false);
+ bind('renderer_getTargetTexture', 'es_renderer_getTargetTexture', false);
+ bind('renderer_getText', 'es_renderer_getText', false);
+ bind('renderer_getTextureBytes', 'es_renderer_getTextureBytes', false);
+ bind('renderer_getTriangles', 'es_renderer_getTriangles', false);
+ bind('renderer_hasCapturedData', 'es_renderer_hasCapturedData', false);
+ bind('renderer_init', 'es_renderer_init', false);
+ bind('renderer_pollPreviewReadback', 'es_renderer_pollPreviewReadback', false);
+ bind('renderer_pollSnapshotReadback', 'es_renderer_pollSnapshotReadback', false);
+ bind('renderer_releaseTarget', 'es_renderer_releaseTarget', false);
+ bind('renderer_renderMaterialPreview', 'es_renderer_renderMaterialPreview', false);
+ bind('renderer_replayToDrawCall', 'es_renderer_replayToDrawCall', false);
+ bind('renderer_resize', 'es_renderer_resize', false);
+ bind('renderer_setClearColor', 'es_renderer_setClearColor', false);
+ bind('renderer_setColorSpace', 'es_renderer_setColorSpace', false);
+ bind('renderer_setEntityClipRect', 'es_renderer_setEntityClipRect', false);
+ bind('renderer_setEntityStencilMask', 'es_renderer_setEntityStencilMask', false);
+ bind('renderer_setEntityStencilTest', 'es_renderer_setEntityStencilTest', false);
+ bind('renderer_setStage', 'es_renderer_setStage', false);
+ bind('renderer_setTextureParams', 'es_renderer_setTextureParams', false);
+ bind('renderer_setViewport', 'es_renderer_setViewport', false);
+ bind('renderer_setYSortLayers', 'es_renderer_setYSortLayers', false);
+ bind('renderer_submitAll', 'es_renderer_submitAll', true);
+ bind('renderer_submitBitmapText', 'es_renderer_submitBitmapText', true);
+ bind('renderer_submitParticles', 'es_renderer_submitParticles', true);
+ bind('renderer_submitShapes', 'es_renderer_submitShapes', true);
+ bind('renderer_submitSpine', 'es_renderer_submitSpine', true);
+ bind('renderer_submitSprites', 'es_renderer_submitSprites', true);
+ bind('renderer_submitUIElements', 'es_renderer_submitUIElements', true);
+ bind('renderer_updateTransforms', 'es_renderer_updateTransforms', true);
+ bind('trail_clear', 'es_trail_clear', true);
+ bind('trail_update', 'es_trail_update', true);
+ bind('transform_patchPosition', 'es_transform_patchPosition', true);
+ bind('transform_update', 'es_transform_update', true);
+ bind('uiFlexLayout_update', 'es_uiFlexLayout_update', true);
+ bind('uiHitTest_getHitEntity', 'es_uiHitTest_getHitEntity', false);
+ bind('uiHitTest_getHitEntityPrev', 'es_uiHitTest_getHitEntityPrev', false);
+ bind('uiHitTest_pick', 'es_uiHitTest_pick', true);
+ bind('uiHitTest_pickAll', 'es_uiHitTest_pickAll', true);
+ bind('uiHitTest_pickResult', 'es_uiHitTest_pickResult', false);
+ bind('uiHitTest_update', 'es_uiHitTest_update', true);
+ bind('uiLayout_update', 'es_uiLayout_update', true);
+ bind('uiNode_computedHeight', 'es_uiNode_computedHeight', true);
+ bind('uiNode_computedWidth', 'es_uiNode_computedWidth', true);
+ bind('uiRenderOrder_update', 'es_uiRenderOrder_update', true);
+ bind('uiTree_markAllDirty', 'es_uiTree_markAllDirty', false);
+ bind('uiTree_markDirty', 'es_uiTree_markDirty', false);
+ bind('uiTree_markStructureDirty', 'es_uiTree_markStructureDirty', false);
+ bind('ui_getRenderOrder', 'es_ui_getRenderOrder', true);
+ return api as NativeEngineApi;
+}
diff --git a/sdk/src/ecs/nativeRuntime.ts b/sdk/src/ecs/nativeRuntime.ts
index fc601e1c7..0f6beb283 100644
--- a/sdk/src/ecs/nativeRuntime.ts
+++ b/sdk/src/ecs/nativeRuntime.ts
@@ -23,12 +23,14 @@ import { NativeMemoryProvider } from './memoryProvider';
import { createNativeResourceManager } from './nativeResourceManager';
import { HOST_FLAGS, TEXT_BINDINGS, hasTextBindings, hasRendererBindings } from './nativeBindings';
import { createNativeRendererBackend, nativeSurfaceSize } from './nativeRenderer';
+import { createNativeEngineApi } from './nativeEngineApi.generated';
+import { setNativeEngineApi } from './engineApi';
import { setRendererBackend } from '../renderer';
import { RenderPipeline } from '../renderPipeline';
import { cameraPlugin } from '../camera/CameraPlugin';
import { UICameraInfo } from '../ui/core/ui-camera-info';
import { DEFAULT_UI_CAMERA_INFO } from '../corePlugin';
-import { textPlugin } from '../ui/text/plugin';
+import { uiPlugin } from '../ui/ui-plugin';
import { setNativeTextSubmit } from '../ui/text/submit';
import { initResourceManager } from '../resourceManager';
import { Assets as AssetsClass } from '../asset/Assets';
@@ -86,9 +88,10 @@ export function createNativeApp(
// cannot be shared as-is — it wires the wasm heap — so installNativeAssets
// builds the equivalent over the native ResourceManager; prefabs and scene
// loading declare Assets as a required resource, so it precedes them.
+ installNativeEngine(scope);
installNativeRenderer(app, scope);
installNativeAssets(app, scope);
- installNativeText(app, scope);
+ installNativeUI(app, scope);
app.addPlugin(inputPlugin);
app.addPlugin(prefabsPlugin);
app.addPlugin(sceneManagerPlugin);
@@ -124,6 +127,14 @@ export function createNativeApp(
* swapchain and the present. Gated on the host having bound the whole surface, so
* a host that still drives its own frame keeps working.
*/
+function installNativeEngine(scope: Record<string, unknown>): void {
+ // The engine entry points, by the names the wasm module uses — generated from
+ // the same C++ declarations embind registers (nativeEngineApi.generated.ts).
+ // With this installed, a plugin that calls uiLayout_update / uiHitTest_* /
+ // uiRenderOrder_update reaches the native core without knowing it is native.
+ setNativeEngineApi(createNativeEngineApi(scope));
+}
+
function installNativeRenderer(app: App, scope: Record<string, unknown>): void {
if (!hasRendererBindings(scope)) return;
setRendererBackend(createNativeRendererBackend(scope));
@@ -138,22 +149,21 @@ function installNativeRenderer(app: App, scope: Record<string, unknown>): void {
}
/**
- * Install text — the same `TextPlugin` the web build runs, over the native core.
- *
- * Two things it cannot take from the web: a glyph source (the device has no 2D
- * canvas — the host's font stack answers, through `PlatformAdapter.rasterizeGlyph`)
- * and a way to hand the laid-out quads to the renderer (no wasm heap — the host
- * takes the typed arrays and calls `RenderFrame::submitTextBatch` itself).
- * Everything between, atlas through batching, is the SDK's one implementation.
+ * Install the UI — the same `uiPlugin` the web build runs: layout, masks, safe
+ * area, text, interaction, behavior, drag, focus and render order.
*
- * The plugin draws from the pipeline's pre-flush callback — the one
- * {@link installNativeRenderer} installed, run between collecting the scene and
- * flushing it, exactly where the web pipeline runs it.
+ * The plugins drive the engine through {@link engineApi}, which answers with the
+ * native host's bindings here and with the wasm module on the web, so none of
+ * them had to learn about a second core. Two things text cannot take from the
+ * web are the glyph source (the device has no 2D canvas — the host's font stack
+ * answers through `PlatformAdapter.rasterizeGlyph`) and the batch submit (no wasm
+ * heap — the host takes the typed arrays and calls `RenderFrame::submitTextBatch`
+ * itself); everything between, atlas through batching, is one implementation.
*
- * Gated on the host having bound the whole text surface: one that has not simply
- * draws no text, exactly as a host without an audio device stays silent.
+ * Gated on the host having bound the text surface: one that has not draws no
+ * text, exactly as a host without an audio device stays silent.
*/
-function installNativeText(app: App, scope: Record<string, unknown>): void {
+function installNativeUI(app: App, scope: Record<string, unknown>): void {
if (!hasTextBindings(scope)) return;
const submit = scope[TEXT_BINDINGS.submitTextBatch] as (
@@ -163,7 +173,7 @@ function installNativeText(app: App, scope: Record<string, unknown>): void {
setNativeTextSubmit((vertices, vertexCount, indices, textureId, transform, entity, layer, depth, sdf) => {
submit(vertices, vertexCount, indices, textureId, transform, entity, layer, depth, sdf);
});
- app.addPlugin(textPlugin);
+ app.addPlugin(uiPlugin);
}
function installNativeAssets(app: App, scope: Record<string, unknown>): void {
diff --git a/sdk/src/ui/input/focus.ts b/sdk/src/ui/input/focus.ts
index f60c6cc41..733d00dbb 100644
--- a/sdk/src/ui/input/focus.ts
+++ b/sdk/src/ui/input/focus.ts
@@ -19,7 +19,8 @@ import { walkParentChain } from '../util/helpers';
import { playModeOnly } from '../../env';
import { UIEvents, UIEventQueue, UIEventType } from '../core/events';
import { PluginName } from '../../systemLabels';
-import type { ESEngineModule, CppRegistry } from '../../wasm';
+import type { CppRegistry } from '../../wasm';
+import { engineApi } from '../../ecs/engineApi';
export class FocusPlugin implements Plugin {
name = PluginName.Focus;
@@ -29,16 +30,16 @@ export class FocusPlugin implements Plugin {
registerComponent('Focusable', Focusable);
const world = app.world;
- const module = app.wasmModule as ESEngineModule | undefined;
- const registry = module ? (world.getCppRegistry() as CppRegistry) : undefined;
+ const engine = engineApi(app);
+ const registry = engine ? (world.getCppRegistry() as CppRegistry) : undefined;
const focusManager = new FocusManagerState();
app.insertResource(FocusManager, focusManager);
// display:none removes an entity from rendering + hit-testing; the Tab
// ring must skip it too or focus lands on invisible controls.
const hiddenInTree = (e: Entity): boolean =>
- !!(module?.getUINodeHiddenInTree && registry
- && module.getUINodeHiddenInTree(registry, e));
+ !!(engine?.getUINodeHiddenInTree && registry
+ && engine.getUINodeHiddenInTree(registry, e));
// An open modal traps the Tab ring: only focusables inside an open
// UIDialog subtree participate while one is up (the scrim already
diff --git a/sdk/src/ui/input/interaction.ts b/sdk/src/ui/input/interaction.ts
index 5fc99822d..ebe703797 100644
--- a/sdk/src/ui/input/interaction.ts
+++ b/sdk/src/ui/input/interaction.ts
@@ -19,7 +19,8 @@ import type { InteractableData } from './interactable';
import { screenToUiWorld, uiHitTestWorld } from '../util/ui-pick';
import { platformDevicePixelRatio } from '../../platform';
import { ensureComponent, walkParentChain } from '../util/helpers';
-import type { ESEngineModule, CppRegistry } from '../../wasm';
+import type { CppRegistry } from '../../wasm';
+import { engineApi } from '../../ecs/engineApi';
import { UILayoutGeneration } from '../layout/ui-layout-generation';
import { SystemLabel, PluginName } from '../../systemLabels';
import type { UILayoutGenerationData } from '../layout/ui-layout-generation';
@@ -51,7 +52,7 @@ export class UIInteractionPlugin implements Plugin {
registerComponent('Interactable', Interactable);
const world = app.world;
- const module = app.wasmModule as ESEngineModule;
+ const engine = engineApi(app);
const registry = world.getCppRegistry() as CppRegistry;
const events = new UIEventQueue();
app.insertResource(UIEvents, events);
@@ -108,7 +109,7 @@ export class UIInteractionPlugin implements Plugin {
let hitEntity: Entity | null = hoveredEntity;
if (needsHitTest) {
hitEntity = uiHitTestWorld(
- module, registry,
+ engine, registry,
worldMouse.x, worldMouse.y,
mouseDown, mousePressed, mouseReleased,
);
diff --git a/sdk/src/ui/layout/layout.ts b/sdk/src/ui/layout/layout.ts
index d359280df..bca57a79e 100644
--- a/sdk/src/ui/layout/layout.ts
+++ b/sdk/src/ui/layout/layout.ts
@@ -21,8 +21,8 @@ import { UICameraInfo } from '../core/ui-camera-info';
import type { UICameraData } from '../core/ui-camera-info';
import { UILayoutGeneration } from './ui-layout-generation';
import type { UILayoutGenerationData } from './ui-layout-generation';
-import type { ESEngineModule } from '../../wasm';
import type { CppRegistry } from '../../wasm';
+import { engineApi } from '../../ecs/engineApi';
import { initUIHelpers } from '../util/helpers';
export class UILayoutPlugin implements Plugin {
@@ -34,10 +34,12 @@ export class UILayoutPlugin implements Plugin {
registerComponent('FlexContainer', FlexContainer);
const world = app.world;
- const module = app.wasmModule as ESEngineModule;
+ // The wasm module on the web, the native host's bindings on a device —
+ // the layout pass is the same either way.
+ const engine = engineApi(app);
const registry = world.getCppRegistry() as CppRegistry;
- initUIHelpers(module, registry);
+ initUIHelpers(engine, registry);
const layoutGen: UILayoutGenerationData = { generation: 0 };
app.insertResource(UILayoutGeneration, layoutGen);
@@ -66,19 +68,19 @@ export class UILayoutPlugin implements Plugin {
const layoutFn = (camera: UICameraData) => {
if (!camera.valid) return;
- module.uiLayout_update(
+ engine?.uiLayout_update?.(
registry,
camera.worldLeft, camera.worldBottom,
camera.worldRight, camera.worldTop,
propertyDirty(),
);
- module.transform_update(registry);
+ engine?.transform_update?.(registry);
layoutGen.generation++;
};
const layoutOnlyFn = (camera: UICameraData) => {
if (!camera.valid) return;
- module.uiLayout_update(
+ engine?.uiLayout_update?.(
registry,
camera.worldLeft, camera.worldBottom,
camera.worldRight, camera.worldTop,
diff --git a/sdk/src/ui/render/render-order.ts b/sdk/src/ui/render/render-order.ts
index d8f5e6261..9d8ba3f3d 100644
--- a/sdk/src/ui/render/render-order.ts
+++ b/sdk/src/ui/render/render-order.ts
@@ -2,7 +2,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { App, Plugin } from '../../app';
import { defineSystem, Schedule } from '../../system';
-import type { ESEngineModule, CppRegistry } from '../../wasm';
+import type { CppRegistry } from '../../wasm';
+import { engineApi } from '../../ecs/engineApi';
import { PluginName } from '../../systemLabels';
export class UIRenderOrderPlugin implements Plugin {
@@ -15,12 +16,12 @@ export class UIRenderOrderPlugin implements Plugin {
build(app: App): void {
const world = app.world;
- const module = app.wasmModule as ESEngineModule;
+ const engine = engineApi(app);
const registry = world.getCppRegistry() as CppRegistry;
app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(
[],
- () => { module.uiRenderOrder_update(registry); },
+ () => { engine?.uiRenderOrder_update?.(registry); },
{ name: 'UIRenderOrderSystem' }
));
}
diff --git a/sdk/src/ui/util/helpers.ts b/sdk/src/ui/util/helpers.ts
index 5c4dbc805..6427caa3b 100644
--- a/sdk/src/ui/util/helpers.ts
+++ b/sdk/src/ui/util/helpers.ts
@@ -1,20 +1,34 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { CoreApiBridge } from '../../CoreApiBridge';
import { Parent } from '../../component';
import type { ParentData, AnyComponentDef } from '../../component';
import type { Entity } from '../../types';
import type { World } from '../../world';
import { UIVisual, UIVisualType } from '../core/ui-visual';
-import type { ESEngineModule, CppRegistry } from '../../wasm';
+import type { CppRegistry } from '../../wasm';
+import type { EngineApi } from '../../ecs/engineApi';
+import { WasmBridge } from '../../WasmBridge';
+
+/** The helpers' view of the engine, guarded: after a wasm abort a call throws
+ * {@link WasmModuleAborted} instead of reaching a dead module. A native host's
+ * bindings pass through the same channel and simply never abort. */
+class UIHelpersBridge extends WasmBridge<NonNullable<EngineApi>> {
+ protected readonly label = 'uiHelpers';
+}
-const bridge = new CoreApiBridge('uiHelpers');
-let module_: ESEngineModule | null = null;
+const bridge = new UIHelpersBridge();
+let engine_: EngineApi | null = null;
let nativeRegistry_: CppRegistry | null = null;
-export function initUIHelpers(module: ESEngineModule, registry: CppRegistry): void {
- bridge.connect(module);
- module_ = bridge.module;
+/** Bind the helpers to this app's engine core (the wasm module on the web, the
+ * native host's bindings on a device) — see ecs/engineApi.ts. */
+export function initUIHelpers(engine: EngineApi | null, registry: CppRegistry): void {
+ if (engine) {
+ bridge.connect(engine);
+ engine_ = bridge.module;
+ } else {
+ engine_ = null;
+ }
nativeRegistry_ = registry;
}
@@ -47,16 +61,16 @@ export function getEntityDepth(world: World, entity: Entity): number {
/** Resolved px width of a UINode (its Yoga-computed size). 0 if unresolved. */
export function getUINodeWidth(entity: Entity): number {
- if (module_ && nativeRegistry_ && module_.getUINodeComputedWidth) {
- return module_.getUINodeComputedWidth(nativeRegistry_, entity);
+ if (engine_ && nativeRegistry_ && engine_.getUINodeComputedWidth) {
+ return engine_.getUINodeComputedWidth(nativeRegistry_, entity);
}
return 0;
}
/** Resolved px height of a UINode. 0 if unresolved. */
export function getUINodeHeight(entity: Entity): number {
- if (module_ && nativeRegistry_ && module_.getUINodeComputedHeight) {
- return module_.getUINodeComputedHeight(nativeRegistry_, entity);
+ if (engine_ && nativeRegistry_ && engine_.getUINodeComputedHeight) {
+ return engine_.getUINodeComputedHeight(nativeRegistry_, entity);
}
return 0;
}
diff --git a/sdk/src/ui/util/ui-pick.ts b/sdk/src/ui/util/ui-pick.ts
index 0e3a626a9..22ecf633c 100644
--- a/sdk/src/ui/util/ui-pick.ts
+++ b/sdk/src/ui/util/ui-pick.ts
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { Entity } from '../../types';
-import type { ESEngineModule, CppRegistry } from '../../wasm';
+import type { CppRegistry } from '../../wasm';
+import type { EngineApi } from '../../ecs/engineApi';
import type { UICameraData } from '../core/ui-camera-info';
import { screenToWorld, worldToScreen, createInvVPCache } from './math';
@@ -20,7 +21,7 @@ export function uiWorldToScreen(camera: UICameraData, worldX: number, worldY: nu
}
export function uiHitTestWorld(
- module: ESEngineModule,
+ engine: EngineApi | null,
registry: CppRegistry,
worldX: number,
worldY: number,
@@ -28,36 +29,37 @@ export function uiHitTestWorld(
mousePressed = false,
mouseReleased = false,
): Entity | null {
- module.uiHitTest_update(registry, worldX, worldY, mouseDown, mousePressed, mouseReleased);
- const hit = module.uiHitTest_getHitEntity();
+ if (!engine?.uiHitTest_update || !engine.uiHitTest_getHitEntity) return null;
+ engine.uiHitTest_update(registry, worldX, worldY, mouseDown, mousePressed, mouseReleased);
+ const hit = engine.uiHitTest_getHitEntity();
return hit === NO_HIT ? null : hit;
}
/** Editor pick: topmost UI entity under the point, regardless of Interactable;
* `uiHitTestWorld` is the runtime raycast. */
export function uiPickWorld(
- module: ESEngineModule,
+ engine: EngineApi | null,
registry: CppRegistry,
worldX: number,
worldY: number,
): Entity | null {
- if (!module.uiHitTest_pick) return null;
- const hit = module.uiHitTest_pick(registry, worldX, worldY);
+ if (!engine?.uiHitTest_pick) return null;
+ const hit = engine.uiHitTest_pick(registry, worldX, worldY);
return hit === NO_HIT ? null : hit;
}
/** All editor-pickable UI entities under the point, most specific first. */
export function uiPickAllWorld(
- module: ESEngineModule,
+ engine: EngineApi | null,
registry: CppRegistry,
worldX: number,
worldY: number,
): Entity[] {
- if (!module.uiHitTest_pickAll || !module.uiHitTest_pickResult) return [];
- const count = module.uiHitTest_pickAll(registry, worldX, worldY);
+ if (!engine?.uiHitTest_pickAll || !engine.uiHitTest_pickResult) return [];
+ const count = engine.uiHitTest_pickAll(registry, worldX, worldY);
const out: Entity[] = [];
for (let i = 0; i < count; i++) {
- const e = module.uiHitTest_pickResult(i);
+ const e = engine.uiHitTest_pickResult(i);
if (e !== NO_HIT) out.push(e);
}
return out;
diff --git a/sdk/tests/binding-surface.test.ts b/sdk/tests/binding-surface.test.ts
index 42dadcec3..ad6869332 100644
--- a/sdk/tests/binding-surface.test.ts
+++ b/sdk/tests/binding-surface.test.ts
@@ -392,6 +392,8 @@ const pooledModuleCpp = [
'bindings/TilemapBindings.cpp',
'bindings/RendererBindings.hpp',
'bindings/RendererBindings.cpp',
+ 'bindings/UIBindings.hpp',
+ 'bindings/UIBindings.cpp',
'bindings/ResourceManagerBindings.hpp',
'bindings/ResourceManagerBindings.cpp',
'bindings/GeometryBindings.hpp',
diff --git a/sdk/tests/native-text.test.ts b/sdk/tests/native-text.test.ts
index 90589eaaa..47d5d89de 100644
--- a/sdk/tests/native-text.test.ts
+++ b/sdk/tests/native-text.test.ts
@@ -110,6 +110,17 @@ function makeHostScope() {
es_renderer_getMeshes: () => 0,
es_renderer_getCulled: () => 0,
es_renderer_surfaceSize: () => ({ width: 800, height: 600 }),
+ // The UI entry points, generated on a device from the same declarations
+ // embind registers; here they just record that the SDK drove them.
+ es_uiLayout_update: () => { calls.push('uiLayout'); },
+ es_transform_update: () => { calls.push('transformUpdate'); },
+ es_uiRenderOrder_update: () => { calls.push('uiRenderOrder'); },
+ es_ui_getRenderOrder: () => -1,
+ es_getUINodeHiddenInTree: () => false,
+ es_getUINodeComputedWidth: () => 0,
+ es_getUINodeComputedHeight: () => 0,
+ es_uiHitTest_update: () => {},
+ es_uiHitTest_getHitEntity: () => 0xffffffff,
es_registry_getCanvasEntity: () => canvasEntity,
es_registry_getCameraEntities: () => cameraEntities,
};
@@ -174,6 +185,11 @@ describe('a frame on the native core', () => {
calls.length = 0; // watch one frame, with the scene in place
await app.tick(1 / 60);
+ // The UI ran: the same layout and render-order passes the web build makes,
+ // reaching the native core through the generated engine API.
+ expect(calls).toContain('uiLayout');
+ expect(calls).toContain('uiRenderOrder');
+
// The host is told to stop drawing its own fallback frame — both would mean
// its pass clearing over this one.
expect(scope.es_jsOwnsFrame).toBe(true);
@@ -241,10 +257,10 @@ describe('a frame on the native core', () => {
buildScene(app, setScene);
await app.tick(1 / 60);
- // No pipeline, no camera plugin — the app still runs its gameplay stack,
- // and a host that drives its own frame keeps working (it is never told
- // otherwise).
- expect(calls).toEqual([]);
+ // No pipeline, no camera plugin — nothing opens or closes a pass, so a host
+ // that drives its own frame keeps working (it is never told otherwise). The
+ // UI passes still run: they belong to the simulation, not to the frame.
+ expect(calls.filter((c) => ['begin', 'submitAll', 'flush', 'end', 'text'].includes(c))).toEqual([]);
expect(app.pipeline).toBeNull();
expect(scope.es_jsOwnsFrame).toBeUndefined();
});
diff --git a/src/esengine/bindings/UIBindings.cpp b/src/esengine/bindings/UIBindings.cpp
new file mode 100644
index 000000000..118cac364
--- /dev/null
+++ b/src/esengine/bindings/UIBindings.cpp
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file UIBindings.cpp
+ * @brief Implements the UI entry points (see UIBindings.hpp).
+ * @details Moved out of WebSDKEntry.cpp, which is the emscripten ENTRY point:
+ * these implementations only ever needed the active context and the
+ * registry, so keeping them there made them web-only for no reason. As
+ * their own TU they compile for a native build too, and the generated
+ * QuickJS wrappers call the same code embind registers.
+ */
+#include "UIBindings.hpp"
+
+#include "ActiveContext.hpp"
+#include "../core/EstellaContext.hpp"
+#include "../core/World.hpp"
+#include "../ecs/Registry.hpp"
+#include "../ecs/UISystem.hpp"
+#include "../ecs/UIRenderOrderSystem.hpp"
+#include "../ecs/TransformSystem.hpp"
+#include "../ecs/components/Transform.hpp"
+#include "../ecs/components/UINode.hpp"
+#include "../ecs/components/UIVisual.hpp"
+
+namespace esengine {
+
+static EstellaContext& ctx() { return activeCtx(); }
+
+
+void uiLayout_update(ecs::Registry& registry, f32 camLeft, f32 camBottom, f32 camRight, f32 camTop,
+ bool propertyDirty) {
+ ctx().require<ecs::UISystem>().layoutUpdate(registry, camLeft, camBottom, camRight, camTop, propertyDirty);
+}
+
+void uiHitTest_update(ecs::Registry& registry, f32 mouseWorldX, f32 mouseWorldY,
+ bool mouseDown, bool mousePressed, bool mouseReleased) {
+ ctx().require<ecs::UISystem>().hitTestUpdate(registry, mouseWorldX, mouseWorldY, mouseDown, mousePressed, mouseReleased);
+}
+
+u32 uiHitTest_getHitEntity() {
+ return ctx().require<ecs::UISystem>().getHitEntity();
+}
+
+u32 uiHitTest_getHitEntityPrev() {
+ return ctx().require<ecs::UISystem>().getPrevHitEntity();
+}
+
+u32 uiHitTest_pick(ecs::Registry& registry, f32 worldX, f32 worldY) {
+ return ctx().require<ecs::UISystem>().pick(registry, worldX, worldY);
+}
+
+u32 uiHitTest_pickAll(ecs::Registry& registry, f32 worldX, f32 worldY) {
+ return ctx().require<ecs::UISystem>().pickAll(registry, worldX, worldY);
+}
+
+u32 uiHitTest_pickResult(u32 index) {
+ return ctx().require<ecs::UISystem>().pickResult(index);
+}
+
+// Resolved (Yoga-pass) pixel size of a UI node, for the editor's selection outline.
+// The node's world box is this size, pivot-centered on its Transform.
+f32 uiNode_computedWidth(ecs::Registry& r, u32 e) {
+ auto* n = r.tryGet<ecs::UINode>(Entity::fromRaw(e));
+ return n ? n->computed_size_.x : 0.0f;
+}
+f32 uiNode_computedHeight(ecs::Registry& r, u32 e) {
+ auto* n = r.tryGet<ecs::UINode>(Entity::fromRaw(e));
+ return n ? n->computed_size_.y : 0.0f;
+}
+
+void uiRenderOrder_update(ecs::Registry& registry) {
+ ecs::uiRenderOrderUpdate(registry);
+}
+
+// The SDF text path (TS) reads an entity's UI
+// draw order so glyph quads interleave with UI quads. uiRenderOrderUpdate
+// assigns uiOrder to every UIVisual in the UI tree (text nodes carry a
+// visualType=None UIVisual purely to be ordered). -1 = not a UI node.
+i32 ui_getRenderOrder(ecs::Registry& registry, u32 entity) {
+ auto* ui = registry.tryGet<ecs::UIVisual>(Entity::fromRaw(entity));
+ return ui ? ui->uiOrder : -1;
+}
+
+void uiFlexLayout_update(ecs::Registry& registry) {
+ // Flex layout is now integrated into uiLayout_update via unified layout pass.
+ // Kept as no-op for backward compatibility with TS plugin.
+ (void)registry;
+}
+
+void uiTree_markStructureDirty() {
+ ctx().require<ecs::UISystem>().treeMarkStructureDirty();
+}
+
+void uiTree_markDirty(u32 entity) {
+ auto e = Entity::fromRaw(entity);
+ if (e == INVALID_ENTITY) return;
+ ctx().require<ecs::UISystem>().treeMarkDirty(e);
+}
+
+void uiTree_markAllDirty() {
+ ctx().require<ecs::UISystem>().tree.markAllDirty();
+}
+
+// UINode (CSS box) computed size — its internal computed_size_ is not
+// embind-readable, so expose it for TS uiHelpers.
+bool getUINodeHiddenInTree(ecs::Registry& registry, u32 entity) {
+ auto* node = registry.tryGet<ecs::UINode>(Entity::fromRaw(entity));
+ return node && node->hidden_in_tree_;
+}
+
+f32 getUINodeComputedWidth(ecs::Registry& registry, u32 entity) {
+ auto* node = registry.tryGet<ecs::UINode>(Entity::fromRaw(entity));
+ if (!node) return 0.0f;
+ return node->computed_size_.x;
+}
+
+f32 getUINodeComputedHeight(ecs::Registry& registry, u32 entity) {
+ auto* node = registry.tryGet<ecs::UINode>(Entity::fromRaw(entity));
+ if (!node) return 0.0f;
+ return node->computed_size_.y;
+}
+
+void transform_update(ecs::Registry& registry) {
+ esengine::World world{registry, ctx().services(), 0.0f};
+ if (auto* ts = ctx().tryGet<ecs::TransformSystem>()) {
+ ts->update(world);
+ } else {
+ ecs::TransformSystem fallback;
+ fallback.update(world);
+ }
+}
+
+void transform_patchPosition(ecs::Registry& registry, u32 entity,
+ f32 x, f32 y, f32 z) {
+ auto* transform = registry.tryGet<ecs::Transform>(Entity::fromRaw(entity));
+ if (!transform) return;
+ transform->position = {x, y, z};
+}
+
+} // namespace esengine
diff --git a/src/esengine/bindings/UIBindings.hpp b/src/esengine/bindings/UIBindings.hpp
new file mode 100644
index 000000000..cb92ab84a
--- /dev/null
+++ b/src/esengine/bindings/UIBindings.hpp
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file UIBindings.hpp
+ * @brief The UI entry points the SDK drives: the Yoga layout pass, hit testing,
+ * draw order, and the computed-box queries.
+ * @details These were defined inline in WebSDKEntry.cpp, which made them
+ * web-only by accident of where they sat — the implementations use
+ * nothing but `activeCtx()` and the registry. Declared here (like
+ * RendererBindings), they are registered with embind by WebSDKEntry on
+ * the web and wrapped for QuickJS by the EHT-generated native bindings,
+ * from THIS file's declarations. One implementation, two registrations.
+ */
+#pragma once
+
+#include "../core/Types.hpp"
+
+namespace esengine {
+
+namespace ecs {
+ class Registry;
+}
+
+/** Solve the UI layout tree against the camera's world box. `propertyDirty` is
+ * the SDK's O(1) "an authored UINode/FlexContainer field changed" signal. */
+void uiLayout_update(ecs::Registry& registry, f32 camLeft, f32 camBottom, f32 camRight, f32 camTop,
+ bool propertyDirty);
+
+void uiHitTest_update(ecs::Registry& registry, f32 mouseWorldX, f32 mouseWorldY,
+ bool mouseDown, bool mousePressed, bool mouseReleased);
+u32 uiHitTest_getHitEntity();
+u32 uiHitTest_getHitEntityPrev();
+u32 uiHitTest_pick(ecs::Registry& registry, f32 worldX, f32 worldY);
+u32 uiHitTest_pickAll(ecs::Registry& registry, f32 worldX, f32 worldY);
+u32 uiHitTest_pickResult(u32 index);
+
+/** Resolved (Yoga-pass) pixel size of a UI node, for the editor's selection
+ * outline. The node's world box is this size, pivot-centered on its Transform. */
+f32 uiNode_computedWidth(ecs::Registry& registry, u32 entity);
+f32 uiNode_computedHeight(ecs::Registry& registry, u32 entity);
+
+void uiRenderOrder_update(ecs::Registry& registry);
+
+/** An entity's UI draw order, so the SDF text path can interleave glyph quads
+ * with UI quads. -1 = not a UI node. */
+i32 ui_getRenderOrder(ecs::Registry& registry, u32 entity);
+
+/** Flex layout folded into uiLayout_update; kept as a no-op for the TS plugin. */
+void uiFlexLayout_update(ecs::Registry& registry);
+
+void uiTree_markStructureDirty();
+void uiTree_markDirty(u32 entity);
+void uiTree_markAllDirty();
+
+/** UINode computed state that is not embind-readable off the component. */
+bool getUINodeHiddenInTree(ecs::Registry& registry, u32 entity);
+f32 getUINodeComputedWidth(ecs::Registry& registry, u32 entity);
+f32 getUINodeComputedHeight(ecs::Registry& registry, u32 entity);
+
+/** Compose world transforms now (the UI layout pass reads them). */
+void transform_update(ecs::Registry& registry);
+void transform_patchPosition(ecs::Registry& registry, u32 entity, f32 x, f32 y, f32 z);
+
+} // namespace esengine
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 624729c39..7b2acf315 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -20,6 +20,7 @@
#include "ActiveContext.hpp"
#include "ResourceManagerBindings.hpp"
#include "RendererBindings.hpp"
+#include "UIBindings.hpp"
#include "BoundarySpan.hpp"
#include "ImmediateDrawBindings.hpp"
#include "GeometryBindings.hpp"
@@ -695,124 +696,6 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_setTextureParams", &esengine::renderer_setTextureParams);
}
-// =============================================================================
-// UI Systems
-// =============================================================================
-
-namespace esengine {
-
-void uiLayout_update(ecs::Registry& registry, f32 camLeft, f32 camBottom, f32 camRight, f32 camTop,
- bool propertyDirty) {
- ctx().require<ecs::UISystem>().layoutUpdate(registry, camLeft, camBottom, camRight, camTop, propertyDirty);
-}
-
-void uiHitTest_update(ecs::Registry& registry, f32 mouseWorldX, f32 mouseWorldY,
- bool mouseDown, bool mousePressed, bool mouseReleased) {
- ctx().require<ecs::UISystem>().hitTestUpdate(registry, mouseWorldX, mouseWorldY, mouseDown, mousePressed, mouseReleased);
-}
-
-u32 uiHitTest_getHitEntity() {
- return ctx().require<ecs::UISystem>().getHitEntity();
-}
-
-u32 uiHitTest_getHitEntityPrev() {
- return ctx().require<ecs::UISystem>().getPrevHitEntity();
-}
-
-u32 uiHitTest_pick(ecs::Registry& registry, f32 worldX, f32 worldY) {
- return ctx().require<ecs::UISystem>().pick(registry, worldX, worldY);
-}
-
-u32 uiHitTest_pickAll(ecs::Registry& registry, f32 worldX, f32 worldY) {
- return ctx().require<ecs::UISystem>().pickAll(registry, worldX, worldY);
-}
-
-u32 uiHitTest_pickResult(u32 index) {
- return ctx().require<ecs::UISystem>().pickResult(index);
-}
-
-// Resolved (Yoga-pass) pixel size of a UI node, for the editor's selection outline.
-// The node's world box is this size, pivot-centered on its Transform.
-f32 uiNode_computedWidth(ecs::Registry& r, u32 e) {
- auto* n = r.tryGet<ecs::UINode>(Entity::fromRaw(e));
- return n ? n->computed_size_.x : 0.0f;
-}
-f32 uiNode_computedHeight(ecs::Registry& r, u32 e) {
- auto* n = r.tryGet<ecs::UINode>(Entity::fromRaw(e));
- return n ? n->computed_size_.y : 0.0f;
-}
-
-void uiRenderOrder_update(ecs::Registry& registry) {
- ecs::uiRenderOrderUpdate(registry);
-}
-
-// The SDF text path (TS) reads an entity's UI
-// draw order so glyph quads interleave with UI quads. uiRenderOrderUpdate
-// assigns uiOrder to every UIVisual in the UI tree (text nodes carry a
-// visualType=None UIVisual purely to be ordered). -1 = not a UI node.
-i32 ui_getRenderOrder(ecs::Registry& registry, u32 entity) {
- auto* ui = registry.tryGet<ecs::UIVisual>(Entity::fromRaw(entity));
- return ui ? ui->uiOrder : -1;
-}
-
-void uiFlexLayout_update(ecs::Registry& registry) {
- // Flex layout is now integrated into uiLayout_update via unified layout pass.
- // Kept as no-op for backward compatibility with TS plugin.
- (void)registry;
-}
-
-void uiTree_markStructureDirty() {
- ctx().require<ecs::UISystem>().treeMarkStructureDirty();
-}
-
-void uiTree_markDirty(u32 entity) {
- auto e = Entity::fromRaw(entity);
- if (e == INVALID_ENTITY) return;
- ctx().require<ecs::UISystem>().treeMarkDirty(e);
-}
-
-void uiTree_markAllDirty() {
- ctx().require<ecs::UISystem>().tree.markAllDirty();
-}
-
-// UINode (CSS box) computed size — its internal computed_size_ is not
-// embind-readable, so expose it for TS uiHelpers.
-bool getUINodeHiddenInTree(ecs::Registry& registry, u32 entity) {
- auto* node = registry.tryGet<ecs::UINode>(Entity::fromRaw(entity));
- return node && node->hidden_in_tree_;
-}
-
-f32 getUINodeComputedWidth(ecs::Registry& registry, u32 entity) {
- auto* node = registry.tryGet<ecs::UINode>(Entity::fromRaw(entity));
- if (!node) return 0.0f;
- return node->computed_size_.x;
-}
-
-f32 getUINodeComputedHeight(ecs::Registry& registry, u32 entity) {
- auto* node = registry.tryGet<ecs::UINode>(Entity::fromRaw(entity));
- if (!node) return 0.0f;
- return node->computed_size_.y;
-}
-
-void transform_update(ecs::Registry& registry) {
- esengine::World world{registry, ctx().services(), 0.0f};
- if (auto* ts = ctx().tryGet<ecs::TransformSystem>()) {
- ts->update(world);
- } else {
- ecs::TransformSystem fallback;
- fallback.update(world);
- }
-}
-
-void transform_patchPosition(ecs::Registry& registry, u32 entity,
- f32 x, f32 y, f32 z) {
- auto* transform = registry.tryGet<ecs::Transform>(Entity::fromRaw(entity));
- if (!transform) return;
- transform->position = {x, y, z};
-}
-
-} // namespace esengine
-
EMSCRIPTEN_BINDINGS(esengine_ui_systems) {
emscripten::function("uiLayout_update", &esengine::uiLayout_update);
emscripten::function("uiHitTest_update", &esengine::uiHitTest_update);
diff --git a/tools/eht/__main__.py b/tools/eht/__main__.py
index 05e0f5d9f..c73463a82 100644
--- a/tools/eht/__main__.py
+++ b/tools/eht/__main__.py
@@ -31,6 +31,13 @@ def _emit_native_functions(args) -> int:
print(f"Generating: {args.native_functions_output}")
args.native_functions_output.write_text(content, encoding='utf-8')
print(f" {len(gen.emitted)} entry point(s) bound")
+ # The TS half: the same entry points as the object the SDK's plugins call, so
+ # a plugin reaches whichever core is present without knowing which. Committed
+ # (the SDK builds from source without running EHT), unlike the C++ wrappers.
+ if args.native_functions_ts is not None:
+ args.native_functions_ts.parent.mkdir(parents=True, exist_ok=True)
+ print(f"Generating: {args.native_functions_ts}")
+ args.native_functions_ts.write_text(gen.generate_ts(), encoding='utf-8')
# Never a silent cap: what the wrappers cannot marshal is what still needs a
# hand-written binding, so say it every run.
for skip in gen.skipped:
@@ -84,6 +91,8 @@ def main() -> int:
help='Bindings headers to emit native QuickJS wrappers for')
parser.add_argument('--native-functions-output', type=Path, default=None,
help='Where to write the generated wrappers (.cpp)')
+ parser.add_argument('--native-functions-ts', type=Path, default=None,
+ help='Also write the TS-side native engine API (.ts)')
args = parser.parse_args()
print("EHT - ESEngine Header Tool")
diff --git a/tools/eht/generators/native_functions.py b/tools/eht/generators/native_functions.py
index 747506ca2..1e2f08eaa 100644
--- a/tools/eht/generators/native_functions.py
+++ b/tools/eht/generators/native_functions.py
@@ -239,6 +239,89 @@ class NativeFunctionsGenerator:
out.append('')
return out
+ # ---- the TS half -------------------------------------------------------
+ # The same declarations, as the object a native host answers them through.
+ # The SDK's plugins call these by the module's own names, so a plugin reaches
+ # whichever core is present without knowing which (see ecs/engineApi.ts).
+ _TS_RETURN = {'void': 'void', 'bool': 'boolean'}
+
+ @staticmethod
+ def _ts_type(cpp: str) -> str:
+ if cpp in _BOOL_TYPES:
+ return 'boolean'
+ if cpp == 'ecs::Registry&':
+ return 'unknown'
+ return 'number'
+
+ def _ts_signature(self, fn: Function) -> str:
+ params = ', '.join(f'{p.name}: {self._ts_type(p.cpp_type)}' for p in fn.params)
+ ret = self._TS_RETURN.get(fn.ret, 'number')
+ return f'{fn.name}?({params}): {ret};'
+
+ def generate_ts(self) -> str:
+ """The native engine API: every generated entry point, callable by the
+ name the wasm module exposes it under."""
+ functions = [f for f in self._functions() if not any(p.cpp_type == 'uintptr_t' for p in f.params)]
+ pointer_taking = [f.name for f in self._functions() if any(p.cpp_type == 'uintptr_t' for p in f.params)]
+
+ lines = [
+ '// SPDX-License-Identifier: Apache-2.0',
+ '// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team',
+ '//',
+ '// Auto-generated by EHT (native_functions) — DO NOT EDIT.',
+ '//',
+ '// The engine entry points a native (embedded-Dawn) host binds, named as the',
+ '// wasm module names them — so an SDK plugin calls `api.uiLayout_update(...)`',
+ '// and reaches whichever core is present. Generated from the SAME bindings',
+ '// headers embind registers from, so the two surfaces cannot drift.',
+ '//',
+ '// Every member is optional: a core answers what it compiles. Entry points that',
+ '// take a heap pointer are NOT here — those need a real backend that decides how',
+ '// bytes cross (see RendererBackend), not a name forwarded.',
+ '',
+ 'export interface NativeEngineApi {',
+ ]
+ for fn in functions:
+ lines.append(f' {self._ts_signature(fn)}')
+ lines.append('}')
+ lines.append('')
+ if pointer_taking:
+ lines.append('// Not forwarded (they take a heap pointer): '
+ + ', '.join(sorted(pointer_taking)) + '.')
+ lines.append('')
+ lines.extend([
+ '/** Build the API over a host scope (the QuickJS global object; a plain object',
+ ' * in tests). A name the host did not bind simply stays absent. */',
+ 'export function createNativeEngineApi(',
+ ' scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,',
+ '): NativeEngineApi {',
+ ' const api: Record<string, unknown> = {};',
+ ' const bind = (name: string, host: string, dropFirst: boolean): void => {',
+ ' const fn = scope[host];',
+ ' if (typeof fn !== \'function\') return;',
+ ' const call = fn as (...a: unknown[]) => unknown;',
+ ' api[name] = dropFirst',
+ ' ? (_registry: unknown, ...args: unknown[]) => call(...args)',
+ ' : (...args: unknown[]) => call(...args);',
+ ' };',
+ ])
+ for fn in functions:
+ takes_registry = any(p.cpp_type == 'ecs::Registry&' for p in fn.params)
+ lines.append(f" bind('{fn.name}', 'es_{fn.name}', {str(takes_registry).lower()});")
+ lines.extend([
+ ' return api as NativeEngineApi;',
+ '}',
+ '',
+ ])
+ return '\n'.join(lines)
+
+ def _functions(self) -> List[Function]:
+ out: List[Function] = []
+ for _, text in self.headers:
+ parsed, _ = parse_header(text)
+ out.extend(parsed)
+ return sorted(out, key=lambda f: f.name)
+
def generate(self) -> str:
lines = [
'// Auto-generated by EHT (native_functions) — DO NOT EDIT.',