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(native): one frame, two backends — the SDK renders on device too

yhh32a1a9126840
diff --git a/native/host_js/game.js b/native/host_js/game.js
index c0e7e0438..3ddd3a6c7 100644
--- a/native/host_js/game.js
+++ b/native/host_js/game.js
@@ -10,13 +10,25 @@
var app, world, input, follower, orbit, t = 0.0;
function init() {
- es_setClear(0.07, 0.08, 0.12);
app = ESEngine.createNativeApp(globalThis.__esNativeBridge, globalThis);
app.tick(0); // sync through finishPlugins: binds input + inserts Input
world = app.world;
input = app.getResource(ESEngine.Input);
var assets = app.getResource(ESEngine.Assets);
+ // The frame belongs to the SDK here, exactly as on the web: a Canvas gives the
+ // design resolution and the clear colour, a Camera gives the projection. The
+ // host no longer decides either — it presents what this camera renders.
+ var stage = world.spawn();
+ world.insert(stage, ESEngine.Canvas, {
+ designResolution: { x: W, y: H }, scaleMode: 2 /* Expand */,
+ backgroundColor: { r: 0.07, g: 0.08, b: 0.12, a: 1 } });
+
+ var camera = world.spawn();
+ world.insert(camera, ESEngine.Transform, { position: { x: W * 0.5, y: H * 0.5, z: 0 } });
+ world.insert(camera, ESEngine.Camera, {
+ projectionType: 1 /* orthographic */, orthoSize: H * 0.5, isActive: true, clearFlags: 3 });
+
// Fallback 2x2 checker (a tiny inline texture) while the real image loads.
// Nearest filter + clamp (format 1, no flip, filter 0, wrap 1) so the scaled-up
// pixels stay crisp — the same import-settings path a cooked pixel-art texture
diff --git a/native/host_js/host_core.cpp b/native/host_js/host_core.cpp
index 51cb1eae0..f6cd2999b 100644
--- a/native/host_js/host_core.cpp
+++ b/native/host_js/host_core.cpp
@@ -34,6 +34,9 @@
#include "esengine/core/World.hpp"
#include "esengine/ecs/TransformSystem.hpp" // TransformSystem + ecs::setParent
#include "esengine/ecs/components/Hierarchy.hpp" // Parent / Children
+#include "esengine/ecs/components/Camera.hpp" // the scene queries the camera plugin makes
+#include "esengine/ecs/components/Canvas.hpp"
+#include "esengine/ecs/components/Transform.hpp"
#include "esengine/renderer/RenderContext.hpp"
#include "esengine/renderer/RenderFrame.hpp"
#include "esengine/renderer/Texture.hpp" // TextureSpecification + filter/wrap for import settings
@@ -128,6 +131,10 @@ 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;
};
@@ -512,6 +519,176 @@ JSValue js_submitTextBatch(JSContext* ctx, JSValueConst, int argc, JSValueConst*
return JS_UNDEFINED;
}
+// ---- the frame: es_renderer_* ------------------------------------------------
+//
+// 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;
+}
+
+// es_renderer_surfaceSize() -> { width, height }: the camera plugin reads it per
+// frame, so a rotation reaches the projection without an event.
+JSValue js_renderer_surfaceSize(JSContext* ctx, JSValueConst, int, JSValueConst*) {
+ JSValue o = JS_NewObject(ctx);
+ JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, g_app ? (int32_t)g_app->w : 0));
+ JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, g_app ? (int32_t)g_app->h : 0));
+ 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;
+ uint32_t n = 0;
+ // Active cameras with a Transform, as the web binding reports them.
+ for (auto entity : g_app->registry->view<ecs::Camera, ecs::Transform>()) {
+ if (g_app->registry->get<ecs::Camera>(entity).isActive) {
+ JS_SetPropertyUint32(ctx, arr, n++, JS_NewInt32(ctx, (int32_t)entity.id()));
+ }
+ }
+ return arr;
+}
+
std::vector<u8> readAsset(App& a, const char* path) {
return a.platform ? a.platform->readAsset(path) : std::vector<u8>{};
}
@@ -1061,6 +1238,23 @@ 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);
+ 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 —
// a host with no sound device binds none and falls back to the Null backend.
@@ -1212,6 +1406,7 @@ 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);
@@ -1231,19 +1426,24 @@ void frame() {
drainFetches(a);
pumpJs(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);
- const glm::mat4 vp = glm::ortho(0.0f, a.w, 0.0f, a.h);
- auto& rf = ctx.require<RenderFrame>();
- rf.begin(vp, 0, RenderFrame::PassClear{true, true, a.clear});
- rf.collectAll(*a.registry);
- // What the SDK draws from JS — glyph quads — goes in between collecting the
- // scene and flushing it, which is where the web pipeline runs the same
- // callbacks. Installed by the SDK's native runtime; absent if it has no text.
- callJs(a, "es_jsPreFlush", 0, nullptr);
- rf.flush();
- rf.end();
+ // The frame itself belongs to the SDK: app.tick above ran its render system,
+ // which resolved the scene's cameras and drove RenderFrame through the
+ // es_renderer_* bindings — the same code path the web build takes. What is
+ // 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) {
+ 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);
+ const glm::mat4 vp = glm::ortho(0.0f, a.w, 0.0f, a.h);
+ auto& rf = ctx.require<RenderFrame>();
+ rf.begin(vp, 0, RenderFrame::PassClear{true, true, a.clear});
+ rf.collectAll(*a.registry);
+ rf.flush();
+ rf.end();
+ }
a.gfx->present();
if (++a.frame % 120 == 0) LOGI("real-SDK frame %llu", (unsigned long long)a.frame);
}
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index 526f23edb..935c295b8 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -65,8 +65,31 @@ function acquireCameraInfo(pool: CameraInfo[], index: number): CameraInfo {
// Canvas / Ortho Helpers
// =============================================================================
-function findCanvasData(module: ESEngineModule, registry: CppRegistry) {
- const entity = module.registry_getCanvasEntity(registry);
+/**
+ * The two scene queries this plugin makes of the engine. On web they are module
+ * functions over the embind registry; a native registry answers them itself (it
+ * has no module to route them through — see createNativeRegistry), so ask the
+ * registry first and fall through unchanged everywhere else.
+ */
+interface SceneQueryRegistry {
+ getCanvasEntity?(): number;
+ getCameraEntities?(): number[];
+}
+
+function canvasEntityOf(module: ESEngineModule | null, registry: CppRegistry): number {
+ const own = (registry as CppRegistry & SceneQueryRegistry).getCanvasEntity;
+ if (own) return own.call(registry);
+ return module?.registry_getCanvasEntity(registry) ?? -1;
+}
+
+function cameraEntitiesOf(module: ESEngineModule | null, registry: CppRegistry): number[] {
+ const own = (registry as CppRegistry & SceneQueryRegistry).getCameraEntities;
+ if (own) return own.call(registry);
+ return module?.registry_getCameraEntities(registry) ?? [];
+}
+
+function findCanvasData(module: ESEngineModule | null, registry: CppRegistry) {
+ const entity = canvasEntityOf(module, registry);
if (entity < 0) return null;
return registry.getCanvas(entity);
}
@@ -211,7 +234,7 @@ export function buildCameraInfo(
/** Authored POVs of the scene's cameras (scene-filtered), no matrices built yet. */
function collectCameraPOVs(
- module: ESEngineModule,
+ module: ESEngineModule | null,
registry: CppRegistry,
width: number,
height: number,
@@ -219,7 +242,7 @@ function collectCameraPOVs(
activeScenes?: Set<string>,
): CameraPOV[] {
if (width === 0 || height === 0) return [];
- const cameraEntities = module.registry_getCameraEntities(registry);
+ const cameraEntities = cameraEntitiesOf(module, registry);
if (cameraEntities.length === 0) return [];
const filtered = activeScenes && world
@@ -238,7 +261,7 @@ function collectCameraPOVs(
}
export function collectCameras(
- module: ESEngineModule,
+ module: ESEngineModule | null,
registry: CppRegistry,
width: number,
height: number,
@@ -329,7 +352,7 @@ function resolveFitSource(app: App, canvas: CanvasScale | null): CanvasScale | n
function resolveCameras(
app: App,
- module: ESEngineModule,
+ module: ESEngineModule | null,
cppRegistry: CppRegistry,
width: number,
height: number,
@@ -376,7 +399,7 @@ function resolveCameras(
function syncUICameraInfo(
app: App,
- module: ESEngineModule,
+ module: ESEngineModule | null,
cppRegistry: CppRegistry,
width: number,
height: number,
@@ -424,7 +447,10 @@ export function cameraPlugin(
return {
name: 'camera',
build(app: App) {
- const module = app.wasmModule!;
+ // Null on the native core: the two engine queries this plugin makes are
+ // answered by the registry there (see canvasEntityOf / cameraEntitiesOf),
+ // and the frame itself goes through the Renderer's backend.
+ const module = app.wasmModule;
const cppRegistry = app.world.getCppRegistry()!;
const pipeline = app.pipeline!;
const startTime = platformNow();
@@ -474,7 +500,7 @@ export function cameraPlugin(
_fn: () => {
const { width, height } = viewport();
if (width === 0 || height === 0) return;
- const canvasEntity = module.registry_getCanvasEntity(cppRegistry);
+ const canvasEntity = canvasEntityOf(module, cppRegistry);
let clearColor: { x: number; y: number; z: number; w: number } | undefined;
if (canvasEntity >= 0) {
const canvas = cppRegistry.getCanvas(canvasEntity);
diff --git a/sdk/src/ecs/nativeBindings.ts b/sdk/src/ecs/nativeBindings.ts
index d0e2d7b85..9663f7c29 100644
--- a/sdk/src/ecs/nativeBindings.ts
+++ b/sdk/src/ecs/nativeBindings.ts
@@ -61,15 +61,47 @@ export function hasTextBindings(
}
/**
- * The other direction: what the HOST calls on the JS side, beyond the game's own
- * `update`. Declared here for the same reason as the es_* names — the C++ host
- * spells it once, the SDK installs it once.
+ * The frame. These are the engine calls the SDK's own render pipeline makes on
+ * web through the wasm module (`renderer_*`), bound here for a core that has no
+ * heap to marshal through — so the CAMERAS, viewports, clear flags, y-sort and
+ * pre-flush draws are decided by one implementation on both platforms, and the
+ * native host owns only its swapchain.
+ *
+ * Required as a set (a host that renders binds all of them); {@link
+ * hasRendererBindings} gates whether the SDK drives the frame at all, since a
+ * host may still own it while this lands.
+ */
+export const RENDERER_BINDINGS = {
+ resize: 'es_renderer_resize',
+ beginFrame: 'es_renderer_beginFrame',
+ updateTransforms: 'es_renderer_updateTransforms',
+ begin: 'es_renderer_begin',
+ submitAll: 'es_renderer_submitAll',
+ flush: 'es_renderer_flush',
+ end: 'es_renderer_end',
+ setStage: 'es_renderer_setStage',
+ setViewport: 'es_renderer_setViewport',
+ setYSortLayers: 'es_renderer_setYSortLayers',
+ stats: 'es_renderer_stats',
+ surfaceSize: 'es_renderer_surfaceSize',
+} 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(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): boolean {
+ return Object.values(RENDERER_BINDINGS).every((name) => typeof scope[name] === 'function');
+}
+
+/**
+ * Scene queries the wasm module answers as module-level functions over the
+ * registry. The native registry answers them itself (see createNativeRegistry);
+ * optional, since a host that binds neither simply has no cameras to render.
*/
-export const HOST_ENTRIES = {
- /** Run the render pipeline's pre-flush callbacks (the text batches). The host
- * calls it between collecting the scene and flushing the frame, which is
- * where the web pipeline runs them too. Absent unless the SDK installed it. */
- preFlush: 'es_jsPreFlush',
+export const SCENE_QUERY_BINDINGS = {
+ canvasEntity: 'es_registry_getCanvasEntity',
+ cameraEntities: 'es_registry_getCameraEntities',
} as const;
/** Platform primitives the SDK's bridge and file reading are built on. */
diff --git a/sdk/src/ecs/nativeRegistry.ts b/sdk/src/ecs/nativeRegistry.ts
index 598b2ec50..7087b8d7e 100644
--- a/sdk/src/ecs/nativeRegistry.ts
+++ b/sdk/src/ecs/nativeRegistry.ts
@@ -17,7 +17,7 @@
import type { CppRegistry } from '../wasm';
import type { Entity } from '../types';
import { PTR_ACCESSORS } from './ptrAccessors.generated';
-import { REGISTRY_BINDINGS } from './nativeBindings';
+import { REGISTRY_BINDINGS, SCENE_QUERY_BINDINGS } from './nativeBindings';
import { COMPONENT_META } from '../component.generated';
import { convertForWasm, convertFromWasm } from './BuiltinBridge';
@@ -40,6 +40,14 @@ function hostCall(scope: Record<string, unknown>, name: string, args: unknown[])
return (fn as (...a: unknown[]) => unknown)(...args);
}
+/** Optional host global — undefined (and no call) when unbound, for the queries a
+ * minimal host may not answer yet. */
+function hostCallOpt(scope: Record<string, unknown>, name: string, args: unknown[]): unknown {
+ const fn = scope[name];
+ if (typeof fn !== 'function') return undefined;
+ return (fn as (...a: unknown[]) => unknown)(...args);
+}
+
/** Present a JS array as the embind VectorEntity interface World.getChildren
* returns (size()/get(i)/delete()), so despawn iterates it the same on both
* backends. Native memory is JS-owned here, so delete() is a no-op. */
@@ -76,6 +84,16 @@ export function createNativeRegistry(
});
reg.delete = (): void => {};
+ // The scene queries the wasm module answers as module-level functions. There is
+ // no module here, so the registry answers them — the camera plugin asks the
+ // registry first and falls through to the module on web (see canvasEntityOf).
+ // Optional on the host: a host that binds neither simply has no cameras, which
+ // the plugin already treats as "nothing to render".
+ reg.getCanvasEntity = (): number =>
+ (hostCallOpt(scope, SCENE_QUERY_BINDINGS.canvasEntity, []) as number | undefined) ?? -1;
+ reg.getCameraEntities = (): number[] =>
+ (hostCallOpt(scope, SCENE_QUERY_BINDINGS.cameraEntities, []) as number[] | undefined) ?? [];
+
for (const cppName of Object.keys(PTR_ACCESSORS)) {
const accessor = PTR_ACCESSORS[cppName];
const bufFn = scope[`es_${cppName}_buffer`] as BufferFn | undefined; // getOrEmplace = add
diff --git a/sdk/src/ecs/nativeRenderer.ts b/sdk/src/ecs/nativeRenderer.ts
new file mode 100644
index 000000000..d961bab1b
--- /dev/null
+++ b/sdk/src/ecs/nativeRenderer.ts
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The native RendererBackend — the embedded-Dawn sibling of the wasm renderer
+// bindings the SDK's frame runs on.
+//
+// Before this, the native host wrote its own frame in C++: one hard-coded
+// orthographic projection, collect, flush, present. Everything the SDK decides
+// about a frame — which cameras exist, their viewport rects, clear flags and
+// ortho size, y-sort layers, which scenes are active, what draws just before the
+// flush — lived only on the web side, so each of those had to be re-implemented
+// natively or go missing.
+//
+// The frame is now ONE implementation (CameraPlugin -> RenderPipeline ->
+// Renderer) over two backends: the wasm module marshals through its heap, this
+// one calls the host's es_renderer_* bindings with the typed arrays as they are.
+// The C++ host keeps what only it can do: the swapchain and the present.
+
+import type { CppRegistry } from '../wasm';
+import type { RendererBackend, RenderStats } from '../renderer';
+import { RENDERER_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
+ * degraded frame). */
+function hostCall(scope: Record<string, unknown>, name: string, args: unknown[]): unknown {
+ const fn = scope[name];
+ if (typeof fn !== 'function') {
+ throw new Error(`native host binding "${name}" is missing`);
+ }
+ return (fn as (...a: unknown[]) => unknown)(...args);
+}
+
+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).
+ *
+ * The registry argument every wasm call carries is implicit here: a native host
+ * has exactly one C++ registry, the one it created the World over, so the
+ * bindings take none.
+ */
+export function createNativeRendererBackend(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): RendererBackend {
+ return {
+ // The renderer is already up: the host created the device and sized the
+ // surface before the SDK booted. Resizing still matters (rotation).
+ init: (): void => {},
+ resize: (width, height): void => {
+ hostCall(scope, RENDERER_BINDINGS.resize, [width, height]);
+ },
+ beginFrame: (elapsedSec): void => {
+ hostCall(scope, RENDERER_BINDINGS.beginFrame, [elapsedSec]);
+ },
+ updateTransforms: (_registry: CppRegistry): void => {
+ hostCall(scope, RENDERER_BINDINGS.updateTransforms, []);
+ },
+ begin: (viewProjection, target, clearFlags, r, g, b, a, clearX, clearY, clearW, clearH): void => {
+ hostCall(scope, RENDERER_BINDINGS.begin,
+ [viewProjection, target, clearFlags, r, g, b, a, clearX, clearY, clearW, clearH]);
+ },
+ submitAll: (_registry: CppRegistry, skipFlags, vpX, vpY, vpW, vpH): void => {
+ hostCall(scope, RENDERER_BINDINGS.submitAll, [skipFlags, vpX, vpY, vpW, vpH]);
+ },
+ flush: (): void => {
+ hostCall(scope, RENDERER_BINDINGS.flush, []);
+ },
+ end: (): void => {
+ hostCall(scope, RENDERER_BINDINGS.end, []);
+ },
+ setStage: (stage): void => {
+ hostCall(scope, RENDERER_BINDINGS.setStage, [stage]);
+ },
+ setViewport: (x, y, w, h): void => {
+ hostCall(scope, RENDERER_BINDINGS.setViewport, [x, y, w, h]);
+ },
+ setYSortLayers: (mask): void => {
+ hostCall(scope, RENDERER_BINDINGS.setYSortLayers, [mask >>> 0]);
+ },
+ getStats: (): RenderStats =>
+ (hostCall(scope, RENDERER_BINDINGS.stats, []) as RenderStats | undefined) ?? NO_STATS,
+ };
+}
+
+/**
+ * The drawable surface in pixels, as the host currently sees it. The camera
+ * plugin reads it every frame, so a rotation or a resized window reaches the
+ * projection without anyone pushing an event.
+ */
+export function nativeSurfaceSize(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): { width: number; height: number } {
+ const size = hostCall(scope, RENDERER_BINDINGS.surfaceSize, []) as
+ { width: number; height: number } | undefined;
+ return size ?? { width: 0, height: 0 };
+}
diff --git a/sdk/src/ecs/nativeRuntime.ts b/sdk/src/ecs/nativeRuntime.ts
index 71acad5f4..c8a5c1814 100644
--- a/sdk/src/ecs/nativeRuntime.ts
+++ b/sdk/src/ecs/nativeRuntime.ts
@@ -21,8 +21,13 @@ import { installNativePlatform, type NativeBridge } from '../platform/native';
import { createNativeRegistry } from './nativeRegistry';
import { NativeMemoryProvider } from './memoryProvider';
import { createNativeResourceManager } from './nativeResourceManager';
-import { HOST_ENTRIES, TEXT_BINDINGS, hasTextBindings } from './nativeBindings';
+import { TEXT_BINDINGS, hasTextBindings, hasRendererBindings } from './nativeBindings';
+import { createNativeRendererBackend, nativeSurfaceSize } from './nativeRenderer';
+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 { setNativeTextSubmit } from '../ui/text/submit';
import { initResourceManager } from '../resourceManager';
@@ -76,11 +81,12 @@ export function createNativeApp(
app.connectCpp(createNativeRegistry(scope), undefined, {
memory: new NativeMemoryProvider(scope),
});
- // The same stack a headless app runs — scenes, prefabs, timers, gameplay AI —
- // plus input. No renderer: the native C++ core owns drawing and reads the ECS
- // this app authors. assetPlugin is the one exception: it wires the wasm heap,
- // so installNativeAssets below builds the equivalent over the native RM.
- // Assets first: prefabs and scene loading declare it as a required resource.
+ // The same order the web app builds in (see _createWebApp): the frame first,
+ // then assets, then the gameplay stack. assetPlugin is the one plugin that
+ // 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.
+ installNativeRenderer(app, scope);
installNativeAssets(app, scope);
installNativeText(app, scope);
app.addPlugin(inputPlugin);
@@ -103,6 +109,31 @@ export function createNativeApp(
* wiring yet) — those arrive with the cooked-asset manifest in the export
* pipeline. Same-signature loaders, so it never diverges from the web channel.
*/
+/**
+ * Install the frame — the same `CameraPlugin` + `RenderPipeline` the web build
+ * runs, over the native core.
+ *
+ * The native host used to write its own frame in C++: one hard-coded projection,
+ * collect, flush, present. Every decision the SDK makes about a frame — which
+ * cameras exist, their viewport rects and clear flags, the design-resolution fit,
+ * y-sort layers, which scenes are active, what draws just before the flush —
+ * either had to be written a second time in C++ or was simply absent on device.
+ *
+ * With the renderer bindings in place the frame is the SDK's one implementation
+ * on both platforms, and the host keeps only what is genuinely its own: the
+ * 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 installNativeRenderer(app: App, scope: Record<string, unknown>): void {
+ if (!hasRendererBindings(scope)) return;
+ setRendererBackend(createNativeRendererBackend(scope));
+ app.setPipeline(new RenderPipeline());
+ app.insertResource(UICameraInfo, { ...DEFAULT_UI_CAMERA_INFO });
+ // The viewport is read per frame, so a rotation reaches the projection without
+ // anyone pushing a resize event.
+ app.addPlugin(cameraPlugin(() => nativeSurfaceSize(scope)));
+}
+
/**
* Install text — the same `TextPlugin` the web build runs, over the native core.
*
@@ -112,11 +143,9 @@ export function createNativeApp(
* takes the typed arrays and calls `RenderFrame::submitTextBatch` itself).
* Everything between, atlas through batching, is the SDK's one implementation.
*
- * The plugin draws from a pre-flush callback, so the app needs a
- * {@link RenderPipeline} to register into even though it owns no rendering; the
- * host runs those callbacks each frame through {@link HOST_ENTRIES.preFlush},
- * between collecting the scene and flushing it — the same point the web pipeline
- * runs them at.
+ * 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.
*
* 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.
@@ -131,13 +160,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);
});
-
- const pipeline = new RenderPipeline();
- app.setPipeline(pipeline);
app.addPlugin(textPlugin);
- scope[HOST_ENTRIES.preFlush] = (): void => {
- pipeline.runPreFlushCallbacks({ _cpp: app.world.getCppRegistry()! });
- };
}
function installNativeAssets(app: App, scope: Record<string, unknown>): void {
diff --git a/sdk/src/renderer.ts b/sdk/src/renderer.ts
index e0e18e880..dc12f98b5 100644
--- a/sdk/src/renderer.ts
+++ b/sdk/src/renderer.ts
@@ -31,15 +31,114 @@ export interface RenderStats {
culled: number;
}
+/**
+ * How a frame reaches the engine. The web marshals through the wasm heap; the
+ * native (embedded-Dawn) core takes the typed arrays as they are. One `Renderer`
+ * façade over two backends — the shape the ResourceManager and the memory
+ * provider already take — so the frame ORCHESTRATION (cameras, viewports, clear
+ * flags, pre-flush draws) is one implementation on both platforms instead of one
+ * per host.
+ *
+ * Only the frame lives here. Render targets, capture and the editor-side queries
+ * remain wasm-only below, and simply do nothing on a native build until they
+ * grow their own bindings.
+ */
+export interface RendererBackend {
+ init(width: number, height: number): void;
+ resize(width: number, height: number): void;
+ beginFrame(elapsedSec: number): void;
+ updateTransforms(registry: CppRegistry): void;
+ begin(viewProjection: Float32Array, target: number, clearFlags: number,
+ r: number, g: number, b: number, a: number,
+ clearX: number, clearY: number, clearW: number, clearH: number): void;
+ submitAll(registry: CppRegistry, skipFlags: number,
+ vpX: number, vpY: number, vpW: number, vpH: number): void;
+ flush(): void;
+ end(): void;
+ setStage(stage: number): void;
+ setViewport(x: number, y: number, w: number, h: number): void;
+ setYSortLayers(mask: number): void;
+ getStats(): RenderStats;
+}
+
+const NO_STATS: RenderStats = { drawCalls: 0, triangles: 0, sprites: 0, text: 0, spine: 0, meshes: 0, culled: 0 };
+
const bridge = new CoreApiBridge('renderer');
let module: ESEngineModule | null = null;
let viewProjectionPtr: number = 0;
+let backend: RendererBackend | null = null;
+
+/** The wasm backend: every call marshals through the module's heap, exactly as
+ * the Renderer always has. */
+function wasmBackend(m: ESEngineModule): RendererBackend {
+ return {
+ init: (width, height) => m.renderer_init(width, height),
+ resize: (width, height) => m.renderer_resize(width, height),
+ beginFrame: (elapsedSec) => m.renderer_beginFrame(elapsedSec),
+ updateTransforms: (registry) => {
+ try {
+ m.renderer_updateTransforms(registry);
+ } catch (e) {
+ handleWasmError(e, 'Renderer.updateTransforms');
+ }
+ },
+ begin: (viewProjection, target, clearFlags, r, g, b, a, clearX, clearY, clearW, clearH) => {
+ if (!viewProjectionPtr) return;
+ try {
+ m.HEAPF32.set(viewProjection, viewProjectionPtr / 4);
+ m.renderer_begin(viewProjectionPtr, target, clearFlags, r, g, b, a, clearX, clearY, clearW, clearH);
+ } catch (e) {
+ handleWasmError(e, 'Renderer.begin');
+ }
+ },
+ submitAll: (registry, skipFlags, vpX, vpY, vpW, vpH) => {
+ try {
+ m.renderer_submitAll(registry, skipFlags, vpX, vpY, vpW, vpH);
+ } catch (e) {
+ handleWasmError(e, 'Renderer.submitAll');
+ }
+ },
+ flush: () => {
+ try {
+ m.renderer_flush();
+ } catch (e) {
+ handleWasmError(e, 'Renderer.flush');
+ }
+ },
+ end: () => {
+ try {
+ m.renderer_end();
+ } catch (e) {
+ handleWasmError(e, 'Renderer.end');
+ }
+ },
+ setStage: (stage) => m.renderer_setStage(stage),
+ setViewport: (x, y, w, h) => m.renderer_setViewport(x, y, w, h),
+ setYSortLayers: (mask) => m.renderer_setYSortLayers?.(mask >>> 0),
+ getStats: () => ({
+ drawCalls: m.renderer_getDrawCalls(),
+ triangles: m.renderer_getTriangles(),
+ sprites: m.renderer_getSprites(),
+ text: m.renderer_getText(),
+ spine: m.renderer_getSpine?.() ?? 0,
+ meshes: m.renderer_getMeshes(),
+ culled: m.renderer_getCulled(),
+ }),
+ };
+}
/** @internal Wired by the engine plugins — not part of the public API. */
export function initRendererAPI(wasmModule: ESEngineModule): void {
bridge.connect(wasmModule);
module = bridge.module;
viewProjectionPtr = module._malloc(16 * 4);
+ backend = wasmBackend(module);
+}
+
+/** @internal Install a non-wasm backend (the native host's). Mirrors
+ * {@link initRendererAPI} for a core that has no heap to marshal through. */
+export function setRendererBackend(next: RendererBackend | null): void {
+ backend = next;
}
export function shutdownRendererAPI(): void {
@@ -49,28 +148,24 @@ export function shutdownRendererAPI(): void {
}
bridge.disconnect();
module = null;
+ backend = null;
}
export const Renderer = {
init(width: number, height: number): void {
- module?.renderer_init(width, height);
+ backend?.init(width, height);
},
resize(width: number, height: number): void {
- module?.renderer_resize(width, height);
+ backend?.resize(width, height);
},
beginFrame(elapsedSec = 0): void {
- module?.renderer_beginFrame(elapsedSec);
+ backend?.beginFrame(elapsedSec);
},
updateTransforms(registry: { _cpp: CppRegistry }): void {
- if (!module) return;
- try {
- module.renderer_updateTransforms(registry._cpp);
- } catch (e) {
- handleWasmError(e, 'Renderer.updateTransforms');
- }
+ backend?.updateTransforms(registry._cpp);
},
/**
@@ -81,44 +176,25 @@ export const Renderer = {
begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags = 0,
clearColor?: { x: number; y: number; z: number; w: number },
clearRect?: { x: number; y: number; w: number; h: number }): void {
- if (!module || !viewProjectionPtr) return;
- try {
- module.HEAPF32.set(viewProjection, viewProjectionPtr / 4);
- module.renderer_begin(viewProjectionPtr, target ?? 0, clearFlags,
- clearColor?.x ?? 0, clearColor?.y ?? 0, clearColor?.z ?? 0, clearColor?.w ?? 1,
- clearRect?.x ?? 0, clearRect?.y ?? 0, clearRect?.w ?? 0, clearRect?.h ?? 0);
- } catch (e) {
- handleWasmError(e, 'Renderer.begin');
- }
+ backend?.begin(viewProjection, target ?? 0, clearFlags,
+ clearColor?.x ?? 0, clearColor?.y ?? 0, clearColor?.z ?? 0, clearColor?.w ?? 1,
+ clearRect?.x ?? 0, clearRect?.y ?? 0, clearRect?.w ?? 0, clearRect?.h ?? 0);
},
flush(): void {
- try {
- module?.renderer_flush();
- } catch (e) {
- handleWasmError(e, 'Renderer.flush');
- }
+ backend?.flush();
},
end(): void {
- try {
- module?.renderer_end();
- } catch (e) {
- handleWasmError(e, 'Renderer.end');
- }
+ backend?.end();
},
submitAll(registry: { _cpp: CppRegistry }, skipFlags: number, vpX: number, vpY: number, vpW: number, vpH: number): void {
- if (!module) return;
- try {
- module.renderer_submitAll(registry._cpp, skipFlags, vpX, vpY, vpW, vpH);
- } catch (e) {
- handleWasmError(e, 'Renderer.submitAll');
- }
+ backend?.submitAll(registry._cpp, skipFlags, vpX, vpY, vpW, vpH);
},
setStage(stage: RenderStage): void {
- module?.renderer_setStage(stage);
+ backend?.setStage(stage);
},
createRenderTarget(width: number, height: number, flags: number = 1): RenderTargetHandle {
@@ -142,12 +218,12 @@ export const Renderer = {
},
setViewport(x: number, y: number, w: number, h: number): void {
- module?.renderer_setViewport(x, y, w, h);
+ backend?.setViewport(x, y, w, h);
},
/** Layers (bits 0..31) that sort by world Y within the layer — top-down occlusion. */
setYSortLayers(mask: number): void {
- module?.renderer_setYSortLayers?.(mask >>> 0);
+ backend?.setYSortLayers(mask);
},
setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void {
@@ -160,18 +236,7 @@ export const Renderer = {
},
getStats(): RenderStats {
- if (!module) {
- return { drawCalls: 0, triangles: 0, sprites: 0, text: 0, spine: 0, meshes: 0, culled: 0 };
- }
- return {
- drawCalls: module.renderer_getDrawCalls(),
- triangles: module.renderer_getTriangles(),
- sprites: module.renderer_getSprites(),
- text: module.renderer_getText(),
- spine: module.renderer_getSpine?.() ?? 0,
- meshes: module.renderer_getMeshes(),
- culled: module.renderer_getCulled(),
- };
+ return backend?.getStats() ?? NO_STATS;
},
captureNextFrame(): void {
diff --git a/sdk/tests/native-text.test.ts b/sdk/tests/native-text.test.ts
index 834b87cbd..04811d201 100644
--- a/sdk/tests/native-text.test.ts
+++ b/sdk/tests/native-text.test.ts
@@ -2,23 +2,23 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file native-text.test.ts
- * @brief Text on the native core: the SAME TextPlugin, glyph atlas and layout
- * the web build runs, with the two things a device cannot share —
- * a glyph source (no 2D canvas) and the batch submit (no wasm heap) —
- * crossing to the host.
+ * @brief A frame on the native core: the SAME camera plugin, render pipeline,
+ * glyph atlas and layout the web build runs, over a mock host scope.
*
- * A mock host scope stands in for the QuickJS globals, so a `Text` entity goes
- * end-to-end headless: rasterize each codepoint → pack the atlas page (created
- * through the native ResourceManager and filled by sub-region uploads) → lay the
- * glyphs out → submit one batch per page through `es_submitTextBatch`.
+ * Two things a device cannot share — a glyph source (no 2D canvas) and the
+ * batch submit (no wasm heap) — cross to the host; everything else is the SDK's
+ * one implementation. `app.tick` therefore has to produce a whole frame here:
+ * resolve the scene's camera, open the pass, collect, draw the text between
+ * collect and flush, close it. That order IS the contract with the host, which
+ * only presents afterwards.
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createNativeApp } from '../src/ecs/nativeRuntime';
-import { HOST_ENTRIES } from '../src/ecs/nativeBindings';
import { shutdownResourceManager } from '../src/resourceManager';
import { setPlatform } from '../src/platform/base';
+import { setRendererBackend } from '../src/renderer';
import { setNativeTextSubmit, TEXT_VERTEX_FLOATS } from '../src/ui/text/submit';
-import { Transform } from '../src/component';
+import { Camera, Canvas, Transform } from '../src/component';
import { Text, TextRenderMode } from '../src/ui/core/text';
import { PTR_ACCESSORS } from '../src/ecs/ptrAccessors.generated';
import type { PlatformGlyphRequest } from '../src/platform/types';
@@ -59,6 +59,11 @@ function installMockEcs(scope: Record<string, unknown>): void {
function makeHostScope() {
const textures = new Map<number, { width: number; height: number }>();
const uploads: { handle: number; x: number; y: number; w: number; h: number; bytes: number }[] = [];
+ // What the host was asked to do this frame, in order.
+ const calls: string[] = [];
+ const beginSpy = vi.fn();
+ let canvasEntity = -1;
+ let cameraEntities: number[] = [];
let nextHandle = 1;
const rasterizeSpy = vi.fn((request: PlatformGlyphRequest) => ({
pixels: new Uint8Array(8 * 8 * 4).fill(255),
@@ -85,10 +90,29 @@ function makeHostScope() {
uploads.push({ handle, x, y, w, h, bytes: pixels.length });
},
es_rasterizeGlyph: rasterizeSpy,
- es_submitTextBatch: submitSpy,
+ es_submitTextBatch: (...args: unknown[]) => { calls.push('text'); submitSpy(...args); },
+ // The frame surface: the SDK's camera plugin + pipeline drive these, and
+ // the order they arrive in is what the host's frame depends on.
+ es_renderer_resize: () => { calls.push('resize'); },
+ es_renderer_beginFrame: () => { calls.push('beginFrame'); },
+ es_renderer_updateTransforms: () => { calls.push('updateTransforms'); },
+ es_renderer_begin: (...args: unknown[]) => { calls.push('begin'); beginSpy(...args); },
+ es_renderer_submitAll: () => { calls.push('submitAll'); },
+ es_renderer_flush: () => { calls.push('flush'); },
+ es_renderer_end: () => { calls.push('end'); },
+ 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_surfaceSize: () => ({ width: 800, height: 600 }),
+ es_registry_getCanvasEntity: () => canvasEntity,
+ es_registry_getCameraEntities: () => cameraEntities,
};
installMockEcs(scope);
- return { scope, uploads, rasterizeSpy, submitSpy };
+ return {
+ scope, uploads, calls, rasterizeSpy, submitSpy, beginSpy,
+ setScene: (canvas: number, cameras: number[]) => { canvasEntity = canvas; cameraEntities = cameras; },
+ };
}
/** The bridge half of the same host: the glyph rasterizer reaches the SDK through
@@ -112,27 +136,52 @@ function makeBridge(scope: Record<string, unknown>): NativeBridge {
afterEach(() => {
shutdownResourceManager();
setNativeTextSubmit(null);
+ setRendererBackend(null);
setPlatform(null as never);
});
-describe('text on the native core', () => {
- it('rasterizes through the host, fills an atlas page and submits one batch', async () => {
- const { scope, uploads, rasterizeSpy, submitSpy } = makeHostScope();
+/** Author the scene the frame renders: a Canvas (clear colour), a Camera, and a
+ * Text label. Returns the label, whose glyphs the assertions follow. */
+function buildScene(app: ReturnType<typeof createNativeApp>, setScene: (canvas: number, cameras: number[]) => void) {
+ const world = app.world;
+ const canvas = world.spawn();
+ world.insert(canvas, Canvas, { backgroundColor: { r: 0.1, g: 0.2, b: 0.3, a: 1 } });
+ const camera = world.spawn();
+ world.insert(camera, Transform, {});
+ world.insert(camera, Camera, { projectionType: 1, orthoSize: 300, isActive: true, clearFlags: 3 });
+ setScene(canvas, [camera]);
+
+ const label = world.spawn();
+ world.insert(label, Transform, {});
+ // Pin the SDF pipeline: Auto reads the entity's world scale, which the C++
+ // TransformSystem computes on a device and this mock leaves at zero.
+ world.insert(label, Text, { content: 'Hi', fontSize: 32, renderMode: TextRenderMode.Sdf });
+ return label;
+}
+
+describe('a frame on the native core', () => {
+ it('renders the scene through the SDK pipeline, text and all', async () => {
+ const { scope, uploads, calls, rasterizeSpy, submitSpy, beginSpy, setScene } = makeHostScope();
const app = createNativeApp(makeBridge(scope), scope);
await app.tick(0);
- const entity = app.world.spawn();
- app.world.insert(entity, Transform, {});
- // Pin the SDF pipeline: Auto reads the entity's world scale, which the C++
- // TransformSystem computes on a device and this mock leaves at zero.
- app.world.insert(entity, Text, { content: 'Hi', fontSize: 32, renderMode: TextRenderMode.Sdf });
+ const entity = buildScene(app, setScene);
+ calls.length = 0; // watch one frame, with the scene in place
await app.tick(1 / 60);
- // The host runs the pipeline's pre-flush callbacks itself, between
- // collecting the scene and flushing it.
- const preFlush = scope[HOST_ENTRIES.preFlush] as () => void;
- expect(typeof preFlush).toBe('function');
- preFlush();
+ // 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.
+ expect(calls.filter((c) => c === 'begin' || c === 'submitAll' || c === 'text' || c === 'flush' || c === 'end'))
+ .toEqual(['begin', 'submitAll', 'text', 'flush', 'end']);
+
+ // The pass cleared to the Canvas' background colour — the scene's, not a
+ // colour the host picked.
+ const [, , clearFlags, r, g, b] = beginSpy.mock.calls[beginSpy.mock.calls.length - 1];
+ expect(clearFlags).toBe(3);
+ expect(r).toBeCloseTo(0.1, 5); // f32 round-trip through the component
+ expect(g).toBeCloseTo(0.2, 5);
+ expect(b).toBeCloseTo(0.3, 5);
// One rasterize per distinct codepoint, asking for the SDF encoding.
expect(rasterizeSpy).toHaveBeenCalledTimes(2);
@@ -158,21 +207,34 @@ describe('text on the native core', () => {
expect((transform as Float32Array).length).toBe(16);
});
- it('draws nothing — and boots — on a host with no font stack', async () => {
- const { scope, submitSpy } = makeHostScope();
+ it('still renders the scene on a host with no font stack — just no text', async () => {
+ const { scope, calls, submitSpy, setScene } = makeHostScope();
delete scope.es_rasterizeGlyph;
const bridge = makeBridge(scope);
delete (bridge as { rasterizeGlyph?: unknown }).rasterizeGlyph;
const app = createNativeApp(bridge, scope);
await app.tick(0);
- const entity = app.world.spawn();
- app.world.insert(entity, Transform, {});
- app.world.insert(entity, Text, { content: 'Hi' });
+ buildScene(app, setScene);
await app.tick(1 / 60);
- // The plugin was never installed, so there is no pre-flush entry at all.
- expect(scope[HOST_ENTRIES.preFlush]).toBeUndefined();
+ expect(calls).toContain('begin');
+ expect(calls).toContain('flush');
expect(submitSpy).not.toHaveBeenCalled();
});
+
+ it('leaves the frame to the host when it bound no renderer', async () => {
+ const { scope, calls, setScene } = makeHostScope();
+ for (const name of Object.keys(scope).filter((n) => n.startsWith('es_renderer_'))) delete scope[name];
+
+ const app = createNativeApp(makeBridge(scope), scope);
+ await app.tick(0);
+ 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.
+ expect(calls).toEqual([]);
+ expect(app.pipeline).toBeNull();
+ });
});