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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(native): text on the device — the same Text, atlas and layout as the web
yhh35d0ccb9e9f9
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txtindex b81c595ad..e017339dd 100644--- a/native/CMakeLists.txt+++ b/native/CMakeLists.txt@@ -73,19 +73,20 @@ endif()set(ESENGINE_ROOT "${REPO}")list(APPEND CMAKE_MODULE_PATH "${REPO}/cmake")set(ES_ENABLE_WEBGPU ON)+# Text is on: the SDK's `Text` draws through the shared glyph atlas (the host+# rasterizes — see host_js/glyph_raster.cpp — and needs the engine's own+# SdfGenerator so both platforms encode the field identically), and the C+++# BitmapText path comes along with it. Neither needs freetype/msdfgen.+set(ES_ENABLE_BITMAP_TEXT ON)include(ESEngineSources)-# BitmapFont is self-contained (no freetype/msdfgen) and ResourceManager references-# it, so the WebGPU-only build (ES_ENABLE_BITMAP_TEXT off) still needs this one TU.-list(APPEND ESENGINE_SOURCES ${SRC}/esengine/text/BitmapFont.cpp)-add_library(esengine STATIC ${ESENGINE_SOURCES})target_include_directories(esengine PUBLIC"${SRC}" "${TP}/stb""${ESTELLA_DAWN_DIR}/include" # <webgpu/webgpu.h> forwarder"${ESTELLA_DAWN_BUILD}/gen/include") # generated <dawn/webgpu.h>-target_compile_definitions(esengine PUBLIC ES_ENABLE_WEBGPU) # NOT ES_PLATFORM_WEB / ES_ENABLE_BITMAP_TEXT+target_compile_definitions(esengine PUBLIC ES_ENABLE_WEBGPU ES_ENABLE_BITMAP_TEXT) # NOT ES_PLATFORM_WEBtarget_link_libraries(esengine PUBLIC glm yogacore webgpu_dawn)# Reference host: boots EstellaContext with an injected WebGPUDevice over the@@ -133,7 +134,8 @@ if(ESTELLA_QUICKJS_DIR)# Static: the thin Xcode app (native/ios) links this plus the libraries# 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 "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_BINDINGS}")+ host_js/native_audio.cpp host_js/ktx2_decode.cpp host_js/glyph_raster.cpp+ "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_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@@ -142,7 +144,8 @@ if(ESTELLA_QUICKJS_DIR)COMPILE_OPTIONS "-x;objective-c++")target_link_libraries(estella_js_host esengine qjs"-framework UIKit" "-framework QuartzCore" "-framework Foundation"- "-framework AVFoundation" "-framework CoreAudio" "-framework AudioToolbox")+ "-framework AVFoundation" "-framework CoreAudio" "-framework AudioToolbox"+ "-framework CoreText" "-framework CoreGraphics")# Merge host + engine + deps + Dawn into ONE archive, so the Xcode app is a# thin shell that links a single library at a fixed path (native/ios).add_custom_command(TARGET estella_js_host POST_BUILD@@ -154,7 +157,8 @@ if(ESTELLA_QUICKJS_DIR)# Android: plain C++; miniaudio dlopens AAudio/OpenSL at runtime (no extra# 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 "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_BINDINGS}")+ host_js/native_audio.cpp host_js/ktx2_decode.cpp host_js/glyph_raster.cpp+ "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_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/README.md b/native/README.mdindex 4cb761d84..0af39a5fe 100644--- a/native/README.md+++ b/native/README.md@@ -39,7 +39,8 @@ the tree:|---|---|---|| Render surface | `WebGPUDevice::configureSurface(NativeSurface)` | `CAMetalLayer*` / `ANativeWindow*` → `WGPUSurface` (commit `bfc495da`) || Instance / present | `WebGPUDevice(device, instance)` + `present()` | host shares its instance; flips the swapchain (native-only) |-| GL / text gates | `EstellaContext` under `ES_PLATFORM_WEB` / `ES_ENABLE_BITMAP_TEXT` | native drops the WebGL entry + optional bitmap text |+| GL gate | `EstellaContext` under `ES_PLATFORM_WEB` | native drops the WebGL entry |+| Glyph source | `Platform::loadFont` + `host_js/glyph_raster.cpp` | the device has no 2D canvas: the OS names a font file, stb_truetype rasterizes, the engine's own `sdfFromAlpha` encodes || Bindings | `python -m eht --native-output` | `es_set_<C>` / `es_<C>_buffer` from the same reflection as the web embind bindings || Data marshalling | `sdk/src/ecs/ptrAccessors.generated.ts` | POD components are wasm32/arm64 layout-identical → the generated accessors write native component memory unchanged (via a zero-copy `ArrayBuffer`) || Host platform | `eshost::Platform` (`host_js/host_core.hpp`) | packaged assets, cache dir, backend, window surface + size, log — the only things the two OS glue files answer differently |@@ -245,6 +246,19 @@ System bindings landing incrementally through the real SDK surfaces:differs per platform. Replies cross back thread-safely (`deliverFetch`) and run on the JSthread in the frame loop. This is what remote asset groups and hot-update need. Simulator-verified (an HTTPS GET returns bytes and a 200); the Android path needs a device retest.+- **Text** (Stage C) — the same `Text` component, glyph atlas, layout and batching the web+ build runs. Only the two ends cross the seam: the device has no 2D canvas to rasterize a+ glyph on, so the host does it (`es_rasterizeGlyph` → `glyph_raster.cpp`: the OS names the+ font file, stb_truetype rasterizes the outline, and the engine's OWN `text::sdfFromAlpha`+ encodes the field, so the shared SDF shader samples identically encoded tiles on both+ platforms); and there is no wasm heap to marshal the laid-out quads through, so the host+ takes the typed arrays and calls `RenderFrame::submitTextBatch` itself (`es_submitTextBatch`,+ run from `es_jsPreFlush` between collecting the scene and flushing it — where the web+ pipeline runs the same callbacks). Picking the font file is the only per-OS part: Android's+ `AFontMatcher` and iOS's Core Text, both of which fall back per codepoint, so CJK resolves+ without a hard-coded path. Device-verified on Android (Latin + CJK, SDF). The C+++ `BitmapText` path compiles natively too (`ES_ENABLE_BITMAP_TEXT` is on — nothing in+ `src/esengine/text` needs freetype or msdfgen).- **KTX2 / compressed textures** — `Assets.loadTexture` on a `.ktx2` path transcodes withthe host's vendored basis_universal (`es_createTextureKTX2` → `ktx2_decode.cpp`) to thebest format the device supports (ASTC → ETC2 → BC, RGBA32 fallback) and uploads the@@ -252,5 +266,11 @@ System bindings landing incrementally through the real SDK surfaces:4–8× less VRAM than RGBA8. The web KTX2 path (WebGL2 + wasm transcoder) is untouched.Simulator-verified (a 64×64 KTX2 sprite renders); base mip only for now.-Remaining: mip chains for compressed textures, and hardening on a physical device (audio-output, the background/foreground transition, Android's miniaudio audio + JNI fetch paths).+Remaining: hardening on a physical device (audio output, the background/foreground+transition, Android's miniaudio audio + JNI fetch paths), and the subsystems this build+still leaves out — tilemaps, particles and post-processing (their `ES_ENABLE_*` sources),+plus physics / Spine / video, which ship as emscripten side modules with no native+counterpart yet. An export names them: **Package Project → Mobile** warns about any of them+a scene uses rather than shipping a package that quietly renders half of it (the gaps are+declared in `desktop/src/project/targetSupport.ts`, checked against this CMakeLists by+`desktop/tests/target-support.test.ts`).diff --git a/native/host_js/game.js b/native/host_js/game.jsindex a9780c99e..c0e7e0438 100644--- a/native/host_js/game.js+++ b/native/host_js/game.js@@ -78,6 +78,16 @@ function init() {console.log('[demo] audio: no Audio resource');}+ // Stage: text through the SAME `Text` component a web game authors. The host+ // rasterizes each glyph from the OS font stack (there is no 2D canvas here)+ // and the SDK's glyph atlas, layout and batching do the rest — including the+ // per-codepoint font fallback that makes the CJK line resolve.+ var label = world.spawn();+ world.insert(label, ESEngine.Transform, { position: { x: W * 0.5, y: H * 0.62, z: 0 } });+ world.insert(label, ESEngine.Text, {+ content: 'Estella 原生文本', fontSize: S * 0.075, align: 1,+ color: { r: 1, g: 0.92, b: 0.4, a: 1 } });+// Stage: prove native networking — es_fetch over NSURLSession/OkHttp, TLS by// the OS. The async reply lands back on the JS thread via the frame loop.globalThis.__esNativeBridge.fetch('https://example.com').then(function (r) {diff --git a/native/host_js/glyph_raster.cpp b/native/host_js/glyph_raster.cppnew file mode 100644index 000000000..8d79fd758--- /dev/null+++ b/native/host_js/glyph_raster.cpp@@ -0,0 +1,154 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file glyph_raster.cpp+ * @brief Implements the native glyph source (see glyph_raster.hpp).+ */+#include "glyph_raster.hpp"++#include "host_core.hpp"++#include "esengine/text/SdfGenerator.hpp"++#include <algorithm>+#include <cmath>+#include <memory>+#include <unordered_map>++#define STB_TRUETYPE_IMPLEMENTATION+#include "stb_truetype.h"++namespace eshost {+namespace {++// The SDF is rasterized and distance-transformed at this multiple of the stored+// resolution, then box-downsampled — magnified glyphs stop showing the source+// grid as edge wobble. The SDK's canvas rasterizer supersamples by the same 4.+constexpr int SDF_SUPERSAMPLE = 4;++/** A parsed font file, kept for the life of the host: fonts are few, glyphs many. */+struct Font {+ std::vector<uint8_t> bytes;+ stbtt_fontinfo info{};+ bool ok = false;+};++/** Parsed fonts by file path — the matcher answers a path per glyph, and only a+ * path we have not seen costs a read + parse. */+std::unordered_map<std::string, std::unique_ptr<Font>> g_fonts;++Font* loadFont(Platform& platform, const std::string& family, uint32_t codepoint, int style) {+ FontFile file = platform.loadFont(family, codepoint, style);+ if (file.path.empty()) return nullptr;++ auto it = g_fonts.find(file.path);+ if (it != g_fonts.end()) return it->second->ok ? it->second.get() : nullptr;++ auto font = std::make_unique<Font>();+ font->bytes = std::move(file.bytes);+ const int offset = stbtt_GetFontOffsetForIndex(font->bytes.data(), file.faceIndex);+ if (offset >= 0 && stbtt_InitFont(&font->info, font->bytes.data(), offset)) {+ font->ok = true;+ }+ Font* raw = font.get();+ g_fonts.emplace(file.path, std::move(font));+ return raw->ok ? raw : nullptr;+}++/** Average an alpha grid down by an integer factor (the SDK's downsampleBytes). */+std::vector<uint8_t> downsample(const std::vector<uint8_t>& src, int width, int height, int factor) {+ if (factor <= 1) return src;+ const int w = width / factor;+ const int h = height / factor;+ std::vector<uint8_t> out((size_t)w * h, 0);+ const int area = factor * factor;+ for (int y = 0; y < h; y++) {+ for (int x = 0; x < w; x++) {+ int sum = 0;+ for (int sy = 0; sy < factor; sy++) {+ const uint8_t* row = src.data() + (size_t)(y * factor + sy) * width + (size_t)x * factor;+ for (int sx = 0; sx < factor; sx++) sum += row[sx];+ }+ out[(size_t)y * w + x] = (uint8_t)std::lround((double)sum / area);+ }+ }+ return out;+}++/** Expand single-channel coverage into the atlas' RGBA tile (RGB = 255, A = it). */+std::vector<uint8_t> toAtlasRgba(const std::vector<uint8_t>& coverage, int width, int height) {+ std::vector<uint8_t> out((size_t)width * height * 4);+ for (size_t i = 0, n = (size_t)width * height; i < n; i++) {+ out[i * 4 + 0] = 255;+ out[i * 4 + 1] = 255;+ out[i * 4 + 2] = 255;+ out[i * 4 + 3] = coverage[i];+ }+ return out;+}++} // namespace++GlyphBitmap rasterizeGlyph(Platform& platform, uint32_t codepoint, const std::string& family,+ int style, float pixelSize, bool sdf, float padding) {+ GlyphBitmap out;+ if (pixelSize <= 0.0f) return out;++ Font* font = loadFont(platform, family, codepoint, style);+ if (!font) return out;++ const int glyph = stbtt_FindGlyphIndex(&font->info, (int)codepoint);+ if (glyph == 0) return out; // the matched font does not have it after all++ // px per em, the same unit CSS font-size (and so the SDK's pixelSize) means.+ const int pad = (int)std::lround(padding);+ const int ss = sdf ? SDF_SUPERSAMPLE : 1;+ const float scale = stbtt_ScaleForMappingEmToPixels(&font->info, pixelSize) * (float)ss;++ int advanceRaw = 0, lsbRaw = 0;+ stbtt_GetGlyphHMetrics(&font->info, glyph, &advanceRaw, &lsbRaw);+ out.advance = advanceRaw * scale / (float)ss;+ out.ok = true;++ // Ink box in supersampled px, y DOWN from the baseline (y0 above it, negative).+ int x0 = 0, y0 = 0, x1 = 0, y1 = 0;+ stbtt_GetGlyphBitmapBox(&font->info, glyph, scale, scale, &x0, &y0, &x1, &y1);+ const int inkWss = x1 - x0;+ const int inkHss = y1 - y0;+ if (inkWss <= 0 || inkHss <= 0) return out; // whitespace: advance only, no cell++ // Stored (post-downsample) tile, padded; the supersampled grid tiles it exactly.+ const int inkW = (inkWss + ss - 1) / ss;+ const int inkH = (inkHss + ss - 1) / ss;+ const int w = inkW + pad * 2;+ const int h = inkH + pad * 2;+ const int wss = w * ss;+ const int hss = h * ss;++ std::vector<uint8_t> alpha((size_t)wss * hss, 0);+ stbtt_MakeGlyphBitmap(&font->info, alpha.data() + (size_t)pad * ss * wss + (size_t)pad * ss,+ inkWss, inkHss, wss, scale, scale, glyph);++ std::vector<uint8_t> coverage;+ if (sdf) {+ // The engine's own generator, so the field the shared SDF shader samples is+ // encoded exactly as the web's (128 = edge, spread = padding after folding).+ std::vector<uint8_t> field((size_t)wss * hss, 0);+ esengine::text::sdfFromAlpha(alpha.data(), field.data(), (esengine::u32)wss, (esengine::u32)hss,+ (esengine::f32)(pad * ss));+ coverage = downsample(field, wss, hss, ss);+ } else {+ coverage = std::move(alpha);+ }++ out.rgba = toAtlasRgba(coverage, w, h);+ out.width = w;+ out.height = h;+ // The tile's top-left in pen space, y UP: the SDK places it at+ // (penX + bearingX, bearingY). The ink starts `pad` in from both.+ out.bearingX = (float)x0 / (float)ss - (float)pad;+ out.bearingY = -(float)y0 / (float)ss + (float)pad;+ return out;+}++} // namespace eshostdiff --git a/native/host_js/glyph_raster.hpp b/native/host_js/glyph_raster.hppnew file mode 100644index 000000000..0442094e5--- /dev/null+++ b/native/host_js/glyph_raster.hpp@@ -0,0 +1,64 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file glyph_raster.hpp+ * @brief The device's glyph source: one codepoint → an upload-ready atlas tile.+ * @details On the web the SDK rasterizes glyphs on an offscreen 2D canvas and+ * converts the coverage to a signed distance field through the engine's+ * wasm heap. A native host has neither, so both halves happen here —+ * stb_truetype for the outline, the engine's OWN `text::sdfFromAlpha`+ * for the field, so the tiles the shared SDF shader samples are encoded+ * identically on both platforms.+ *+ * Only picking the font file is per-OS (Android's font matcher, Core+ * Text on iOS); it sits behind {@link eshost::Platform::loadFont}.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++#include <cstdint>+#include <string>+#include <vector>++namespace eshost {++struct Platform;++/** Style bits, matching the SDK's atlas cache key (ui/text/glyph-rasterizer.ts). */+enum : int { GLYPH_BOLD = 1, GLYPH_ITALIC = 2 };++/**+ * A rasterized glyph in the atlas' own terms: an RGBA8 tile (RGB = 255, alpha =+ * coverage or SDF) and metrics in the requested pixel size. `ok` is false when no+ * font could produce the codepoint; a blank-but-ok glyph (whitespace) carries an+ * advance and an empty tile, exactly as the canvas path returns.+ */+struct GlyphBitmap {+ std::vector<uint8_t> rgba;+ int width = 0;+ int height = 0;+ float advance = 0.0f;+ float bearingX = 0.0f;+ float bearingY = 0.0f;+ bool ok = false;+};++/**+ * Rasterize @p codepoint at @p pixelSize (px per em, as CSS font-size means it).+ *+ * @param style GLYPH_BOLD | GLYPH_ITALIC — passed to the platform's font match.+ * @param sdf true → a signed distance field (128 = edge, @p padding px per+ * half the byte range); false → plain antialiased coverage.+ * @param padding border around the ink, in px; the SDF spread.+ *+ * Fonts are cached by file path, so a glyph costs one match plus the raster.+ */+GlyphBitmap rasterizeGlyph(Platform& platform, uint32_t codepoint, const std::string& family,+ int style, float pixelSize, bool sdf, float padding);++} // namespace eshostdiff --git a/native/host_js/host_core.cpp b/native/host_js/host_core.cppindex b9381d322..51cb1eae0 100644--- a/native/host_js/host_core.cpp+++ b/native/host_js/host_core.cpp@@ -28,6 +28,7 @@#include "esengine_bundle.h" // the real SDK, bundled: installs globalThis.ESEngine#include "native_audio.hpp" // the miniaudio-backed engine behind es_audio*#include "ktx2_decode.hpp" // basis_universal transcode behind es_createTextureKTX2+#include "glyph_raster.hpp" // stb_truetype + the engine's SDF, behind es_rasterizeGlyph#include "esengine/core/EstellaContext.hpp"#include "esengine/core/World.hpp"@@ -389,6 +390,128 @@ JSValue js_getTextureDimensions(JSContext* ctx, JSValueConst, int, JSValueConst*return obj;}+// es_getTextureRenderId(handle) -> the id a draw command binds this texture by+// (Texture::getId(), backend-neutral). The SDK's glyph atlas passes it straight+// to the text batch, exactly as the web path does through getTextureGLId.+JSValue js_getTextureRenderId(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ int64_t id = 0;+ JS_ToInt64(ctx, &id, argv[0]);+ auto* tex = g_app->ctx->require<resource::ResourceManager>().getTexture(+ resource::TextureHandle((u32)id));+ return JS_NewInt64(ctx, tex ? (int64_t)tex->getId() : 0);+}++// es_updateTextureSubregion(handle, x, y, w, h, pixels) — upload one rect of an+// existing texture. The dynamic glyph atlas packs glyphs into a page this way+// instead of re-uploading the whole page per glyph.+JSValue js_updateTextureSubregion(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 6) return JS_UNDEFINED;+ int64_t id = 0; JS_ToInt64(ctx, &id, argv[0]);+ int32_t x = 0, y = 0, w = 0, h = 0;+ JS_ToInt32(ctx, &x, argv[1]); JS_ToInt32(ctx, &y, argv[2]);+ JS_ToInt32(ctx, &w, argv[3]); JS_ToInt32(ctx, &h, argv[4]);+ if (w <= 0 || h <= 0) return JS_UNDEFINED;+ std::vector<u8> pixels;+ readByteSource(ctx, argv[5], pixels);+ if (pixels.empty()) return JS_UNDEFINED;+ auto* tex = g_app->ctx->require<resource::ResourceManager>().getTexture(+ resource::TextureHandle((u32)id));+ if (!tex) return JS_UNDEFINED;+ // updateSubRegion bounds-checks the rect and the buffer size itself.+ tex->updateSubRegion((u32)x, (u32)y, (u32)w, (u32)h, pixels.data(), (u32)pixels.size(), /*flipY=*/false);+ return JS_UNDEFINED;+}++// es_rasterizeGlyph({ codepoint, fontFamily, style, pixelSize, sdf, padding })+// -> { pixels: ArrayBuffer, width, height, advance, bearingX, bearingY } | null.+// The device's answer to the browser's 2D canvas; see glyph_raster.hpp.+JSValue js_rasterizeGlyph(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 1 || !g_app || !g_app->platform) return JS_NULL;+ JSValue req = argv[0];++ const auto numberField = [&](const char* name, double fallback) {+ JSValue v = JS_GetPropertyStr(ctx, req, name);+ double out = fallback;+ if (!JS_IsUndefined(v)) JS_ToFloat64(ctx, &out, v);+ JS_FreeValue(ctx, v);+ return out;+ };+ const auto boolField = [&](const char* name) {+ JSValue v = JS_GetPropertyStr(ctx, req, name);+ const bool out = JS_ToBool(ctx, v) != 0;+ JS_FreeValue(ctx, v);+ return out;+ };++ std::string family;+ JSValue familyVal = JS_GetPropertyStr(ctx, req, "fontFamily");+ if (const char* s = JS_ToCString(ctx, familyVal)) {+ family = s;+ JS_FreeCString(ctx, s);+ }+ JS_FreeValue(ctx, familyVal);++ const auto glyph = eshost::rasterizeGlyph(+ *g_app->platform,+ (uint32_t)numberField("codepoint", 0),+ family,+ (int)numberField("style", 0),+ (float)numberField("pixelSize", 48),+ boolField("sdf"),+ (float)numberField("padding", 6));+ if (!glyph.ok) return JS_NULL;++ JSValue o = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, o, "pixels",+ glyph.rgba.empty() ? JS_NewArrayBufferCopy(ctx, nullptr, 0)+ : JS_NewArrayBufferCopy(ctx, glyph.rgba.data(), glyph.rgba.size()));+ JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, glyph.width));+ JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, glyph.height));+ JS_SetPropertyStr(ctx, o, "advance", JS_NewFloat64(ctx, glyph.advance));+ JS_SetPropertyStr(ctx, o, "bearingX", JS_NewFloat64(ctx, glyph.bearingX));+ JS_SetPropertyStr(ctx, o, "bearingY", JS_NewFloat64(ctx, glyph.bearingY));+ return o;+}++// Read a typed array's elements without copying more than the view. Returns the+// element pointer + count, or {nullptr, 0} when the value is not a typed array.+template <typename T>+std::pair<const T*, size_t> typedArrayView(JSContext* ctx, JSValueConst v, std::vector<u8>& storage) {+ storage.clear();+ readByteSource(ctx, v, storage);+ if (storage.size() < sizeof(T)) return {nullptr, 0};+ return {reinterpret_cast<const T*>(storage.data()), storage.size() / sizeof(T)};+}++// es_submitTextBatch(vertices, vertexCount, indices, textureId, transform,+// entity, layer, depth, sdf)+// The SDK lays glyph quads out against the atlas and hands them here — the native+// counterpart of the web's renderer_submitTextBatch, minus the wasm heap.+JSValue js_submitTextBatch(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 9 || !g_app || !g_app->ctx) return JS_UNDEFINED;+ std::vector<u8> vBytes, iBytes, tBytes;+ auto [vertices, vertexFloats] = typedArrayView<f32>(ctx, argv[0], vBytes);+ int32_t vertexCount = 0; JS_ToInt32(ctx, &vertexCount, argv[1]);+ auto [indices, indexCount] = typedArrayView<u16>(ctx, argv[2], iBytes);+ int64_t textureId = 0; JS_ToInt64(ctx, &textureId, argv[3]);+ auto [transform, transformFloats] = typedArrayView<f32>(ctx, argv[4], tBytes);+ int64_t entity = 0; JS_ToInt64(ctx, &entity, argv[5]);+ int32_t layer = 0; JS_ToInt32(ctx, &layer, argv[6]);+ double depth = 0; JS_ToFloat64(ctx, &depth, argv[7]);+ const bool sdf = JS_ToBool(ctx, argv[8]) != 0;++ // The vertex format is x,y,u,v,r,g,b,a — 8 floats each; validate before the+ // renderer trusts the spans, as the web binding's boundarySpan does.+ if (!vertices || !indices || !transform) return JS_UNDEFINED;+ if (vertexCount <= 0 || indexCount == 0 || transformFloats < 16) return JS_UNDEFINED;+ if (vertexFloats < (size_t)vertexCount * 8) return JS_UNDEFINED;++ g_app->ctx->require<RenderFrame>().submitTextBatch(+ vertices, vertexCount, indices, (i32)indexCount, (u32)textureId, transform,+ Entity::fromRaw((u32)entity), layer, (f32)depth, sdf);+ return JS_UNDEFINED;+}+std::vector<u8> readAsset(App& a, const char* path) {return a.platform ? a.platform->readAsset(path) : std::vector<u8>{};}@@ -930,6 +1053,14 @@ void initJS(App& a) {bindGlobal(a, global, "es_getTextureDimensions", js_getTextureDimensions, 1);bindGlobal(a, global, "es_readAsset", js_readAsset, 1);bindGlobal(a, global, "es_loadImagePixels", js_loadImagePixels, 1);+ // Text (es_rasterizeGlyph + es_submitTextBatch + the two texture calls the+ // glyph atlas needs): the SDK's TEXT_BINDINGS, all-or-nothing. The device has+ // no 2D canvas to rasterize on and no wasm heap to submit through; everything+ // between those two — atlas, layout, batching — is the SDK's own code.+ bindGlobal(a, global, "es_rasterizeGlyph", js_rasterizeGlyph, 1);+ bindGlobal(a, global, "es_submitTextBatch", js_submitTextBatch, 9);+ bindGlobal(a, global, "es_updateTextureSubregion", js_updateTextureSubregion, 6);+ bindGlobal(a, global, "es_getTextureRenderId", js_getTextureRenderId, 1);// 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.@@ -1107,6 +1238,10 @@ void frame() {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();a.gfx->present();diff --git a/native/host_js/host_core.hpp b/native/host_js/host_core.hppindex 143978e62..a23676c06 100644--- a/native/host_js/host_core.hpp+++ b/native/host_js/host_core.hpp@@ -57,6 +57,18 @@ struct FetchResult {std::string error;};+/**+ * A font file the glyph rasterizer can parse. `path` identifies it (the cache+ * key — empty means the platform found nothing), `faceIndex` selects a face+ * inside a collection (.ttc), and `bytes` is the file, read only the first time+ * a path is seen.+ */+struct FontFile {+ std::string path;+ std::vector<esengine::u8> bytes;+ int faceIndex = 0;+};+/*** @brief The platform seam: what the host needs that Android and iOS answer* differently. The glue implements it; host_core owns everything else.@@ -80,6 +92,15 @@ struct Platform {virtual void log(bool error, const char* message) = 0;+ /** A font for @p family that covers @p codepoint, with @p style's bold/italic+ * bits (see GLYPH_BOLD / GLYPH_ITALIC) applied to the match. Empty `path`+ * when the platform has nothing — the glyph then simply does not draw.+ *+ * This is the ONLY per-OS part of text: which file to open. Android asks its+ * font matcher (which handles CJK fallback), iOS asks Core Text; the+ * rasterization and the SDF conversion are shared (see glyph_raster.hpp). */+ virtual FontFile loadFont(const std::string& family, esengine::u32 codepoint, int style) = 0;+/** Perform an HTTP request off the main thread (NSURLSession / a JNI* HttpURLConnection), then hand the reply back through {@link deliverFetch}* with the same `req.id`. The OS owns the TLS stack, so this is where nativediff --git a/native/host_js/main_android.cpp b/native/host_js/main_android.cppindex 27a742e3a..9ee40406a 100644--- a/native/host_js/main_android.cpp+++ b/native/host_js/main_android.cpp@@ -17,12 +17,15 @@#include <android/log.h>#include <android/input.h>#include <android/asset_manager.h>+#include <android/font.h>+#include <android/font_matcher.h>#include <android/native_window.h>#include <jni.h>#include <thread>#include "host_core.hpp"+#include "glyph_raster.hpp" // GLYPH_BOLD / GLYPH_ITALIC, for the font match#define LOG_TAG "EstellaSDK"@@ -171,6 +174,51 @@ struct AndroidPlatform final : eshost::Platform {__android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, LOG_TAG, "%s", message);}+ // Android's own font matcher (NDK, API 29+) picks the file: it knows the+ // installed families, applies weight/italic, and — the part worth having —+ // falls back per codepoint, so CJK text resolves to Noto without the host+ // hard-coding a single font path.+ eshost::FontFile loadFont(const std::string& family, u32 codepoint, int style) override {+ eshost::FontFile out;+ AFontMatcher* matcher = AFontMatcher_create();+ if (!matcher) return out;+ AFontMatcher_setStyle(matcher, (style & eshost::GLYPH_BOLD) ? AFONT_WEIGHT_BOLD : AFONT_WEIGHT_NORMAL,+ (style & eshost::GLYPH_ITALIC) != 0);+ // The matcher takes the text to cover as UTF-16; one codepoint is one unit+ // below U+10000 and a surrogate pair above it.+ uint16_t text[2];+ uint32_t length = 0;+ if (codepoint >= 0x10000) {+ const uint32_t v = codepoint - 0x10000;+ text[length++] = (uint16_t)(0xD800 + (v >> 10));+ text[length++] = (uint16_t)(0xDC00 + (v & 0x3FF));+ } else {+ text[length++] = (uint16_t)(codepoint ? codepoint : 'A');+ }+ AFont* font = AFontMatcher_match(matcher, family.empty() ? "sans-serif" : family.c_str(),+ text, length, nullptr);+ AFontMatcher_destroy(matcher);+ if (!font) return out;++ if (const char* path = AFont_getFontFilePath(font)) {+ out.path = path;+ out.faceIndex = (int)AFont_getCollectionIndex(font);+ if (FILE* f = fopen(path, "rb")) {+ fseek(f, 0, SEEK_END);+ const long size = ftell(f);+ fseek(f, 0, SEEK_SET);+ if (size > 0) {+ out.bytes.resize((size_t)size);+ if (fread(out.bytes.data(), 1, out.bytes.size(), f) != out.bytes.size()) out.bytes.clear();+ }+ fclose(f);+ }+ }+ AFont_close(font);+ if (out.bytes.empty()) out.path.clear();+ return out;+ }+// A detached JNI thread runs the request; deliverFetch is thread-safe and the// JS callback runs back on the main thread in drainFetches.void startFetch(const eshost::FetchRequest& req) override {diff --git a/native/host_js/main_ios.mm b/native/host_js/main_ios.mmindex 2991ce6ff..a9a273d81 100644--- a/native/host_js/main_ios.mm+++ b/native/host_js/main_ios.mm@@ -22,8 +22,10 @@*/#import <UIKit/UIKit.h>#import <QuartzCore/CAMetalLayer.h>+#import <CoreText/CoreText.h>#include "host_core.hpp"+#include "glyph_raster.hpp" // GLYPH_BOLD / GLYPH_ITALIC, for the font matchusing esengine::u32;using esengine::u8;@@ -75,6 +77,64 @@ struct IOSPlatform final : eshost::Platform {NSLog(@"[Estella]%s %s", error ? " ERROR:" : "", message);}+ // Core Text names the file: it resolves a family (falling back to the system+ // font when the name is unknown), and CTFontCreateForString picks a face that+ // actually covers the codepoint — the CJK fallback, without a hard-coded path.+ // The URL is a real file under /System/Library/Fonts, readable from the app.+ eshost::FontFile loadFont(const std::string& family, u32 codepoint, int style) override {+ eshost::FontFile out;+ CTFontSymbolicTraits traits = 0;+ if (style & eshost::GLYPH_BOLD) traits |= kCTFontTraitBold;+ if (style & eshost::GLYPH_ITALIC) traits |= kCTFontTraitItalic;++ NSString* name = family.empty() ? @"Helvetica" : [NSString stringWithUTF8String:family.c_str()];+ CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)name, 16.0, NULL);+ if (!font) return out;+ if (traits) {+ if (CTFontRef styled = CTFontCreateCopyWithSymbolicTraits(font, 16.0, NULL, traits, traits)) {+ CFRelease(font);+ font = styled;+ }+ }++ // Does this face have the glyph? If not, let Core Text find one that does.+ if (codepoint) {+ UniChar chars[2];+ CFIndex length = 0;+ if (codepoint >= 0x10000) {+ const uint32_t v = codepoint - 0x10000;+ chars[length++] = (UniChar)(0xD800 + (v >> 10));+ chars[length++] = (UniChar)(0xDC00 + (v & 0x3FF));+ } else {+ chars[length++] = (UniChar)codepoint;+ }+ CGGlyph glyphs[2] = {0, 0};+ if (!CTFontGetGlyphsForCharacters(font, chars, glyphs, length)) {+ CFStringRef text = CFStringCreateWithCharacters(NULL, chars, length);+ CTFontRef fallback = CTFontCreateForString(font, text, CFRangeMake(0, length));+ CFRelease(text);+ if (fallback) {+ CFRelease(font);+ font = fallback;+ }+ }+ }++ CFURLRef url = (CFURLRef)CTFontCopyAttribute(font, kCTFontURLAttribute);+ CFRelease(font);+ if (!url) return out;+ NSString* path = [(__bridge NSURL*)url path];+ CFRelease(url);+ if (!path) return out;++ NSData* data = [NSData dataWithContentsOfFile:path];+ if (!data) return out;+ out.path = std::string([path UTF8String]);+ out.bytes.resize(data.length);+ memcpy(out.bytes.data(), data.bytes, data.length);+ return out;+ }+// NSURLSession runs the request (TLS via the OS) on a background queue and// calls its completion there; deliverFetch is thread-safe and the JS callback// runs back on the main thread in drainFetches.diff --git a/native/ios/project.yml b/native/ios/project.ymlindex 9bdfecc15..829da7e45 100644--- a/native/ios/project.yml+++ b/native/ios/project.yml@@ -64,6 +64,8 @@ targets:- sdk: QuartzCore.framework- sdk: IOSurface.framework- sdk: CoreGraphics.framework+ # Core Text names the font file the glyph rasterizer parses (main_ios.mm).+ - sdk: CoreText.framework- sdk: Foundation.framework# miniaudio's CoreAudio backend (native_audio.cpp), linked at build time# because it forces MA_NO_RUNTIME_LINKING on Apple.diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 35d7f2be1..43c5b88ca 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -4496,6 +4496,7 @@ onAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefined+rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>@@ -5122,6 +5123,7 @@ beginScreenCapture: () => voidendScreenCapture: () => voidrender: (params: RenderParams) => voidrenderCamera: (params: CameraRenderParams) => void+runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => voidsetActiveScenes: (scenes: Set<string> | null) => voidsetPostProcess: (pp: PostProcessAPI | null) => voidsubmitScene: (registry: { _cpp: CppRegistry; }, viewProjection: Float32Array, viewport: Viewport, _elapsed: number) => voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 019dabd1b..d3e01193b 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -3955,6 +3955,7 @@ now: (() => number) | undefinedonHide: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedonShow: ((callback: () => void) => () => void) | undefined+rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>registerInput: (listener: NativeInputListener) => () => void@@ -4013,6 +4014,7 @@ es_devicePixelRatio: (() => number) | undefinedes_fetch: ((request: { url: string; method?: string; headers?: Record<string, string>; body?: string | ArrayBuffer; responseType?: string; }, callback: (result: { ok: boolean; status: number; statusText: string; headers: Record<string, string>; arrayBuffer?: ArrayBuffer; text?: string; error?: string; }) => void) => void) | undefinedes_getStorageItem: ((key: string) => string | null) | undefinedes_loadImagePixels: (path: string) => { width: number; height: number; pixels: ArrayBuffer; } | null+es_rasterizeGlyph: ((request: PlatformGlyphRequest) => { pixels: ArrayBuffer; width: number; height: number; advance: number; bearingX: number; bearingY: number; } | null) | undefinedes_readAsset: (path: string) => ArrayBuffer | nulles_readCacheFile: ((key: string) => ArrayBuffer | null) | undefinedes_removeStorageItem: ((key: string) => void) | undefined@@ -4057,6 +4059,7 @@ now: () => numberonAppHide: (callback: () => void) => () => voidonAppShow: (callback: () => void) => () => voidonMemoryWarning: (callback: () => void) => () => void+rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: (key: string) => Promise<ArrayBuffer | null>readFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>@@ -4640,6 +4643,7 @@ onAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefined+rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>@@ -5276,6 +5280,7 @@ beginScreenCapture: () => voidendScreenCapture: () => voidrender: (params: RenderParams) => voidrenderCamera: (params: CameraRenderParams) => void+runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => voidsetActiveScenes: (scenes: Set<string> | null) => voidsetPostProcess: (pp: PostProcessAPI | null) => voidsubmitScene: (registry: { _cpp: CppRegistry; }, viewProjection: Float32Array, viewport: Viewport, _elapsed: number) => voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 43f45f43a..69b9a6669 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4491,6 +4491,7 @@ onAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefined+rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>@@ -5117,6 +5118,7 @@ beginScreenCapture: () => voidendScreenCapture: () => voidrender: (params: RenderParams) => voidrenderCamera: (params: CameraRenderParams) => void+runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => voidsetActiveScenes: (scenes: Set<string> | null) => voidsetPostProcess: (pp: PostProcessAPI | null) => voidsubmitScene: (registry: { _cpp: CppRegistry; }, viewProjection: Float32Array, viewport: Viewport, _elapsed: number) => voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex cf5b8cfac..24d46e614 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4498,6 +4498,7 @@ onAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefined+rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>@@ -5124,6 +5125,7 @@ beginScreenCapture: () => voidendScreenCapture: () => voidrender: (params: RenderParams) => voidrenderCamera: (params: CameraRenderParams) => void+runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => voidsetActiveScenes: (scenes: Set<string> | null) => voidsetPostProcess: (pp: PostProcessAPI | null) => voidsubmitScene: (registry: { _cpp: CppRegistry; }, viewProjection: Float32Array, viewport: Viewport, _elapsed: number) => voiddiff --git a/sdk/src/ecs/nativeBindings.ts b/sdk/src/ecs/nativeBindings.tsindex ed57c91c0..d0e2d7b85 100644--- a/sdk/src/ecs/nativeBindings.ts+++ b/sdk/src/ecs/nativeBindings.ts@@ -34,6 +34,44 @@ export const RESOURCE_BINDINGS = {getTextureDimensions: 'es_getTextureDimensions',} as const;+/**+ * Text rendering, which on native crosses the seam twice: the host rasterizes a+ * glyph (it owns the font stack — there is no 2D canvas) and the host submits the+ * laid-out quads (there is no wasm heap to marshal them through). Everything+ * between those two calls — atlas, layout, batching — is the same SDK code the+ * web runs.+ *+ * OPTIONAL, like {@link AUDIO_BINDINGS}: a host that has not bound its font stack+ * simply draws no text, rather than failing to boot. {@link hasTextBindings} is+ * the gate.+ */+export const TEXT_BINDINGS = {+ rasterizeGlyph: 'es_rasterizeGlyph',+ submitTextBatch: 'es_submitTextBatch',+ updateTextureSubregion: 'es_updateTextureSubregion',+ getTextureRenderId: 'es_getTextureRenderId',+} as const;++/** Whether a host bound the whole text surface — all-or-nothing, so a partially+ * implemented host draws nothing instead of half-drawing. */+export function hasTextBindings(+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,+): boolean {+ return Object.values(TEXT_BINDINGS).every((name) => typeof scope[name] === 'function');+}++/**+ * 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.+ */+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',+} as const;+/** Platform primitives the SDK's bridge and file reading are built on. */export const PLATFORM_BINDINGS = {readAsset: 'es_readAsset',diff --git a/sdk/src/ecs/nativeResourceManager.ts b/sdk/src/ecs/nativeResourceManager.tsindex 6ad0863b5..904b5334d 100644--- a/sdk/src/ecs/nativeResourceManager.ts+++ b/sdk/src/ecs/nativeResourceManager.ts@@ -15,7 +15,7 @@// method when present, so web (embind, no such method) stays byte-identical.import type { CppResourceManager } from '../wasm';-import { RESOURCE_BINDINGS } from './nativeBindings';+import { RESOURCE_BINDINGS, TEXT_BINDINGS } from './nativeBindings';/** Invoke a host-provided global by name; throws if the host did not bind it* (these are part of the native ResourceManager contract). */@@ -45,8 +45,8 @@ function hostCallOpt(scope: Record<string, unknown>, name: string, args: unknown* and optionally es_updateTextureSubregion / es_setTextureBudget.** Only the methods the native asset path actually calls are implemented; the- * wasm/GL-specific ones (heap-pointer createTexture, registerExternalTexture,- * GL id lookup, bitmap-font glyph upload) throw if reached, and the residency /+ * wasm-specific ones (heap-pointer createTexture, registerExternalTexture,+ * bitmap-font glyph upload) throw if reached, and the residency /* stats hooks the SDK optional-chains are simply omitted — so a texture that lost* its last reference re-decodes instead of reviving (correct, just not yet cached).*/@@ -70,9 +70,16 @@ export function createNativeResourceManager(},updateTextureSubregionFromBytes: (handle, x, y, width, height, pixels): void => {- hostCallOpt(scope, 'es_updateTextureSubregion', [handle, x, y, width, height, pixels]);+ hostCallOpt(scope, TEXT_BINDINGS.updateTextureSubregion, [handle, x, y, width, height, pixels]);},+ // The id a draw command binds a texture by. Named for GL because that is+ // where it started, but the engine returns `Texture::getId()` on every+ // backend — the glyph atlas passes it straight to the text batch. The+ // host reads it off the same ResourceManager it created the texture in.+ getTextureGLId: (handle): number =>+ hostCall(scope, TEXT_BINDINGS.getTextureRenderId, [handle]) as number,+releaseTexture: (handle): void => {hostCallOpt(scope, RESOURCE_BINDINGS.releaseTexture, [handle]);},@@ -98,7 +105,6 @@ export function createNativeResourceManager(rm.createTextureEx = unsupported('createTextureEx(ptr)');rm.registerExternalTexture = unsupported('registerExternalTexture');rm.registerExternalTextureSized = unsupported('registerExternalTextureSized');- rm.getTextureGLId = unsupported('getTextureGLId');return rm as CppResourceManager;}diff --git a/sdk/src/ecs/nativeRuntime.ts b/sdk/src/ecs/nativeRuntime.tsindex 4f6ec83c7..71acad5f4 100644--- a/sdk/src/ecs/nativeRuntime.ts+++ b/sdk/src/ecs/nativeRuntime.ts@@ -21,6 +21,10 @@ 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 { RenderPipeline } from '../renderPipeline';+import { textPlugin } from '../ui/text/plugin';+import { setNativeTextSubmit } from '../ui/text/submit';import { initResourceManager } from '../resourceManager';import { Assets as AssetsClass } from '../asset/Assets';import { Assets as AssetsResource } from '../asset/AssetPlugin';@@ -78,6 +82,7 @@ export function createNativeApp(// so installNativeAssets below builds the equivalent over the native RM.// Assets first: prefabs and scene loading declare it as a required resource.installNativeAssets(app, scope);+ installNativeText(app, scope);app.addPlugin(inputPlugin);app.addPlugin(prefabsPlugin);app.addPlugin(sceneManagerPlugin);@@ -98,6 +103,43 @@ 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 text — the same `TextPlugin` the web build runs, over the native core.+ *+ * Two things it cannot take from the web: a glyph source (the device has no 2D+ * canvas — the host's font stack answers, through `PlatformAdapter.rasterizeGlyph`)+ * and a way to hand the laid-out quads to the renderer (no wasm heap — the host+ * takes the typed arrays and calls `RenderFrame::submitTextBatch` itself).+ * Everything between, atlas through batching, is the SDK's one implementation.+ *+ * 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.+ *+ * 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.+ */+function installNativeText(app: App, scope: Record<string, unknown>): void {+ if (!hasTextBindings(scope)) return;++ const submit = scope[TEXT_BINDINGS.submitTextBatch] as (+ vertices: Float32Array, vertexCount: number, indices: Uint16Array, textureId: number,+ transform: Float32Array, entity: number, layer: number, depth: number, sdf: boolean,+ ) => 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 {// The host's es_* texture bindings back the SDK's resource surface, so// requireResourceManager() resolves for the whole asset path.diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex e231fc8f1..e692b05e5 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -130,6 +130,22 @@ export function platformCreateImage(): import('./types').PlatformImage {return getPlatform().createImage();}+/** Whether this platform rasterizes glyphs itself (no 2D canvas to draw them on).+ * The glyph atlas picks its rasterizer from this — false everywhere a canvas+ * exists, so web/WeChat text is untouched. Safe before a platform is set. */+export function platformHasGlyphRasterizer(): boolean {+ return isPlatformInitialized() && typeof getPlatform().rasterizeGlyph === 'function';+}++/** Rasterize one glyph through the platform's own text stack; null when the+ * platform has no rasterizer, or the font/glyph was unavailable. */+export function platformRasterizeGlyph(+ request: import('./types').PlatformGlyphRequest,+): import('./types').PlatformGlyph | null {+ if (!isPlatformInitialized()) return null;+ return getPlatform().rasterizeGlyph?.(request) ?? null;+}+export function platformNow(): number {return getPlatform().now();}diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex f7f92b171..eb4e8c1f2 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -16,6 +16,8 @@ export type {PlatformCanvas,PlatformCanvas2DContext,PlatformImage,+ PlatformGlyph,+ PlatformGlyphRequest,} from './types';// Re-export base functions@@ -36,6 +38,8 @@ export {platformInstantiateWasm,platformCreateCanvas,platformCreateImage,+ platformHasGlyphRasterizer,+ platformRasterizeGlyph,platformNow,platformUnbindInputEvents,platformCreateAudioBackend,diff --git a/sdk/src/platform/native/adapter.ts b/sdk/src/platform/native/adapter.tsindex bfa9ff380..33884d9a6 100644--- a/sdk/src/platform/native/adapter.ts+++ b/sdk/src/platform/native/adapter.ts@@ -23,6 +23,8 @@ import type {ImageLoadResult,PlatformCanvas,PlatformImage,+ PlatformGlyph,+ PlatformGlyphRequest,} from '../types';import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';import { setPlatform } from '../base';@@ -42,11 +44,21 @@ export class NativePlatformAdapter implements PlatformAdapter {const audio = bridge_.audio;this.createAudioBackend = () => new NativeAudioBackend(audio);}+ // Likewise for text: present only when the host bound its font stack, so+ // `platformHasGlyphRasterizer()` answers truthfully and the glyph atlas+ // knows whether this device can produce glyphs at all.+ if (bridge_.rasterizeGlyph) {+ const rasterize = bridge_.rasterizeGlyph.bind(bridge_);+ this.rasterizeGlyph = (request) => rasterize(request);+ }}/** Assigned in the constructor only when the host bound an audio engine. */createAudioBackend?: () => PlatformAudioBackend;+ /** Assigned in the constructor only when the host bound a glyph rasterizer. */+ rasterizeGlyph?: (request: PlatformGlyphRequest) => PlatformGlyph | null;+async fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {const r = await this.bridge_.fetch(url, options);const text = () =>diff --git a/sdk/src/platform/native/bridge.ts b/sdk/src/platform/native/bridge.tsindex 7cca91226..e45243663 100644--- a/sdk/src/platform/native/bridge.ts+++ b/sdk/src/platform/native/bridge.ts@@ -18,7 +18,7 @@* shell (boot spike → full host) lands. Public via the `esengine/native` entry.*/-import type { ImageLoadResult, PlatformRequestOptions } from '../types';+import type { ImageLoadResult, PlatformGlyph, PlatformGlyphRequest, PlatformRequestOptions } from '../types';/*** A single fetch result from the native http stack. The adapter wraps it into a@@ -104,6 +104,13 @@ export interface NativeBridge {* route the play realm and WeChat also use). */loadImagePixels(path: string): Promise<ImageLoadResult>;+ /** Rasterize one glyph — the device's answer to the 2D canvas the browser+ * path draws text on. Synchronous, because the dynamic glyph atlas fills+ * cells during the frame that needs them. Optional: a host that has not+ * bound its font stack omits it and `Text` draws nothing (the atlas treats+ * a null the same as a canvas miss). See {@link PlatformAdapter.rasterizeGlyph}. */+ rasterizeGlyph?(request: PlatformGlyphRequest): PlatformGlyph | null;+/** Persistent key-value store (NSUserDefaults / SharedPreferences). Sync,* like localStorage / wx.*StorageSync. `storageKeys()` lets the adapter* implement `clearStorage(prefix)` itself. */diff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.tsindex 86f7ef242..6eeb86dde 100644--- a/sdk/src/platform/native/hostBridge.ts+++ b/sdk/src/platform/native/hostBridge.ts@@ -14,7 +14,7 @@import { log } from '../../logger';import type { NativeAudioBridge, NativeBridge, NativeFetchResult, NativeInputListener } from './bridge';-import type { PlatformRequestOptions } from '../types';+import type { PlatformGlyph, PlatformGlyphRequest, PlatformRequestOptions } from '../types';import { assertHostEnvironment } from './hostEnvironment';import { hasAudioBindings } from '../../ecs/nativeBindings';@@ -29,6 +29,13 @@ export interface NativeHostBindings {es_readAsset(path: string): ArrayBuffer | null;/** Decode a packaged image to top-first RGBA, or null on failure. */es_loadImagePixels(path: string): { width: number; height: number; pixels: ArrayBuffer } | null;+ /** Rasterize one glyph through the OS font stack — what a 2D canvas does on+ * the web. Optional, all-or-nothing with the rest of {@link TEXT_BINDINGS}:+ * a host that has not bound its font stack draws no text. */+ es_rasterizeGlyph?(request: PlatformGlyphRequest): {+ pixels: ArrayBuffer; width: number; height: number;+ advance: number; bearingX: number; bearingY: number;+ } | null;/** A writable byte store (the host's cache dir). Optional: without it there* is no offline hot-update cache and no persistence for storage. */es_readCacheFile?(key: string): ArrayBuffer | null;@@ -132,6 +139,7 @@ export function createHostBridge(}): Promise.reject(new Error(`image decode failed: ${path}`));},+ ...(bindings.es_rasterizeGlyph ? { rasterizeGlyph: (request) => hostGlyph(bindings, request) } : {}),...storage,...(bindings.es_readCacheFile && bindings.es_writeCacheFile? {@@ -152,6 +160,25 @@ export function createHostBridge(};}+/**+ * One glyph from the host's font stack, as the atlas wants it. The host answers+ * with an ArrayBuffer (a native JS engine hands raw buffers across, as it does+ * for decoded images); the view is the SDK's to put on, so the atlas' upload+ * path sees the same Uint8Array it gets from a canvas.+ */+function hostGlyph(bindings: NativeHostBindings, request: PlatformGlyphRequest): PlatformGlyph | null {+ const glyph = bindings.es_rasterizeGlyph!(request);+ if (!glyph) return null;+ return {+ pixels: new Uint8Array(glyph.pixels),+ width: glyph.width,+ height: glyph.height,+ advance: glyph.advance,+ bearingX: glyph.bearingX,+ bearingY: glyph.bearingY,+ };+}+/*** Perform an HTTP request through the host's native stack (es_fetch), wrapping* its callback in the Promise the adapter expects. A host without es_fetch isdiff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex c3bf68529..9c46de0d5 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -207,6 +207,39 @@ export interface PlatformCanvas {): PlatformCanvas2DContext | null;}+/**+ * A glyph to rasterize, for a platform whose text comes from the OS rather than a+ * 2D canvas. `style` carries the atlas' bold/italic bits (1 | 2), and `sdf` ++ * `padding` say which encoding the atlas wants — the same two the Canvas2D+ * rasterizer implements, so both backends fill the same atlas.+ */+export interface PlatformGlyphRequest {+ codepoint: number;+ fontFamily: string;+ style: number;+ /** Em size to rasterize at, in px. */+ pixelSize: number;+ /** Signed distance field (128 = edge, `padding` px per half byte-range) vs+ * plain antialiased coverage. */+ sdf: boolean;+ /** Padding around the ink — the SDF spread — in px. */+ padding: number;+}++/**+ * A rasterized glyph: an upload-ready RGBA8 tile (RGB = 255, A = coverage or SDF)+ * plus its metrics in `pixelSize` units. Structurally the atlas' `RasterGlyph`;+ * declared here so the platform layer stays independent of ui/text.+ */+export interface PlatformGlyph {+ pixels: Uint8Array;+ width: number;+ height: number;+ advance: number;+ bearingX: number;+ bearingY: number;+}+/*** A load/error callback SINK: callers only ever ASSIGN one (`img.onload = …`); the* host image invokes it. The parameter is the bottom type `never` so, by@@ -255,6 +288,19 @@ export interface PlatformAdapter {createCanvas(width: number, height: number): PlatformCanvas;+ /**+ * Rasterize one glyph through the OS text stack, for a platform with no 2D+ * canvas to draw it on. Synchronous: the dynamic glyph atlas fills cells+ * during the frame it needs them.+ *+ * Optional — a platform that has {@link createCanvas} omits it and the atlas+ * uses the Canvas2D rasterizer (web, WeChat). Native implements it (the+ * embedded-Dawn host has no DOM), and `null` means the font or the glyph was+ * unavailable, which the atlas treats as "no cell" exactly as it does a+ * canvas miss.+ */+ rasterizeGlyph?(request: PlatformGlyphRequest): PlatformGlyph | null;+now(): number;createImage(): PlatformImage;diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.tsindex 7aec8a997..d0d953f0f 100644--- a/sdk/src/renderPipeline.ts+++ b/sdk/src/renderPipeline.ts@@ -70,6 +70,17 @@ export class RenderPipeline {this.preFlushCallbacks_.push(cb);}+ /**+ * Run what plugins registered to draw just before the frame flushes (glyph+ * quads, today). {@link submitScene} calls this in the middle of its own+ * sequence; a host that owns its render loop in C++ — the native one — calls+ * it directly at the same point, between collecting the scene and flushing,+ * so text lands in the same frame either way.+ */+ runPreFlushCallbacks(registry: { _cpp: CppRegistry }): void {+ for (const cb of this.preFlushCallbacks_) cb(registry);+ }+beginFrame(elapsedSec = 0): void {Renderer.beginFrame(elapsedSec);}@@ -105,7 +116,7 @@ export class RenderPipeline {Renderer.updateTransforms(registry);Renderer.submitAll(registry, 0, viewport.x, viewport.y, viewport.w, viewport.h);- for (const cb of this.preFlushCallbacks_) cb(registry);+ this.runPreFlushCallbacks(registry);Renderer.flush();this.executeDrawCallbacks(viewProjection, _elapsed);diff --git a/sdk/src/ui/text/atlas-page-store.ts b/sdk/src/ui/text/atlas-page-store.tsindex bbb836a20..c7b611ec1 100644--- a/sdk/src/ui/text/atlas-page-store.ts+++ b/sdk/src/ui/text/atlas-page-store.ts@@ -17,7 +17,9 @@ export class EngineAtlasPageStore implements AtlasPageStore {// handle, so keep the mapping.private readonly handleByGlId = new Map<number, number>();- constructor(private readonly module: ESEngineModule) {}+ /** `module` is the wasm-heap marshalling vehicle; null on the native+ * (embedded-Dawn) core, whose ResourceManager takes the bytes directly. */+ constructor(private readonly module: ESEngineModule | null) {}createPage(size: number): number {// Blank (transparent) RGBA8 page; linear filtering keeps SDF text smoothdiff --git a/sdk/src/ui/text/glyph-rasterizer.ts b/sdk/src/ui/text/glyph-rasterizer.tsindex aba6cff87..37d8521c4 100644--- a/sdk/src/ui/text/glyph-rasterizer.ts+++ b/sdk/src/ui/text/glyph-rasterizer.ts@@ -85,13 +85,17 @@ const SDF_SUPERSAMPLE = 4;export class CanvasGlyphRasterizer implements GlyphRasterizer {readonly renderSize: number;- private readonly module: ESEngineModule;+ /** The SDF conversion runs in the engine's wasm heap; without a module there+ * is none, and an SDF atlas simply has no glyphs (as when the build lacks+ * the binding). A platform with no wasm core rasterizes elsewhere entirely —+ * see {@link NativeGlyphRasterizer}. */+ private readonly module: ESEngineModule | null;private readonly pad: number;private readonly sdf: boolean;private readonly canvas: Canvas2D;private readonly ctx: Ctx2D | null;- constructor(module: ESEngineModule, opts: CanvasGlyphRasterizerOptions = {}) {+ constructor(module: ESEngineModule | null, opts: CanvasGlyphRasterizerOptions = {}) {this.module = module;this.renderSize = opts.renderSize ?? 48;this.pad = opts.padding ?? 6;@@ -150,7 +154,7 @@ export class CanvasGlyphRasterizer implements GlyphRasterizer {// encoding matches spread = pad exactly). Bitmap: native-AA coverage as-is.let coverage = alpha;if (this.sdf) {- const sdf = sdfFromAlpha(this.module, alpha, wSS, hSS, pad * ss);+ const sdf = this.module ? sdfFromAlpha(this.module, alpha, wSS, hSS, pad * ss) : null;if (!sdf) return null;coverage = downsampleBytes(sdf, wSS, hSS, ss);}diff --git a/sdk/src/ui/text/native-glyph-rasterizer.ts b/sdk/src/ui/text/native-glyph-rasterizer.tsnew file mode 100644index 000000000..e3da762ff--- /dev/null+++ b/sdk/src/ui/text/native-glyph-rasterizer.ts@@ -0,0 +1,57 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ui/text/native-glyph-rasterizer.ts+ * @brief The platform's own glyph source, for a device with no 2D canvas to+ * draw text on — the embedded-Dawn native host.+ *+ * The Canvas2D rasterizer measures and draws a glyph, then converts the alpha+ * coverage to an SDF through the engine's wasm heap. A native host has neither a+ * canvas nor a wasm heap, so the whole of that runs on its side of the seam+ * (its font stack + the engine's own `sdfFromAlpha`, compiled native) and this+ * class only carries the request across: same {@link GlyphRasterizer} contract,+ * same tile format, so the atlas, the layout and the batching above it are the+ * ONE implementation both platforms run.+ *+ * Mirrors how `createNativeResourceManager` backs the shared Assets channel.+ */+import { platformRasterizeGlyph } from '../../platform';+import type { GlyphRasterizer, RasterGlyph } from './glyph-atlas';++export interface NativeGlyphRasterizerOptions {+ /** Size glyphs are rasterized at (an SDF is resolution-independent). Default 48. */+ renderSize?: number;+ /** SDF spread / padding around the glyph ink, in px. Default 6. */+ padding?: number;+ /** Produce an SDF (scalable) vs a plain-alpha bitmap (native AA). Default true. */+ sdf?: boolean;+}++export class NativeGlyphRasterizer implements GlyphRasterizer {+ readonly renderSize: number;+ private readonly pad: number;+ private readonly sdf: boolean;++ constructor(opts: NativeGlyphRasterizerOptions = {}) {+ this.renderSize = opts.renderSize ?? 48;+ this.pad = opts.padding ?? 6;+ this.sdf = opts.sdf ?? true;+ }++ rasterize(codepoint: number, fontFamily: string, style: number, pixelSize = this.renderSize): RasterGlyph | null {+ const glyph = platformRasterizeGlyph({+ codepoint, fontFamily, style, pixelSize, sdf: this.sdf, padding: this.pad,+ });+ if (!glyph) return null;+ // A host may answer a whitespace glyph with advance only (no cell) — the+ // same shape the canvas path returns, so the atlas needs no special case.+ return {+ pixels: glyph.pixels,+ width: glyph.width,+ height: glyph.height,+ advance: glyph.advance,+ bearingX: glyph.bearingX,+ bearingY: glyph.bearingY,+ };+ }+}diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.tsindex 29b05b52e..b675fc88a 100644--- a/sdk/src/ui/text/plugin.ts+++ b/sdk/src/ui/text/plugin.ts@@ -85,7 +85,9 @@ export class TextPlugin implements Plugin {const pipeline = app.pipeline;if (!pipeline) return; // logic-only host → nothing to draw- const module = app.wasmModule as ESEngineModule;+ // Null on the native core (no wasm): the optional engine queries below+ // simply do not answer there, and the text still lays out and submits.+ const module = app.wasmModule as ESEngineModule | null;const registry = world.getCppRegistry() as CppRegistry;pipeline.addPreFlushCallback(() => {@@ -106,7 +108,7 @@ export class TextPlugin implements Plugin {// enabled === false: pre-upgrade data lacks the field → visible.if (!t.content || t.enabled === false) continue;// display:none anywhere up the UI tree hides this text too.- if (module.getUINodeHiddenInTree?.(registry, entity)) continue;+ if (module?.getUINodeHiddenInTree?.(registry, entity)) continue;seen.add(entity as number);const tr = world.get(entity, Transform) as TransformData;@@ -145,7 +147,7 @@ export class TextPlugin implements Plugin {boxHeight = box.boxHeight;if (t.wordWrap) maxWidth = box.maxWidth; // wrap only when enabled- const order = module.ui_getRenderOrder+ const order = module?.ui_getRenderOrder? module.ui_getRenderOrder(registry, entity as number): -1;layer = order >= 0 ? UI_BASE_LAYER + order : UI_BASE_LAYER;@@ -200,7 +202,7 @@ export class TextPlugin implements Plugin {/** The two glyph pipelines, created lazily; they share layout, page store,* and batch submit — only the atlas contents and shader coverage differ. */private rendererFor(app: App, kind: 'bitmap' | 'sdf', contentScale: number): SdfTextRenderer {- const module = app.wasmModule as ESEngineModule;+ const module = app.wasmModule as ESEngineModule | null;if (kind === 'sdf') {if (!this.sdfRenderer_) {this.sdfRenderer_ = new SdfTextRenderer(module, { sdf: true });diff --git a/sdk/src/ui/text/submit.ts b/sdk/src/ui/text/submit.tsindex 477c7f698..f41e1fe81 100644--- a/sdk/src/ui/text/submit.ts+++ b/sdk/src/ui/text/submit.ts@@ -13,6 +13,31 @@ import { withScratch } from '../../wasmScratch';/** Floats per glyph vertex: position(2) + uv(2) + color(4). */export const TEXT_VERTEX_FLOATS = 8;+/**+ * The same submit, without a wasm heap to marshal through: the native host takes+ * the typed arrays directly and calls the engine's `RenderFrame::submitTextBatch`+ * itself. Arguments mirror {@link submitTextBatch} after the module.+ */+export type NativeTextBatchSubmit = (+ vertices: Float32Array,+ vertexCount: number,+ indices: Uint16Array,+ textureId: number,+ transform: Float32Array,+ entity: number,+ layer: number,+ depth: number,+ sdf: boolean,+) => void;++let nativeSubmit_: NativeTextBatchSubmit | null = null;++/** Install the native host's submit (by the native runtime); null clears it.+ * Only consulted when there is no wasm binding, so web is untouched. */+export function setNativeTextSubmit(submit: NativeTextBatchSubmit | null): void {+ nativeSubmit_ = submit;+}+/*** Submit a batch of glyph quads. `vertices` is `TEXT_VERTEX_FLOATS` floats per* vertex (x,y,u,v,r,g,b,a); `indices` reference those vertices; `transform` is a@@ -20,7 +45,7 @@ export const TEXT_VERTEX_FLOATS = 8;* already world-space). No-op if the engine build lacks the binding.*/export function submitTextBatch(- module: ESEngineModule,+ module: ESEngineModule | null,vertices: Float32Array,indices: Uint16Array,textureId: number,@@ -30,9 +55,13 @@ export function submitTextBatch(depth: number,sdf: boolean,): void {- if (!module.renderer_submitTextBatch) return;const vertexCount = (vertices.length / TEXT_VERTEX_FLOATS) | 0;if (vertexCount <= 0 || indices.length <= 0 || transform.length < 16) return;+ // No wasm heap (the native core): the host reads the arrays as they are.+ if (!module?.renderer_submitTextBatch) {+ nativeSubmit_?.(vertices, vertexCount, indices, textureId, transform, entity, layer, depth, sdf);+ return;+ }// Copy through HEAPU8 (the one heap view emscripten reliably exports here)// as raw bytes; _malloc is ≥8-byte aligned so the C++ f32/u16 reads are fine.diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.tsindex f07f76fbd..1bcb1286f 100644--- a/sdk/src/ui/text/text-renderer.ts+++ b/sdk/src/ui/text/text-renderer.ts@@ -11,8 +11,10 @@* engine page store + submitTextBatch.*/import type { ESEngineModule } from '../../wasm';+import { platformHasGlyphRasterizer } from '../../platform';import { GlyphAtlas } from './glyph-atlas';import { CanvasGlyphRasterizer, type CanvasGlyphRasterizerOptions } from './glyph-rasterizer';+import { NativeGlyphRasterizer } from './native-glyph-rasterizer';import { EngineAtlasPageStore } from './atlas-page-store';import { layoutText, buildGlyphVertices, type LaidGlyph, type RGBA } from './layout';import { submitTextBatch } from './submit';@@ -155,10 +157,17 @@ export class SdfTextRenderer {private readonly sdf: boolean;private readonly cache_ = new Map<number, TextCacheEntry>();- constructor(private readonly module: ESEngineModule, opts: TextRendererOptions = {}) {+ /** `module` is null on the native core (no wasm heap); the glyph source is+ * then the platform's own rasterizer, since there is no 2D canvas to draw+ * glyphs on. Everything above the rasterizer — atlas, layout, batching — is+ * the same code either way. */+ constructor(private readonly module: ESEngineModule | null, opts: TextRendererOptions = {}) {this.sdf = opts.sdf ?? true;+ const rasterizer = platformHasGlyphRasterizer()+ ? new NativeGlyphRasterizer({ renderSize: opts.renderSize, padding: opts.padding, sdf: this.sdf })+ : new CanvasGlyphRasterizer(module, opts);this.atlas = new GlyphAtlas(- new CanvasGlyphRasterizer(module, opts),+ rasterizer,new EngineAtlasPageStore(module),{ pageSize: opts.pageSize, sdf: this.sdf, dpr: opts.dpr },);diff --git a/sdk/tests/native-text.test.ts b/sdk/tests/native-text.test.tsnew file mode 100644index 000000000..834b87cbd--- /dev/null+++ b/sdk/tests/native-text.test.ts@@ -0,0 +1,178 @@+// SPDX-License-Identifier: Apache-2.0+// 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.+ *+ * 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`.+ */+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 { setNativeTextSubmit, TEXT_VERTEX_FLOATS } from '../src/ui/text/submit';+import { 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';+import type { NativeBridge } from '../src/platform/native/bridge';++/** The host's ECS half: entity allocation + per-component storage, enough for a+ * World to spawn a Text entity (see native-world.test.ts for the full surface). */+function installMockEcs(scope: Record<string, unknown>): void {+ let nextId = 1;+ const comps = new Map<string, Map<number, ArrayBuffer>>();+ const store = (cpp: string) => {+ let m = comps.get(cpp);+ if (!m) { m = new Map(); comps.set(cpp, m); }+ return m;+ };+ scope.es_createEntity = () => nextId++;+ scope.es_destroyEntity = (e: number) => { for (const m of comps.values()) m.delete(e); };+ scope.es_hasParent = () => false;+ scope.es_setParent = () => {};+ scope.es_removeParent = () => {};+ scope.es_hasChildren = () => false;+ scope.es_getChildren = () => [];+ for (const cppName of Object.keys(PTR_ACCESSORS)) {+ scope[`es_${cppName}_buffer`] = (e: number) => {+ const m = store(cppName);+ let b = m.get(e);+ if (!b) { b = new ArrayBuffer(256); m.set(e, b); }+ return b;+ };+ scope[`es_${cppName}_has`] = (e: number) => store(cppName).has(e);+ scope[`es_${cppName}_remove`] = (e: number) => { store(cppName).delete(e); };+ }+}++/** A host scope with the full native surface: textures, the glyph rasterizer and+ * the text submit. Every glyph is a solid 8×8 tile, which is all the atlas and+ * the layout need to produce real geometry. */+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 }[] = [];+ let nextHandle = 1;+ const rasterizeSpy = vi.fn((request: PlatformGlyphRequest) => ({+ pixels: new Uint8Array(8 * 8 * 4).fill(255),+ width: 8,+ height: 8,+ advance: request.pixelSize * 0.5,+ bearingX: 0,+ bearingY: 8,+ }));+ const submitSpy = vi.fn();+ const scope: Record<string, unknown> = {+ es_createTexture: (width: number, height: number) => {+ const handle = nextHandle++;+ textures.set(handle, { width, height });+ return handle;+ },+ es_releaseTexture: (handle: number) => { textures.delete(handle); },+ es_getTextureDimensions: (handle: number) => textures.get(handle) ?? null,+ // The atlas page id: the host answers with the engine's render id for the+ // handle. A distinct number here proves the id that reaches the batch is+ // this one, not the ResourceManager handle.+ es_getTextureRenderId: (handle: number) => handle + 100,+ es_updateTextureSubregion: (handle: number, x: number, y: number, w: number, h: number, pixels: Uint8Array) => {+ uploads.push({ handle, x, y, w, h, bytes: pixels.length });+ },+ es_rasterizeGlyph: rasterizeSpy,+ es_submitTextBatch: submitSpy,+ };+ installMockEcs(scope);+ return { scope, uploads, rasterizeSpy, submitSpy };+}++/** The bridge half of the same host: the glyph rasterizer reaches the SDK through+ * the platform adapter, so it is declared here as well as on the scope. */+function makeBridge(scope: Record<string, unknown>): NativeBridge {+ return {+ readFile: async () => new ArrayBuffer(0),+ fileExists: async () => false,+ fetch: async () => ({ ok: false, status: 404 }),+ loadImagePixels: async () => { throw new Error('no images in this test'); },+ rasterizeGlyph: (request) => (scope.es_rasterizeGlyph as (r: PlatformGlyphRequest) => never)(request),+ getStorageItem: () => null,+ setStorageItem: () => {},+ removeStorageItem: () => {},+ storageKeys: () => [],+ registerInput: () => () => {},+ devicePixelRatio: () => 1,+ };+}++afterEach(() => {+ shutdownResourceManager();+ setNativeTextSubmit(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();+ 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 });+ 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();++ // One rasterize per distinct codepoint, asking for the SDF encoding.+ expect(rasterizeSpy).toHaveBeenCalledTimes(2);+ const request = rasterizeSpy.mock.calls[0][0];+ expect(String.fromCodePoint(request.codepoint)).toBe('H');+ expect(request.sdf).toBe(true);+ expect(request.padding).toBeGreaterThan(0);++ // Each glyph landed in the atlas page as an 8×8 RGBA sub-region upload.+ expect(uploads).toHaveLength(2);+ expect(uploads[0]).toMatchObject({ handle: 1, w: 8, h: 8, bytes: 8 * 8 * 4 });++ // One batch for the one page, bound by the host's render id (handle + 100),+ // carrying two quads: 4 vertices and 6 indices each.+ expect(submitSpy).toHaveBeenCalledTimes(1);+ const [vertices, vertexCount, indices, textureId, transform, ent, , , sdf] = submitSpy.mock.calls[0];+ expect(textureId).toBe(101);+ expect(ent).toBe(entity);+ expect(sdf).toBe(true);+ expect(vertexCount).toBe(8);+ expect((vertices as Float32Array).length).toBe(8 * TEXT_VERTEX_FLOATS);+ expect((indices as Uint16Array).length).toBe(12);+ expect((transform as Float32Array).length).toBe(16);+ });++ it('draws nothing — and boots — on a host with no font stack', async () => {+ const { scope, submitSpy } = 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' });+ 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(submitSpy).not.toHaveBeenCalled();+ });+});