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(eht): generate the native binding surface, don't hand-write it twice

yhh4f05a4b8f470
diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.js
index 44e628de3..ff3900e23 100644
--- a/build-tools/tasks/native.js
+++ b/build-tools/tasks/native.js
@@ -33,6 +33,23 @@ async function generateNativeBindings(rootDir, genDir, python) {
return out;
}
+// Generate the QuickJS wrappers for the engine's binding ENTRY POINTS — the same
+// declarations embind registers on the web, so the SDK reaches the engine by the
+// same names on both platforms and nothing is bound twice by hand. The bodies are
+// 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(
+ (h) => path.join(rootDir, 'src', 'esengine', 'bindings', h));
+ await runCommand(python, [
+ path.join(rootDir, 'tools', 'eht.py'),
+ '--native-functions', ...headers,
+ '--native-functions-output', out,
+ '--native-shim', 'esn_shim.hpp',
+ ], { cwd: rootDir });
+ return out;
+}
+
// Embed the real esengine SDK, bundled to one QuickJS-loadable file
// (dist/index.native.bundled.js — the IIFE that installs globalThis.ESEngine).
// The host evals it, then a game script drives it via ESEngine.createNativeWorld.
@@ -69,6 +86,8 @@ async function prepareGenerated(rootDir, buildDir, quickjs) {
const python = await resolvePython() ?? 'python3';
logger.step('Generating native ECS bindings (EHT, single reflection source)...');
await generateNativeBindings(rootDir, genDir, python);
+ logger.step('Generating native entry-point bindings (EHT, same declarations as embind)...');
+ await generateNativeFunctionBindings(rootDir, genDir, python);
logger.step('Embedding the real SDK bundle (dist/index.native.bundled.js)...');
await generateSdkBundle(rootDir, genDir);
return genDir;
diff --git a/cmake/ESEngineSources.cmake b/cmake/ESEngineSources.cmake
index eca6d1e3d..52bf9c95f 100644
--- a/cmake/ESEngineSources.cmake
+++ b/cmake/ESEngineSources.cmake
@@ -48,6 +48,22 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
list(APPEND ESENGINE_SOURCES ${ESENGINE_ROOT}/src/esengine/renderer/GLDevice.cpp)
endif()
+# The binding ENTRY POINTS the SDK calls (renderer_begin, renderer_submitAll, …).
+# They are not web-specific: they reach the engine through activeCtx() and validate
+# JS-supplied spans through BoundarySpan, both portable. The web build compiles
+# them as part of SDK_BINDING_SOURCES (with embind registering them); a native
+# build compiles the same TU here and registers the same functions on QuickJS from
+# generated wrappers — one binding implementation, two registration layers. The
+# few entry points that return an `emscripten::val` are gated out natively.
+if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
+ list(APPEND ESENGINE_SOURCES
+ ${ESENGINE_ROOT}/src/esengine/bindings/RendererBindings.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.
+ ${ESENGINE_ROOT}/src/esengine/bindings/EngineContext.cpp)
+endif()
+
if(ES_ENABLE_WEBGPU)
list(APPEND ESENGINE_SOURCES ${ESENGINE_ROOT}/src/esengine/renderer/webgpu/WebGPUDevice.cpp)
endif()
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index e017339dd..9a5ea156e 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -68,8 +68,9 @@ endif()
# The engine core, native arm64. The source list is the SAME single-source file the
# web build uses (cmake/ESEngineSources.cmake) — selecting the WebGPU backend and
-# dropping GL / bitmap text / particles / tilemap / post-process for this build. The
-# bindings/ (emscripten embind) TUs are web-only and never listed there.
+# dropping GL / particles / tilemap / post-process for this build. It also brings in
+# the portable binding entry points (RendererBindings.cpp), whose QuickJS wrappers
+# are generated from the same declarations embind registers.
set(ESENGINE_ROOT "${REPO}")
list(APPEND CMAKE_MODULE_PATH "${REPO}/cmake")
set(ES_ENABLE_WEBGPU ON)
@@ -112,6 +113,14 @@ if(ESTELLA_QUICKJS_DIR)
"Generate it (and ptraccessors_js.h) via `cli native --quickjs`, which runs "
"`python -m eht --native-output ... --native-only`.")
endif()
+ # The engine's binding entry points, wrapped for QuickJS from the SAME
+ # declarations embind registers (`--native-functions`). The bodies are in the
+ # binding TUs the engine target compiles, so both platforms run one
+ # implementation and only the registration differs.
+ set(NATIVE_FN_BINDINGS "${ESTELLA_NATIVE_GEN_DIR}/NativeFunctionBindings.generated.cpp")
+ if(NOT EXISTS "${NATIVE_FN_BINDINGS}")
+ message(FATAL_ERROR "Missing ${NATIVE_FN_BINDINGS} — generate it via `cli native --quickjs`.")
+ endif()
# QuickJS-ng interpreter — core is just these four C files.
add_library(qjs STATIC
@@ -135,7 +144,7 @@ if(ESTELLA_QUICKJS_DIR)
# below. -ObjC on the app keeps the Obj-C classes in main_ios.mm alive.
add_library(estella_js_host STATIC host_js/host_core.cpp host_js/main_ios.mm
host_js/native_audio.cpp host_js/ktx2_decode.cpp host_js/glyph_raster.cpp
- "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_BINDINGS}")
+ "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_BINDINGS}" "${NATIVE_FN_BINDINGS}")
# miniaudio's CoreAudio backend uses AVAudioSession (Obj-C), so its TU must
# be Objective-C++ on Apple; it also forces MA_NO_RUNTIME_LINKING there, so
# the audio frameworks are linked at build time (the app links the merged
@@ -158,7 +167,7 @@ if(ESTELLA_QUICKJS_DIR)
# link libs). native_audio.cpp's Obj-C paths are __APPLE__-guarded out.
add_library(estella_js_host SHARED host_js/host_core.cpp host_js/main_android.cpp
host_js/native_audio.cpp host_js/ktx2_decode.cpp host_js/glyph_raster.cpp
- "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_BINDINGS}")
+ "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_BINDINGS}" "${NATIVE_FN_BINDINGS}")
target_link_libraries(estella_js_host esengine qjs native_app_glue android log)
set_target_properties(estella_js_host PROPERTIES LINK_FLAGS "-u ANativeActivity_onCreate")
endif()
diff --git a/native/host_js/esn_shim.hpp b/native/host_js/esn_shim.hpp
index 333abb66f..51925c035 100644
--- a/native/host_js/esn_shim.hpp
+++ b/native/host_js/esn_shim.hpp
@@ -11,6 +11,9 @@ extern "C" {
}
#include "esengine/ecs/Registry.hpp" // esengine::ecs::Registry + esengine::Entity
+#include "esengine/core/Types.hpp" // esengine::u8
+
+#include <vector>
// --- provided by the host (js/main.cpp) --------------------------------------
esengine::ecs::Registry& esn_reg();
@@ -23,6 +26,15 @@ bool esn_getbool(JSContext* ctx, JSValueConst obj, const char* key, int* out);
void esn_getvec(JSContext* ctx, JSValueConst obj, const char* key, float* dst, int n);
// Wrap [ptr, ptr+size) as a zero-copy JS ArrayBuffer (native owns the memory).
JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size);
+// Read a JS byte source (ArrayBuffer, typed-array view, or plain number array)
+// into `out`. Backs the generated wrappers for entry points that take a
+// `uintptr_t` buffer: on the web that is a wasm heap offset, here it is real
+// memory the wrapper owns for the duration of the call.
+void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out);
-// --- provided by the generated file (NativeBindings.generated.cpp) -----------
+// --- provided by the generated files -----------------------------------------
+// Components (NativeBindings.generated.cpp) and the engine's binding entry
+// points (NativeFunctionBindings.generated.cpp), from the same declarations the
+// web build registers with embind.
void esn_register(JSContext* ctx, JSValue global);
+void esn_register_functions(JSContext* ctx, JSValue global);
diff --git a/native/host_js/host_core.cpp b/native/host_js/host_core.cpp
index f6cd2999b..2e768257b 100644
--- a/native/host_js/host_core.cpp
+++ b/native/host_js/host_core.cpp
@@ -31,6 +31,7 @@
#include "glyph_raster.hpp" // stb_truetype + the engine's SDF, behind es_rasterizeGlyph
#include "esengine/core/EstellaContext.hpp"
+#include "esengine/bindings/ActiveContext.hpp" // g_activeContext — the context the generated bindings act on
#include "esengine/core/World.hpp"
#include "esengine/ecs/TransformSystem.hpp" // TransformSystem + ecs::setParent
#include "esengine/ecs/components/Hierarchy.hpp" // Parent / Children
@@ -131,10 +132,6 @@ struct App {
f32 w = 0, h = 0;
bool ready = false; // engine + JS booted once
bool surfaceReady = false; // a live window surface is bound (false while screen off)
- // Set for the frame whenever the SDK's render pipeline opened a pass through
- // es_renderer_begin. The host then only presents; a game (or host) that
- // predates those bindings still gets the fallback pass in frame().
- bool sdkOwnsFrame = false;
uint64_t frame = 0;
};
@@ -200,6 +197,15 @@ void esn_getvec(JSContext* ctx, JSValueConst obj, const char* key, float* dst, i
}
JS_FreeValue(ctx, arr);
}
+namespace { void readByteSource(JSContext* ctx, JSValueConst v, std::vector<u8>& out); }
+
+// The generated wrappers for entry points that take a `uintptr_t` buffer read
+// their bytes through this: on the web that argument is a wasm heap offset, here
+// it is memory the wrapper owns for the duration of the call.
+void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<u8>& out) {
+ readByteSource(ctx, v, out);
+}
+
JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size) {
return JS_NewArrayBuffer(ctx, reinterpret_cast<uint8_t*>(ptr), size, nullptr, nullptr, false);
}
@@ -519,143 +525,14 @@ JSValue js_submitTextBatch(JSContext* ctx, JSValueConst, int argc, JSValueConst*
return JS_UNDEFINED;
}
-// ---- the frame: es_renderer_* ------------------------------------------------
+// ---- the frame -------------------------------------------------------------
//
-// The SDK's own render pipeline (CameraPlugin -> RenderPipeline -> Renderer) runs
-// on device through these, so which cameras exist, their viewport rects and clear
-// flags, the y-sort layers and what draws just before the flush are decided by
-// the SAME code the web build runs. Each one mirrors its web counterpart in
-// bindings/RendererBindings.cpp; the registry argument those take is implicit
-// here (a host has exactly one). What remains the host's own is the swapchain and
-// the present, in frame() below.
-
-JSValue js_renderer_resize(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
- if (argc < 2 || !g_app || !g_app->ctx) return JS_UNDEFINED;
- int32_t w = 0, h = 0;
- JS_ToInt32(ctx, &w, argv[0]); JS_ToInt32(ctx, &h, argv[1]);
- auto& ctxRef = *g_app->ctx;
- ctxRef.state().viewport_width = (u32)w;
- ctxRef.state().viewport_height = (u32)h;
- ctxRef.require<RenderFrame>().resize((u32)w, (u32)h);
- return JS_UNDEFINED;
-}
-
-JSValue js_renderer_beginFrame(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
- if (!g_app || !g_app->ctx) return JS_UNDEFINED;
- double elapsed = 0;
- if (argc > 0) JS_ToFloat64(ctx, &elapsed, argv[0]);
- auto& ctxRef = *g_app->ctx;
- ctxRef.state().transforms_updated = false;
- ctxRef.require<RenderContext>().setFrameTime((f32)elapsed, (u32)g_app->w, (u32)g_app->h);
- return JS_UNDEFINED;
-}
-
-// The transform pass, once per frame: the flag mirrors the web binding's
-// ensureTransformsUpdated, so submitAll below never repeats it.
-void ensureTransformsUpdated(App& a) {
- auto& ctxRef = *a.ctx;
- if (ctxRef.state().transforms_updated) return;
- World world{*a.registry, ctxRef.services(), 1.0f / 60.0f};
- ctxRef.require<ecs::TransformSystem>().update(world);
- ctxRef.state().transforms_updated = true;
-}
-
-JSValue js_renderer_updateTransforms(JSContext*, JSValueConst, int, JSValueConst*) {
- if (!g_app || !g_app->ctx) return JS_UNDEFINED;
- ensureTransformsUpdated(*g_app);
- return JS_UNDEFINED;
-}
-
-// es_renderer_begin(viewProjection, target, clearFlags, r,g,b,a, x,y,w,h) — the
-// pass's load-op rides begin, exactly as on web: bit 0 = colour, bit 1 = depth,
-// and a zero-width region means the whole target.
-JSValue js_renderer_begin(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
- if (argc < 11 || !g_app || !g_app->ctx) return JS_UNDEFINED;
- std::vector<u8> matrixBytes;
- readByteSource(ctx, argv[0], matrixBytes);
- if (matrixBytes.size() < 16 * sizeof(f32)) return JS_UNDEFINED;
- const f32* m = reinterpret_cast<const f32*>(matrixBytes.data());
-
- int32_t target = 0, clearFlags = 0, clearX = 0, clearY = 0, clearW = 0, clearH = 0;
- double r = 0, g = 0, b = 0, a = 1;
- JS_ToInt32(ctx, &target, argv[1]);
- JS_ToInt32(ctx, &clearFlags, argv[2]);
- JS_ToFloat64(ctx, &r, argv[3]); JS_ToFloat64(ctx, &g, argv[4]);
- JS_ToFloat64(ctx, &b, argv[5]); JS_ToFloat64(ctx, &a, argv[6]);
- JS_ToInt32(ctx, &clearX, argv[7]); JS_ToInt32(ctx, &clearY, argv[8]);
- JS_ToInt32(ctx, &clearW, argv[9]); JS_ToInt32(ctx, &clearH, argv[10]);
-
- g_app->sdkOwnsFrame = true;
- g_app->ctx->require<RenderFrame>().begin(
- glm::make_mat4(m), (u32)target,
- RenderFrame::PassClear{(clearFlags & 1) != 0, (clearFlags & 2) != 0,
- glm::vec4((f32)r, (f32)g, (f32)b, (f32)a),
- clearX, clearY, (u32)clearW, (u32)clearH});
- return JS_UNDEFINED;
-}
-
-JSValue js_renderer_submitAll(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
- if (argc < 5 || !g_app || !g_app->ctx) return JS_UNDEFINED;
- int32_t skipFlags = 0, vpX = 0, vpY = 0, vpW = 0, vpH = 0;
- JS_ToInt32(ctx, &skipFlags, argv[0]);
- JS_ToInt32(ctx, &vpX, argv[1]); JS_ToInt32(ctx, &vpY, argv[2]);
- JS_ToInt32(ctx, &vpW, argv[3]); JS_ToInt32(ctx, &vpH, argv[4]);
- ensureTransformsUpdated(*g_app);
- auto& rf = g_app->ctx->require<RenderFrame>();
- rf.processMasks(*g_app->registry, vpX, vpY, vpW, vpH);
- rf.collectAll(*g_app->registry, (u32)skipFlags);
- return JS_UNDEFINED;
-}
-
-JSValue js_renderer_flush(JSContext*, JSValueConst, int, JSValueConst*) {
- if (g_app && g_app->ctx) g_app->ctx->require<RenderFrame>().flush();
- return JS_UNDEFINED;
-}
-
-JSValue js_renderer_end(JSContext*, JSValueConst, int, JSValueConst*) {
- if (g_app && g_app->ctx) g_app->ctx->require<RenderFrame>().end();
- return JS_UNDEFINED;
-}
-
-JSValue js_renderer_setStage(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
- if (argc < 1 || !g_app || !g_app->ctx) return JS_UNDEFINED;
- int32_t stage = 0; JS_ToInt32(ctx, &stage, argv[0]);
- g_app->ctx->require<RenderFrame>().setStage(static_cast<RenderStage>(stage));
- return JS_UNDEFINED;
-}
-
-JSValue js_renderer_setViewport(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
- if (argc < 4 || !g_app || !g_app->gfx) return JS_UNDEFINED;
- int32_t x = 0, y = 0, w = 0, h = 0;
- JS_ToInt32(ctx, &x, argv[0]); JS_ToInt32(ctx, &y, argv[1]);
- JS_ToInt32(ctx, &w, argv[2]); JS_ToInt32(ctx, &h, argv[3]);
- g_app->gfx->setViewport(x, y, (u32)w, (u32)h);
- return JS_UNDEFINED;
-}
-
-JSValue js_renderer_setYSortLayers(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
- if (argc < 1 || !g_app || !g_app->ctx) return JS_UNDEFINED;
- uint32_t mask = 0; JS_ToUint32(ctx, &mask, argv[0]);
- g_app->ctx->require<RenderFrame>().setYSortLayers(mask);
- return JS_UNDEFINED;
-}
-
-// es_renderer_stats() -> the engine's per-frame counters, which the SDK's stats
-// overlay and the editor read through Renderer.getStats().
-JSValue js_renderer_stats(JSContext* ctx, JSValueConst, int, JSValueConst*) {
- JSValue o = JS_NewObject(ctx);
- const RenderFrame::Stats empty{};
- const RenderFrame::Stats& stats =
- g_app && g_app->ctx ? g_app->ctx->require<RenderFrame>().stats() : empty;
- JS_SetPropertyStr(ctx, o, "drawCalls", JS_NewInt32(ctx, (int32_t)stats.draw_calls));
- JS_SetPropertyStr(ctx, o, "triangles", JS_NewInt32(ctx, (int32_t)stats.triangles));
- JS_SetPropertyStr(ctx, o, "sprites", JS_NewInt32(ctx, (int32_t)stats.sprites));
- JS_SetPropertyStr(ctx, o, "text", JS_NewInt32(ctx, (int32_t)stats.text));
- JS_SetPropertyStr(ctx, o, "spine", JS_NewInt32(ctx, 0));
- JS_SetPropertyStr(ctx, o, "meshes", JS_NewInt32(ctx, (int32_t)stats.meshes));
- JS_SetPropertyStr(ctx, o, "culled", JS_NewInt32(ctx, (int32_t)stats.culled));
- return o;
-}
+// The es_renderer_* entry points are GENERATED (NativeFunctionBindings.generated.cpp)
+// from the same declarations embind registers on the web, and call the same
+// binding TU — so the SDK's camera plugin and render pipeline drive a device
+// frame through one implementation. What stays here is what has no web
+// counterpart: the surface size, and the camera list (its web sibling returns an
+// emscripten::val, which does not exist natively).
// es_renderer_surfaceSize() -> { width, height }: the camera plugin reads it per
// frame, so a rotation reaches the projection without an event.
@@ -666,16 +543,6 @@ JSValue js_renderer_surfaceSize(JSContext* ctx, JSValueConst, int, JSValueConst*
return o;
}
-// The two scene queries the camera plugin makes: which entity carries the Canvas
-// (its background colour clears the frame) and which carry a Camera.
-JSValue js_registry_getCanvasEntity(JSContext* ctx, JSValueConst, int, JSValueConst*) {
- if (!g_app || !g_app->registry) return JS_NewInt32(ctx, -1);
- for (auto entity : g_app->registry->view<ecs::Canvas>()) {
- return JS_NewInt32(ctx, (int32_t)entity.id());
- }
- return JS_NewInt32(ctx, -1);
-}
-
JSValue js_registry_getCameraEntities(JSContext* ctx, JSValueConst, int, JSValueConst*) {
JSValue arr = JS_NewArray(ctx);
if (!g_app || !g_app->registry) return arr;
@@ -1238,22 +1105,10 @@ void initJS(App& a) {
bindGlobal(a, global, "es_submitTextBatch", js_submitTextBatch, 9);
bindGlobal(a, global, "es_updateTextureSubregion", js_updateTextureSubregion, 6);
bindGlobal(a, global, "es_getTextureRenderId", js_getTextureRenderId, 1);
- // The frame (es_renderer_* + the two scene queries): the SDK's own camera
- // plugin and render pipeline run on these, so a native frame is decided by the
- // same code the web build runs. The host keeps the swapchain and the present.
- bindGlobal(a, global, "es_renderer_resize", js_renderer_resize, 2);
- bindGlobal(a, global, "es_renderer_beginFrame", js_renderer_beginFrame, 1);
- bindGlobal(a, global, "es_renderer_updateTransforms", js_renderer_updateTransforms, 0);
- bindGlobal(a, global, "es_renderer_begin", js_renderer_begin, 11);
- bindGlobal(a, global, "es_renderer_submitAll", js_renderer_submitAll, 5);
- bindGlobal(a, global, "es_renderer_flush", js_renderer_flush, 0);
- bindGlobal(a, global, "es_renderer_end", js_renderer_end, 0);
- bindGlobal(a, global, "es_renderer_setStage", js_renderer_setStage, 1);
- bindGlobal(a, global, "es_renderer_setViewport", js_renderer_setViewport, 4);
- bindGlobal(a, global, "es_renderer_setYSortLayers", js_renderer_setYSortLayers, 1);
- bindGlobal(a, global, "es_renderer_stats", js_renderer_stats, 0);
+ // The frame: es_renderer_* (and every other binding entry point) comes from
+ // esn_register_functions below — generated from the declarations embind
+ // registers on the web. Only what has no web counterpart is bound by hand.
bindGlobal(a, global, "es_renderer_surfaceSize", js_renderer_surfaceSize, 0);
- bindGlobal(a, global, "es_registry_getCanvasEntity", js_registry_getCanvasEntity, 0);
bindGlobal(a, global, "es_registry_getCameraEntities", js_registry_getCameraEntities, 0);
// Audio (es_audio*): bound only when a device came up, so the SDK's
// hasAudioBindings() gates the native audio backend on real availability —
@@ -1275,6 +1130,10 @@ void initJS(App& a) {
}
// Per-component bindings (EHT-generated): es_set_<C> / es_<C>_buffer / _has / _remove.
esn_register(a.js, global);
+ // The engine's binding entry points (EHT-generated from the same declarations
+ // embind registers): es_renderer_*, es_uiLayout_*, es_particle_*, … The SDK
+ // calls them by the same names its wasm path calls the module by.
+ esn_register_functions(a.js, global);
JS_FreeValue(a.js, global);
// Layers: the real SDK bundle (engine, embedded) installs ESEngine; the host
@@ -1389,6 +1248,11 @@ bool boot(Platform& platform) {
if (!bindSurface()) return false;
static EstellaContext context;
a.ctx = &context;
+ // The binding entry points (the generated es_* wrappers call the same ones
+ // embind does) reach the engine through activeCtx(); install ours, exactly as
+ // the web entry does at initRenderer. Without this they would act on the
+ // fallback context and render into a different engine than the host presents.
+ g_activeContext = &context;
context.state().viewport_width = (i32)a.w;
context.state().viewport_height = (i32)a.h;
if (!context.init(std::move(device))) { LOGE("context.init failed"); return false; }
@@ -1402,11 +1266,21 @@ bool boot(Platform& platform) {
return true;
}
+// Has the SDK's render pipeline taken over the frame? It declares itself through
+// `es_jsOwnsFrame` (see HOST_FLAGS in the SDK's nativeBindings) once installed.
+bool jsOwnsFrame(App& a) {
+ JSValue global = JS_GetGlobalObject(a.js);
+ JSValue v = JS_GetPropertyStr(a.js, global, "es_jsOwnsFrame");
+ const bool owns = JS_ToBool(a.js, v) != 0;
+ JS_FreeValue(a.js, v);
+ JS_FreeValue(a.js, global);
+ return owns;
+}
+
void frame() {
if (!g_app || !g_app->ready || !g_app->surfaceReady) return;
App& a = *g_app;
auto& ctx = *a.ctx;
- a.sdkOwnsFrame = false; // set again by es_renderer_begin if the SDK renders
JSValue dt = JS_NewFloat64(a.js, 1.0 / 60.0);
callJs(a, "update", 1, &dt);
JS_FreeValue(a.js, dt);
@@ -1432,8 +1306,10 @@ void frame() {
// left here is what only a host can do: flip the swapchain.
//
// A game script that predates those bindings (or a host that has not bound
- // them) still gets a frame: fall back to one full-viewport pass.
- if (!a.sdkOwnsFrame) {
+ // them) still gets a frame: fall back to one full-viewport pass. The SDK says
+ // which it is by declaring es_jsOwnsFrame when its pipeline is installed —
+ // both drawing would mean the host's pass clears over the SDK's.
+ if (!jsOwnsFrame(a)) {
ctx.require<RenderContext>().setFrameTime((f32)a.frame / 60.0f, (u32)a.w, (u32)a.h);
World world{*a.registry, ctx.services(), 1.0f / 60.0f};
ctx.require<ecs::TransformSystem>().update(world);
diff --git a/sdk/src/ecs/nativeBindings.ts b/sdk/src/ecs/nativeBindings.ts
index 9663f7c29..bc5225920 100644
--- a/sdk/src/ecs/nativeBindings.ts
+++ b/sdk/src/ecs/nativeBindings.ts
@@ -82,10 +82,34 @@ export const RENDERER_BINDINGS = {
setStage: 'es_renderer_setStage',
setViewport: 'es_renderer_setViewport',
setYSortLayers: 'es_renderer_setYSortLayers',
- stats: 'es_renderer_stats',
+ /** Host-specific: the drawable size, which no wasm entry point has. */
surfaceSize: 'es_renderer_surfaceSize',
} as const;
+/** The per-frame counters, read one call each — the same entry points the wasm
+ * module exposes under the same names, so the two paths report identically. */
+export const RENDERER_STATS_BINDINGS = {
+ drawCalls: 'es_renderer_getDrawCalls',
+ triangles: 'es_renderer_getTriangles',
+ sprites: 'es_renderer_getSprites',
+ text: 'es_renderer_getText',
+ meshes: 'es_renderer_getMeshes',
+ culled: 'es_renderer_getCulled',
+} as const;
+
+/**
+ * What the SDK declares back to the host, on the same global object.
+ *
+ * A host predates these bindings gracefully: it keeps a fallback frame (one
+ * full-viewport pass) for a game script that never drives one. `ownsFrame` is how
+ * it learns to stop — set once the SDK's render pipeline is installed, so the two
+ * never both draw (which would look like the SDK's frame silently vanishing, since
+ * the host's pass would clear and re-collect over it).
+ */
+export const HOST_FLAGS = {
+ ownsFrame: 'es_jsOwnsFrame',
+} as const;
+
/** Whether the host bound the whole frame surface — the gate for the SDK driving
* the frame (cameras and all) rather than the host hard-coding one. */
export function hasRendererBindings(
diff --git a/sdk/src/ecs/nativeRenderer.ts b/sdk/src/ecs/nativeRenderer.ts
index d961bab1b..fb59eb174 100644
--- a/sdk/src/ecs/nativeRenderer.ts
+++ b/sdk/src/ecs/nativeRenderer.ts
@@ -18,7 +18,7 @@
import type { CppRegistry } from '../wasm';
import type { RendererBackend, RenderStats } from '../renderer';
-import { RENDERER_BINDINGS } from './nativeBindings';
+import { RENDERER_BINDINGS, RENDERER_STATS_BINDINGS } from './nativeBindings';
/** Invoke a host-provided global by name; throws if the host did not bind it
* (these are the frame contract — a missing one is a broken host, not a
@@ -31,8 +31,6 @@ function hostCall(scope: Record<string, unknown>, name: string, args: unknown[])
return (fn as (...a: unknown[]) => unknown)(...args);
}
-const NO_STATS: RenderStats = { drawCalls: 0, triangles: 0, sprites: 0, text: 0, spine: 0, meshes: 0, culled: 0 };
-
/**
* Build the RendererBackend over the host's frame bindings. `scope` holds the
* globals (the QuickJS global object on a device; a plain object in tests).
@@ -79,8 +77,21 @@ export function createNativeRendererBackend(
setYSortLayers: (mask): void => {
hostCall(scope, RENDERER_BINDINGS.setYSortLayers, [mask >>> 0]);
},
- getStats: (): RenderStats =>
- (hostCall(scope, RENDERER_BINDINGS.stats, []) as RenderStats | undefined) ?? NO_STATS,
+ getStats: (): RenderStats => {
+ const read = (name: string): number => {
+ const fn = scope[name];
+ return typeof fn === 'function' ? ((fn as () => number)() ?? 0) : 0;
+ };
+ return {
+ drawCalls: read(RENDERER_STATS_BINDINGS.drawCalls),
+ triangles: read(RENDERER_STATS_BINDINGS.triangles),
+ sprites: read(RENDERER_STATS_BINDINGS.sprites),
+ text: read(RENDERER_STATS_BINDINGS.text),
+ spine: 0, // the spine module has no native counterpart yet
+ meshes: read(RENDERER_STATS_BINDINGS.meshes),
+ culled: read(RENDERER_STATS_BINDINGS.culled),
+ };
+ },
};
}
diff --git a/sdk/src/ecs/nativeRuntime.ts b/sdk/src/ecs/nativeRuntime.ts
index c8a5c1814..fc601e1c7 100644
--- a/sdk/src/ecs/nativeRuntime.ts
+++ b/sdk/src/ecs/nativeRuntime.ts
@@ -21,7 +21,7 @@ import { installNativePlatform, type NativeBridge } from '../platform/native';
import { createNativeRegistry } from './nativeRegistry';
import { NativeMemoryProvider } from './memoryProvider';
import { createNativeResourceManager } from './nativeResourceManager';
-import { TEXT_BINDINGS, hasTextBindings, hasRendererBindings } from './nativeBindings';
+import { HOST_FLAGS, TEXT_BINDINGS, hasTextBindings, hasRendererBindings } from './nativeBindings';
import { createNativeRendererBackend, nativeSurfaceSize } from './nativeRenderer';
import { setRendererBackend } from '../renderer';
import { RenderPipeline } from '../renderPipeline';
@@ -132,6 +132,9 @@ function installNativeRenderer(app: App, scope: Record<string, unknown>): void {
// The viewport is read per frame, so a rotation reaches the projection without
// anyone pushing a resize event.
app.addPlugin(cameraPlugin(() => nativeSurfaceSize(scope)));
+ // Tell the host to stop drawing its fallback frame: from here the pipeline
+ // above opens and closes every pass, and a second one would clear over it.
+ scope[HOST_FLAGS.ownsFrame] = true;
}
/**
diff --git a/sdk/tests/native-text.test.ts b/sdk/tests/native-text.test.ts
index 04811d201..90589eaaa 100644
--- a/sdk/tests/native-text.test.ts
+++ b/sdk/tests/native-text.test.ts
@@ -103,7 +103,12 @@ function makeHostScope() {
es_renderer_setStage: () => {},
es_renderer_setViewport: () => {},
es_renderer_setYSortLayers: () => {},
- es_renderer_stats: () => ({ drawCalls: 1, triangles: 2, sprites: 1, text: 1, spine: 0, meshes: 0, culled: 0 }),
+ es_renderer_getDrawCalls: () => 1,
+ es_renderer_getTriangles: () => 2,
+ es_renderer_getSprites: () => 1,
+ es_renderer_getText: () => 1,
+ es_renderer_getMeshes: () => 0,
+ es_renderer_getCulled: () => 0,
es_renderer_surfaceSize: () => ({ width: 800, height: 600 }),
es_registry_getCanvasEntity: () => canvasEntity,
es_registry_getCameraEntities: () => cameraEntities,
@@ -169,6 +174,10 @@ describe('a frame on the native core', () => {
calls.length = 0; // watch one frame, with the scene in place
await app.tick(1 / 60);
+ // 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);
+
// The SDK drove a whole frame: the camera's pass opened, the scene was
// collected, the text drew before the flush, and the pass closed. The host
// adds only the present after this.
@@ -233,8 +242,10 @@ describe('a frame on the native core', () => {
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.
+ // and a host that drives its own frame keeps working (it is never told
+ // otherwise).
expect(calls).toEqual([]);
expect(app.pipeline).toBeNull();
+ expect(scope.es_jsOwnsFrame).toBeUndefined();
});
});
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 771f4568d..3a3e0c7f1 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -29,7 +29,9 @@
#endif
#include "../trail/TrailSystem.hpp"
+#ifdef __EMSCRIPTEN__
#include <emscripten/val.h>
+#endif
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
@@ -646,6 +648,7 @@ i32 registry_getCanvasEntity(ecs::Registry& registry) {
return -1;
}
+#ifdef __EMSCRIPTEN__
emscripten::val registry_getCameraEntities(ecs::Registry& registry) {
auto cameraView = registry.view<ecs::Camera, ecs::Transform>();
auto result = emscripten::val::array();
@@ -671,6 +674,7 @@ emscripten::val getChildEntities(ecs::Registry& registry, u32 entity) {
}
return result;
}
+#endif
u32 registry_getGeneration(ecs::Registry& registry, u32 entity) {
return Entity::fromRaw(entity).generation();
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index b79df8214..ae93c4dbb 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -6,9 +6,14 @@
#include "../core/Types.hpp"
#include <string>
+// The value type embind returns for array/object results. Web-only: a native
+// build compiles this same TU (see cmake/ESEngineSources.cmake) and simply does
+// not carry the entry points that return one.
+#ifdef __EMSCRIPTEN__
namespace emscripten {
class val;
}
+#endif
namespace esengine {
@@ -143,8 +148,10 @@ u32 renderer_getPreviewHeight();
void renderer_setTextureParams(u32 textureId, i32 minFilter, i32 magFilter, i32 wrapS, i32 wrapT);
i32 registry_getCanvasEntity(ecs::Registry& registry);
+#ifdef __EMSCRIPTEN__
emscripten::val registry_getCameraEntities(ecs::Registry& registry);
emscripten::val getChildEntities(ecs::Registry& registry, u32 entity);
+#endif
u32 registry_getGeneration(ecs::Registry& registry, u32 entity);
void registry_batchSyncPhysicsTransforms(ecs::Registry& registry, uintptr_t bufferPtr, int count, float ppu);
diff --git a/tools/eht/__main__.py b/tools/eht/__main__.py
index 61d362201..05e0f5d9f 100644
--- a/tools/eht/__main__.py
+++ b/tools/eht/__main__.py
@@ -9,9 +9,35 @@ from .abi import compute_abi_hash
from .generators import (
EmbindGenerator, TypeScriptGenerator, MetadataGenerator,
PtrLayoutGenerator, EditorAPIGenerator, NativeBindingsGenerator,
+ NativeFunctionsGenerator,
)
+def _emit_native_functions(args) -> int:
+ """Emit the opt-in QuickJS wrappers for the engine's binding entry points —
+ the same declarations embind registers, so the two cannot drift."""
+ headers = []
+ for path in args.native_functions:
+ if not path.is_file():
+ print(f"[FAIL] --native-functions: no such header: {path}")
+ return 1
+ # The generated TU includes the header the way the binding TUs do.
+ include = f'esengine/bindings/{path.name}'
+ headers.append((include, path.read_text(encoding='utf-8')))
+
+ gen = NativeFunctionsGenerator(headers, shim_header=args.native_shim)
+ content = gen.generate()
+ args.native_functions_output.parent.mkdir(parents=True, exist_ok=True)
+ 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")
+ # 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:
+ print(f" skipped {skip.name}: {skip.reason}")
+ return 0
+
+
def _emit_native(components, enums, args) -> None:
"""Emit the opt-in native (QuickJS) bindings from the parsed reflection —
the native sibling of WebBindings.generated.cpp, one reflection source."""
@@ -52,10 +78,26 @@ def main() -> int:
# web/editor/TS *.generated.* files at all (no throwaway output dirs needed).
parser.add_argument('--native-only', action='store_true',
help='With --native-output: emit only the native bindings')
+ # Opt-in QuickJS wrappers for the engine's binding ENTRY POINTS (renderer_*,
+ # uiLayout_*, …), parsed from the bindings headers embind registers from.
+ parser.add_argument('--native-functions', type=Path, nargs='+', default=None,
+ 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)')
args = parser.parse_args()
print("EHT - ESEngine Header Tool")
+ # Function wrappers are parsed from declarations, not component reflection —
+ # emit them before (and independently of) the component pass.
+ if args.native_functions:
+ if args.native_functions_output is None:
+ print("[FAIL] --native-functions requires --native-functions-output.")
+ return 1
+ code = _emit_native_functions(args)
+ if code != 0 or args.native_output is None:
+ return code
+
cpp_parser = CppParser()
for input_dir in args.input:
print(f"Parsing: {input_dir}")
diff --git a/tools/eht/generators/__init__.py b/tools/eht/generators/__init__.py
index 77632f646..d4eafabed 100644
--- a/tools/eht/generators/__init__.py
+++ b/tools/eht/generators/__init__.py
@@ -6,8 +6,10 @@ from .metadata import MetadataGenerator
from .ptr_layout import PtrLayoutGenerator
from .editor_api import EditorAPIGenerator
from .native_bindings import NativeBindingsGenerator
+from .native_functions import NativeFunctionsGenerator
__all__ = [
'EmbindGenerator', 'TypeScriptGenerator', 'MetadataGenerator',
'PtrLayoutGenerator', 'EditorAPIGenerator', 'NativeBindingsGenerator',
+ 'NativeFunctionsGenerator',
]
diff --git a/tools/eht/generators/native_functions.py b/tools/eht/generators/native_functions.py
new file mode 100644
index 000000000..747506ca2
--- /dev/null
+++ b/tools/eht/generators/native_functions.py
@@ -0,0 +1,275 @@
+"""Native (QuickJS) wrappers for the engine's binding ENTRY POINTS.
+
+The component half of the boundary has been generated from one reflection source
+for a while (``native_bindings.py`` + ``embind.py``). The function half was not:
+every entry point the SDK calls — ``renderer_begin``, ``renderer_submitAll``,
+``uiLayout_update``, … — was declared once in C++ and then bound BY HAND, once in
+embind for the web and once more in the native host. Which is why anything JS
+drives (the frame, the UI layout, tilemaps, particles) worked on the web and had
+to be rewritten in C++ to work on a device.
+
+This generator removes the second hand-written copy. It reads the declarations in
+``bindings/*.hpp`` — the same ones embind registers — and emits a QuickJS wrapper
+per function that marshals the arguments and calls it. The BODY is shared: the
+binding TU itself compiles natively (see cmake/ESEngineSources.cmake), so both
+platforms run the same implementation; only the registration differs.
+
+The mapping is small because the declarations are:
+
+ ``ecs::Registry&`` the host has exactly one registry, so it is implicit and
+ consumes no JS argument
+ scalars u32/i32/f32/f64/bool/int/float/double
+ ``uintptr_t`` ptr a JS ArrayBuffer / typed array; the wrapper copies the
+ bytes and passes a real pointer (the same BoundarySpan
+ validation runs inside the binding)
+ returns void / integer / float / bool
+
+Anything else — ``emscripten::val`` results, ``std::string``, typed pointers — is
+SKIPPED and reported, never silently dropped: the skip list is what tells you
+which entry points still need a hand-written binding.
+"""
+
+import re
+from typing import List, NamedTuple, Optional, Tuple
+
+# What the wrapper can marshal, and how each maps to a QuickJS read.
+_INT_TYPES = {'i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64',
+ 'int', 'int32_t', 'uint32_t', 'size_t', 'long'}
+_FLOAT_TYPES = {'f32', 'f64', 'float', 'double'}
+_BOOL_TYPES = {'bool'}
+_VOID = 'void'
+
+# `void name(args);` on one or more lines, inside the header's namespace.
+_DECL = re.compile(
+ r'^(?P<ret>[A-Za-z_][\w:]*(?:\s*\*)?)\s+(?P<name>[A-Za-z_]\w*)\s*\((?P<args>[^;{]*)\)\s*;',
+ re.MULTILINE | re.DOTALL,
+)
+
+
+class Param(NamedTuple):
+ cpp_type: str
+ name: str
+
+
+class Function(NamedTuple):
+ name: str
+ ret: str
+ params: List[Param]
+ # The feature gates the declaration sits under (ES_ENABLE_SPINE, …). The
+ # wrapper carries them verbatim, so the generated TU tracks whatever the
+ # build enables instead of assuming a fixed feature set.
+ guards: Tuple[str, ...] = ()
+
+
+class Skipped(NamedTuple):
+ name: str
+ reason: str
+
+
+def _clean(t: str) -> str:
+ return ' '.join(t.replace('const', '').split()).strip()
+
+
+def parse_header(text: str) -> Tuple[List[Function], List[Skipped]]:
+ """Parse the declarations of one bindings header, in file order.
+
+ Declarations under an ``#ifdef __EMSCRIPTEN__`` are skipped outright: those
+ are the web-only entry points (they return an ``emscripten::val``), and the
+ native build does not even compile them.
+ """
+ functions: List[Function] = []
+ skipped: List[Skipped] = []
+
+ # Walk the header keeping the preprocessor stack: __EMSCRIPTEN__ regions are
+ # dropped outright (web-only entry points the native build does not compile),
+ # every other gate is remembered and re-emitted around the wrapper.
+ kept: List[str] = []
+ guards_per_line: List[Tuple[str, ...]] = []
+ stack: List[Optional[str]] = [] # None = a web-only region being dropped
+ for line in text.splitlines():
+ token = line.strip()
+ if token.startswith('#ifdef ') or token.startswith('#ifndef ') or token.startswith('#if '):
+ name = token.split(None, 1)[1].strip() if ' ' in token else ''
+ stack.append(None if name == '__EMSCRIPTEN__' else name)
+ continue
+ if token.startswith('#endif'):
+ if stack:
+ stack.pop()
+ continue
+ if token.startswith('#else') or token.startswith('#elif'):
+ # An #else of a dropped region is kept-but-ungated, and vice versa;
+ # the bindings headers do not use it, so treat it as a plain region.
+ if stack:
+ stack[-1] = stack[-1] and f'!{stack[-1]}'
+ continue
+ if any(g is None for g in stack):
+ continue
+ kept.append(line)
+ guards_per_line.append(tuple(g for g in stack if g))
+ body = '\n'.join(kept)
+
+ # Offset → line index, so a match can be attributed to its guard stack.
+ line_starts: List[int] = []
+ offset = 0
+ for line in kept:
+ line_starts.append(offset)
+ offset += len(line) + 1
+
+ def guards_at(pos: int) -> Tuple[str, ...]:
+ lo, hi = 0, len(line_starts) - 1
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if line_starts[mid] <= pos:
+ lo = mid
+ else:
+ hi = mid - 1
+ return guards_per_line[lo] if guards_per_line else ()
+
+ for match in _DECL.finditer(body):
+ ret = _clean(match.group('ret'))
+ name = match.group('name')
+ if name in {'if', 'for', 'while', 'switch', 'return', 'namespace', 'class'}:
+ continue
+ params, reason = _parse_params(match.group('args'))
+ if reason is None and not _returnable(ret):
+ reason = f'returns {ret}'
+ if reason is not None:
+ skipped.append(Skipped(name, reason))
+ continue
+ functions.append(Function(name, ret, params, guards_at(match.start())))
+ return functions, skipped
+
+
+def _parse_params(args: str) -> Tuple[List[Param], Optional[str]]:
+ params: List[Param] = []
+ args = args.strip()
+ if not args or args == 'void':
+ return params, None
+ for raw in args.split(','):
+ decl = _clean(raw)
+ if not decl:
+ continue
+ parts = decl.replace('&', ' & ').split()
+ # `ecs::Registry &registry` → the host's one registry, no JS argument.
+ if parts[0].endswith('Registry') and '&' in decl:
+ params.append(Param('ecs::Registry&', parts[-1]))
+ continue
+ if '&' in decl or '*' in decl:
+ return params, f'takes {decl}'
+ cpp_type = ' '.join(parts[:-1]) if len(parts) > 1 else parts[0]
+ name = parts[-1] if len(parts) > 1 else f'arg{len(params)}'
+ cpp_type = _clean(cpp_type)
+ if cpp_type not in _INT_TYPES | _FLOAT_TYPES | _BOOL_TYPES | {'uintptr_t'}:
+ return params, f'takes {cpp_type}'
+ params.append(Param(cpp_type, name))
+ return params, None
+
+
+def _returnable(ret: str) -> bool:
+ return ret == _VOID or ret in _INT_TYPES | _FLOAT_TYPES | _BOOL_TYPES
+
+
+# The engine's short scalar aliases live in namespace esengine; the plain C++
+# spellings do not and must stay unqualified.
+_PLAIN = {'int', 'long', 'float', 'double', 'bool', 'size_t', 'uintptr_t',
+ 'int32_t', 'uint32_t'}
+
+
+def _qualify(cpp_type: str) -> str:
+ return cpp_type if cpp_type in _PLAIN else f'esengine::{cpp_type}'
+
+
+class NativeFunctionsGenerator:
+ """Emit ``es_<name>`` QuickJS wrappers for parsed binding declarations."""
+
+ def __init__(self, headers: List[Tuple[str, str]], shim_header: str = 'esn_shim.hpp'):
+ # headers: (include path as the generated TU should spell it, source text)
+ self.headers = headers
+ self.shim_header = shim_header
+ self.skipped: List[Skipped] = []
+ self.emitted: List[str] = []
+
+ def _wrapper(self, fn: Function) -> List[str]:
+ js_params = [p for p in fn.params if p.cpp_type != 'ecs::Registry&']
+ out = [f'#ifdef {g}' for g in fn.guards]
+ out.append(f'static JSValue es_{fn.name}(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{')
+ if js_params:
+ out.append(f' if (argc < {len(js_params)}) return JS_UNDEFINED;')
+ out.append(' (void)argc; (void)argv;')
+
+ call_args: List[str] = []
+ js_index = 0
+ for param in fn.params:
+ if param.cpp_type == 'ecs::Registry&':
+ call_args.append('esn_reg()')
+ continue
+ local = f'a{js_index}'
+ if param.cpp_type == 'uintptr_t':
+ # A JS buffer: copy the bytes, then hand the binding a real pointer.
+ # Its own BoundarySpan check still runs on the other side.
+ out.append(f' std::vector<esengine::u8> {local}_bytes;')
+ out.append(f' esn_bytes(ctx, argv[{js_index}], {local}_bytes);')
+ out.append(f' const uintptr_t {local} = {local}_bytes.empty() ? 0 '
+ f': reinterpret_cast<uintptr_t>({local}_bytes.data());')
+ elif param.cpp_type in _BOOL_TYPES:
+ out.append(f' const bool {local} = JS_ToBool(ctx, argv[{js_index}]) != 0;')
+ elif param.cpp_type in _FLOAT_TYPES:
+ cpp = _qualify(param.cpp_type)
+ out.append(f' double {local}_d = 0; JS_ToFloat64(ctx, &{local}_d, argv[{js_index}]);')
+ out.append(f' const {cpp} {local} = static_cast<{cpp}>({local}_d);')
+ else:
+ cpp = _qualify(param.cpp_type)
+ out.append(f' int64_t {local}_i = 0; JS_ToInt64(ctx, &{local}_i, argv[{js_index}]);')
+ out.append(f' const {cpp} {local} = static_cast<{cpp}>({local}_i);')
+ call_args.append(local)
+ js_index += 1
+
+ call = f'esengine::{fn.name}({", ".join(call_args)})'
+ if fn.ret == _VOID:
+ out.append(f' {call};')
+ out.append(' return JS_UNDEFINED;')
+ elif fn.ret in _BOOL_TYPES:
+ out.append(f' return JS_NewBool(ctx, {call});')
+ elif fn.ret in _FLOAT_TYPES:
+ out.append(f' return JS_NewFloat64(ctx, static_cast<double>({call}));')
+ else:
+ out.append(f' return JS_NewInt64(ctx, static_cast<int64_t>({call}));')
+ out.append('}')
+ out.extend('#endif' for _ in fn.guards)
+ out.append('')
+ return out
+
+ def generate(self) -> str:
+ lines = [
+ '// Auto-generated by EHT (native_functions) — DO NOT EDIT.',
+ '// QuickJS wrappers for the engine binding entry points embind also registers,',
+ '// from the SAME declarations. The bodies live in the binding TUs, which this',
+ '// build compiles too — one implementation, two registration layers.',
+ f'#include "{self.shim_header}"',
+ '',
+ '#include <cstdint>',
+ '#include <vector>',
+ '',
+ ]
+ functions: List[Function] = []
+ for include, text in self.headers:
+ lines.append(f'#include "{include}"')
+ parsed, skipped = parse_header(text)
+ functions.extend(parsed)
+ self.skipped.extend(skipped)
+ lines.append('')
+
+ for fn in sorted(functions, key=lambda f: f.name):
+ self.emitted.append(fn.name)
+ lines.extend(self._wrapper(fn))
+
+ lines.append('void esn_register_functions(JSContext* ctx, JSValue global) {')
+ for fn in sorted(functions, key=lambda f: f.name):
+ js_arity = len([p for p in fn.params if p.cpp_type != 'ecs::Registry&'])
+ lines.extend(f'#ifdef {g}' for g in fn.guards)
+ lines.append(f' JS_SetPropertyStr(ctx, global, "es_{fn.name}", '
+ f'JS_NewCFunction(ctx, es_{fn.name}, "es_{fn.name}", {js_arity}));')
+ lines.extend('#endif' for _ in fn.guards)
+ lines.append('}')
+ lines.append('')
+ return '\n'.join(lines)