Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(native): Assets.loadTexture over a native ResourceManager (Stage B)

yhha6c192ce07d6
diff --git a/native/README.md b/native/README.md
index fcf786e41..2407b33e9 100644
--- a/native/README.md
+++ b/native/README.md
@@ -97,11 +97,22 @@ Dawn with `llvm-strip`), `zipalign -f 4`, `apksigner sign`.
## Status
The engine core + render path are proven on device (Snapdragon 8 Elite / Adreno
-830, 120 fps). The JS host now runs the **real SDK**: `ESEngine.createNativeWorld()`
-returns the same `World` the web build uses, connected to the native core through
-the generated registry + memory backend; the host binds the entity/hierarchy +
-component functions the SDK reads off `globalThis`. Verified on this machine: the
-arm64 host compiles + links with the SDK bundle embedded, and the bundle + game
-script run in a bare JS scope (a QuickJS stand-in). Remaining: an on-device render
-pass of the real-SDK scene, more system bindings (input / audio / assets), and the
-iOS shell (the Metal surface seam is already in place).
+830, 120 fps). The JS host runs the **real SDK**: `ESEngine.createNativeApp()`
+returns the same `App` + `World` the web build uses, connected to the native core
+through the generated registry + memory backend; the host binds the entity /
+hierarchy / component functions the SDK reads off `globalThis`, plus the input and
+texture bindings.
+
+System bindings (Stage B) landing incrementally through the real SDK surfaces:
+
+- **Input** — host touch → the SDK's `inputPlugin` → the `Input` resource (device-verified).
+- **Assets** — `ESEngine.Assets.loadTexture(path)` runs the SAME asset pipeline the
+ web build uses: the platform decodes the image (`bridge.loadImagePixels`) and the
+ **native ResourceManager** (`createNativeResourceManager`, over the host's
+ `es_createTexture` / `es_releaseTexture` / `es_getTextureDimensions`) uploads the
+ bytes directly — no wasm heap. `game.js` now loads its logo through this channel
+ instead of a hand-rolled `es_createTexture`.
+
+Remaining: audio, lifecycle, and the cooked-asset manifest (import settings / KTX2 /
+atlases) that the editor's native-export pipeline will ship (Stage C); then the iOS
+shell (the Metal surface seam is already in place).
diff --git a/native/js/game.js b/native/js/game.js
index ec3012a7e..5d48c09ab 100644
--- a/native/js/game.js
+++ b/native/js/game.js
@@ -1,8 +1,8 @@
// Demo game — pure game logic, loaded at runtime from the APK's assets/ (NOT
// compiled into the C++ host). It authors through the real SDK exactly like a web
-// game: ESEngine.createNativeApp + world.spawn/insert + the Input resource. The
-// host provides `ESEngine` (SDK bundle), the `es_*` globals, the frame constants
-// W/H/S, and the platform bridge `__esNativeBridge`.
+// game: ESEngine.createNativeApp + world.spawn/insert + the Input and Assets
+// resources. The host provides `ESEngine` (SDK bundle), the `es_*` globals, the
+// frame constants W/H/S, and the platform bridge `__esNativeBridge`.
//
// A sprite follows the touch; a shape orbits — proof the real App runs on device.
@@ -14,8 +14,9 @@ function init() {
app.tick(0); // sync through finishPlugins: binds input + inserts Input
world = app.world;
input = app.getResource(ESEngine.Input);
+ var assets = app.getResource(ESEngine.Assets);
- // Fallback 2x2 checker while the real image decodes.
+ // Fallback 2x2 checker (a tiny inline texture) while the real image loads.
var tex = es_createTexture(2, 2, [
255, 0, 0, 255, 0, 255, 0, 255,
0, 0, 255, 255, 255, 255, 0, 255 ]);
@@ -25,13 +26,15 @@ function init() {
world.insert(follower, ESEngine.Sprite, {
texture: tex, color: { r: 1, g: 1, b: 1, a: 1 }, size: { x: S * 0.28, y: S * 0.28 } });
- // Load a REAL image (logo.png) from the APK through the SDK platform
- // (NativeBridge.loadImagePixels), decoded by the host with stb_image, and swap
- // it onto the follower — proving the native image-decode -> texture path.
- globalThis.__esNativeBridge.loadImagePixels('logo.png').then(function (img) {
- var logo = es_createTexture(img.width, img.height, img.pixels);
+ // Load logo.png through the REAL SDK asset pipeline — the SAME Assets API a web
+ // game uses. Assets.loadTexture decodes the image via the platform
+ // (bridge.loadImagePixels) and uploads it through the native ResourceManager,
+ // returning a tracked handle. No hand-rolled es_createTexture: the demo now
+ // exercises the unified asset channel, not a bespoke native texture path.
+ assets.loadTexture('logo.png').then(function (result) {
world.insert(follower, ESEngine.Sprite, {
- texture: logo, color: { r: 1, g: 1, b: 1, a: 1 }, size: { x: S * 0.28, y: S * 0.28 } });
+ texture: result.handle, color: { r: 1, g: 1, b: 1, a: 1 },
+ size: { x: S * 0.28, y: S * 0.28 } });
});
orbit = world.spawn();
diff --git a/native/js/main.cpp b/native/js/main.cpp
index db568f159..30f31ee4f 100644
--- a/native/js/main.cpp
+++ b/native/js/main.cpp
@@ -35,6 +35,7 @@
#include "esengine/renderer/RenderFrame.hpp"
#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
#include "esengine/resource/ResourceManager.hpp"
+#include "esengine/resource/ShaderParser.hpp" // linearColorSpace() — texture format at the JS boundary
#include <glm/gtc/matrix_transform.hpp>
@@ -199,27 +200,90 @@ JSValue js_setClear(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {
g_app->clear = {(f32)r, (f32)g, (f32)b, 1.0f};
return JS_UNDEFINED;
}
-JSValue js_createTexture(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {
- int32_t w = 0, h = 0;
- JS_ToInt32(ctx, &w, argv[0]);
- JS_ToInt32(ctx, &h, argv[1]);
+// Read an RGBA byte source into `out`. Fast path: a Uint8Array (what the SDK's
+// createTextureFromBytes hands us) — copy straight from its ArrayBuffer. Fallback:
+// a plain JS number array (the tiny inline checker some scripts build) — index it.
+void readByteSource(JSContext* ctx, JSValueConst v, std::vector<u8>& out) {
+ size_t byteOffset = 0, byteLen = 0, bytesPerEl = 0;
+ JSValue ab = JS_GetTypedArrayBuffer(ctx, v, &byteOffset, &byteLen, &bytesPerEl);
+ if (!JS_IsException(ab)) {
+ size_t abSize = 0;
+ uint8_t* base = JS_GetArrayBuffer(ctx, &abSize, ab);
+ if (base && byteOffset + byteLen <= abSize) {
+ out.assign(base + byteOffset, base + byteOffset + byteLen);
+ }
+ JS_FreeValue(ctx, ab);
+ return;
+ }
+ JS_FreeValue(ctx, ab);
+ JS_FreeValue(ctx, JS_GetException(ctx)); // not a typed array — clear + index it
uint32_t len = 0;
- JSValue lv = JS_GetPropertyStr(ctx, argv[2], "length");
+ JSValue lv = JS_GetPropertyStr(ctx, v, "length");
JS_ToUint32(ctx, &len, lv);
JS_FreeValue(ctx, lv);
- std::vector<u8> pixels(len);
+ out.resize(len);
for (uint32_t i = 0; i < len; ++i) {
- JSValue el = JS_GetPropertyUint32(ctx, argv[2], i);
- int32_t v = 0;
- JS_ToInt32(ctx, &v, el);
- pixels[i] = (u8)v;
+ JSValue el = JS_GetPropertyUint32(ctx, v, i);
+ int32_t iv = 0;
+ JS_ToInt32(ctx, &iv, el);
+ out[i] = (u8)iv;
JS_FreeValue(ctx, el);
}
+}
+
+// The texture format at the JS boundary — mirrors bindings/ResourceManagerBindings
+// boundaryTextureFormat so native and web upload colour identically (format 0 = RGB8;
+// else sRGB variant under the linear pipeline, plain RGBA8 in gamma).
+TextureFormat boundaryTextureFormat(int32_t format) {
+ if (format == 0) return TextureFormat::RGB8;
+ if (resource::ShaderParser::linearColorSpace()) return TextureFormat::SRGB8A8;
+ return TextureFormat::RGBA8;
+}
+
+// es_createTexture(w, h, pixels, format?, flip?, filter?, wrap?) -> handle id.
+// Backs the native ResourceManager's createTextureFromBytes: the SDK decodes an
+// image to RGBA (loadImagePixels) and hands the bytes here — no wasm heap. filter/
+// wrap arrive with the cooked-asset import settings (Stage C); until then only the
+// default sampler is used, matching the plain rm_createTexture path.
+JSValue js_createTexture(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
+ int32_t w = 0, h = 0;
+ JS_ToInt32(ctx, &w, argv[0]);
+ JS_ToInt32(ctx, &h, argv[1]);
+ std::vector<u8> pixels;
+ readByteSource(ctx, argv[2], pixels);
+
+ int32_t format = 1; // default: colour (RGBA8 / sRGB)
+ if (argc > 3 && !JS_IsUndefined(argv[3])) JS_ToInt32(ctx, &format, argv[3]);
+ bool flip = (argc > 4 && !JS_IsUndefined(argv[4])) ? JS_ToBool(ctx, argv[4]) != 0 : false;
+
auto handle = g_app->ctx->require<resource::ResourceManager>().createTexture(
- (u32)w, (u32)h, ConstSpan<u8>(pixels.data(), pixels.size()), TextureFormat::RGBA8, false);
+ (u32)w, (u32)h, ConstSpan<u8>(pixels.data(), pixels.size()),
+ boundaryTextureFormat(format), flip);
return JS_NewInt64(ctx, (int64_t)handle.id());
}
+// es_releaseTexture(handle) — drop one native ResourceManager reference.
+JSValue js_releaseTexture(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {
+ int64_t id = 0;
+ JS_ToInt64(ctx, &id, argv[0]);
+ g_app->ctx->require<resource::ResourceManager>().releaseTexture(
+ resource::TextureHandle((u32)id));
+ return JS_UNDEFINED;
+}
+
+// es_getTextureDimensions(handle) -> { width, height } | null.
+JSValue js_getTextureDimensions(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));
+ if (!tex) return JS_NULL;
+ JSValue obj = JS_NewObject(ctx);
+ JS_SetPropertyStr(ctx, obj, "width", JS_NewInt32(ctx, (int32_t)tex->getWidth()));
+ JS_SetPropertyStr(ctx, obj, "height", JS_NewInt32(ctx, (int32_t)tex->getHeight()));
+ return obj;
+}
+
// Read an APK asset (assets/<path>) fully into a buffer; empty if missing. This is
// the native NativeBridge.readFile capability — a packaged (project-relative) file.
std::vector<u8> readAsset(App& a, const char* path) {
@@ -404,9 +468,13 @@ void initJS(App& a) {
bindGlobal(a, global, "es_removeParent", js_removeParent, 1);
bindGlobal(a, global, "es_hasChildren", js_hasChildren, 1);
bindGlobal(a, global, "es_getChildren", js_getChildren, 1);
- // Resources + clear + asset reads.
+ // Resources + clear + asset reads. es_createTexture / es_releaseTexture /
+ // es_getTextureDimensions are the native ResourceManager contract the SDK's
+ // createNativeResourceManager binds to (the asset pipeline's texture backend).
bindGlobal(a, global, "es_setClear", js_setClear, 3);
bindGlobal(a, global, "es_createTexture", js_createTexture, 3);
+ bindGlobal(a, global, "es_releaseTexture", js_releaseTexture, 1);
+ bindGlobal(a, global, "es_getTextureDimensions", js_getTextureDimensions, 1);
bindGlobal(a, global, "es_readAsset", js_readAsset, 1);
bindGlobal(a, global, "es_loadImagePixels", js_loadImagePixels, 1);
// Per-component bindings (EHT-generated): es_set_<C> / es_<C>_buffer / _has / _remove.
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 43bcf96a3..88c036572 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1770,6 +1770,7 @@ createLabelAtlasFont: (textureHandle: number, texWidth: number, texHeight: numbe
createShader: (vertSrc: string, fragSrc: string) => number
createTexture: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean) => number
createTextureEx: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number) => number
+createTextureFromBytes: ((width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, filterMode?: number, wrapMode?: number) => number) | undefined
getBitmapFontRefCount: (handle: number) => number
getResourceStats: () => { shaderCount: number; textureCount: number; vertexBufferCount: number; indexBufferCount: number; cacheHits: number; cacheMisses: number; textureBytes: number; textureBudget: number; textureEvictableCount: number; }
getShaderRefCount: (handle: number) => number
@@ -1789,6 +1790,7 @@ setTextureBudget: (bytes: number) => void
setTextureMetadata: (handle: number, left: number, right: number, top: number, bottom: number) => void
trimTextureCache: () => number
updateTextureSubregion: (handle: number, x: number, y: number, width: number, height: number, pixels: number, pixelsLen: number) => void
+updateTextureSubregionFromBytes: ((handle: number, x: number, y: number, width: number, height: number, pixels: Uint8Array) => void) | undefined
```
## CreateListViewOptions — interface
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 6235449ed..db8891b10 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1329 stable · 22 beta · 0 deprecated
+Symbols: 1330 stable · 22 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1778,6 +1778,7 @@ createLabelAtlasFont: (textureHandle: number, texWidth: number, texHeight: numbe
createShader: (vertSrc: string, fragSrc: string) => number
createTexture: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean) => number
createTextureEx: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number) => number
+createTextureFromBytes: ((width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, filterMode?: number, wrapMode?: number) => number) | undefined
getBitmapFontRefCount: (handle: number) => number
getResourceStats: () => { shaderCount: number; textureCount: number; vertexBufferCount: number; indexBufferCount: number; cacheHits: number; cacheMisses: number; textureBytes: number; textureBudget: number; textureEvictableCount: number; }
getShaderRefCount: (handle: number) => number
@@ -1797,6 +1798,7 @@ setTextureBudget: (bytes: number) => void
setTextureMetadata: (handle: number, left: number, right: number, top: number, bottom: number) => void
trimTextureCache: () => number
updateTextureSubregion: (handle: number, x: number, y: number, width: number, height: number, pixels: number, pixelsLen: number) => void
+updateTextureSubregionFromBytes: ((handle: number, x: number, y: number, width: number, height: number, pixels: Uint8Array) => void) | undefined
```
## CreateListViewOptions — interface
@@ -8448,6 +8450,11 @@ Plugin
(scope?: Record<string, unknown>): CppRegistry
```
+## createNativeResourceManager — function
+```
+(scope?: Record<string, unknown>): CppResourceManager
+```
+
## createNativeWorld — function
```
(scope?: Record<string, unknown>): World
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index ba12dcfbd..619c09b1e 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1765,6 +1765,7 @@ createLabelAtlasFont: (textureHandle: number, texWidth: number, texHeight: numbe
createShader: (vertSrc: string, fragSrc: string) => number
createTexture: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean) => number
createTextureEx: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number) => number
+createTextureFromBytes: ((width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, filterMode?: number, wrapMode?: number) => number) | undefined
getBitmapFontRefCount: (handle: number) => number
getResourceStats: () => { shaderCount: number; textureCount: number; vertexBufferCount: number; indexBufferCount: number; cacheHits: number; cacheMisses: number; textureBytes: number; textureBudget: number; textureEvictableCount: number; }
getShaderRefCount: (handle: number) => number
@@ -1784,6 +1785,7 @@ setTextureBudget: (bytes: number) => void
setTextureMetadata: (handle: number, left: number, right: number, top: number, bottom: number) => void
trimTextureCache: () => number
updateTextureSubregion: (handle: number, x: number, y: number, width: number, height: number, pixels: number, pixelsLen: number) => void
+updateTextureSubregionFromBytes: ((handle: number, x: number, y: number, width: number, height: number, pixels: Uint8Array) => void) | undefined
```
## CreateListViewOptions — interface
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 1f323d245..8a5393481 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -140,6 +140,7 @@ createLabelAtlasFont: (textureHandle: number, texWidth: number, texHeight: numbe
createShader: (vertSrc: string, fragSrc: string) => number
createTexture: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean) => number
createTextureEx: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number) => number
+createTextureFromBytes: ((width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, filterMode?: number, wrapMode?: number) => number) | undefined
getBitmapFontRefCount: (handle: number) => number
getResourceStats: () => { shaderCount: number; textureCount: number; vertexBufferCount: number; indexBufferCount: number; cacheHits: number; cacheMisses: number; textureBytes: number; textureBudget: number; textureEvictableCount: number; }
getShaderRefCount: (handle: number) => number
@@ -159,6 +160,7 @@ setTextureBudget: (bytes: number) => void
setTextureMetadata: (handle: number, left: number, right: number, top: number, bottom: number) => void
trimTextureCache: () => number
updateTextureSubregion: (handle: number, x: number, y: number, width: number, height: number, pixels: number, pixelsLen: number) => void
+updateTextureSubregionFromBytes: ((handle: number, x: number, y: number, width: number, height: number, pixels: Uint8Array) => void) | undefined
```
## ESEngineModule — interface
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 01b966e1a..bf705d535 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1765,6 +1765,7 @@ createLabelAtlasFont: (textureHandle: number, texWidth: number, texHeight: numbe
createShader: (vertSrc: string, fragSrc: string) => number
createTexture: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean) => number
createTextureEx: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number) => number
+createTextureFromBytes: ((width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, filterMode?: number, wrapMode?: number) => number) | undefined
getBitmapFontRefCount: (handle: number) => number
getResourceStats: () => { shaderCount: number; textureCount: number; vertexBufferCount: number; indexBufferCount: number; cacheHits: number; cacheMisses: number; textureBytes: number; textureBudget: number; textureEvictableCount: number; }
getShaderRefCount: (handle: number) => number
@@ -1784,6 +1785,7 @@ setTextureBudget: (bytes: number) => void
setTextureMetadata: (handle: number, left: number, right: number, top: number, bottom: number) => void
trimTextureCache: () => number
updateTextureSubregion: (handle: number, x: number, y: number, width: number, height: number, pixels: number, pixelsLen: number) => void
+updateTextureSubregionFromBytes: ((handle: number, x: number, y: number, width: number, height: number, pixels: Uint8Array) => void) | undefined
```
## CreateListViewOptions — interface
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 01645413f..fbb1ec12b 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -129,7 +129,9 @@ export interface AssetsOptions {
* {@link ManifestModel}. Optional — label/path loading works without it.
*/
manifest?: AddressableManifest | ManifestModel;
- module: ESEngineModule;
+ /** The wasm module, or null on the native (embedded-Dawn) backend, which has
+ * no wasm heap — its ResourceManager uploads texture bytes directly. */
+ module: ESEngineModule | null;
/**
* Lazy accessor for the owning app's Audio API. AudioAssetLoader
* calls it at load time so AssetPlugin and AudioPlugin can be built
@@ -194,7 +196,7 @@ export class Assets {
}
private baseUrl_?: string;
- private module_: ESEngineModule;
+ private module_: ESEngineModule | null;
private manifestModel_: ManifestModel | null = null;
/** CDN root that `remote`-group assets resolve against; see {@link setRemoteRoot}. */
private remoteRoot_?: string;
diff --git a/sdk/src/asset/loaders/SpineAssetLoader.ts b/sdk/src/asset/loaders/SpineAssetLoader.ts
index d4584d95c..e3c415e62 100644
--- a/sdk/src/asset/loaders/SpineAssetLoader.ts
+++ b/sdk/src/asset/loaders/SpineAssetLoader.ts
@@ -12,13 +12,13 @@ export class SpineAssetLoader implements AssetLoader<SpineResult> {
readonly type = 'spine';
readonly extensions = ['.skel'];
- private module_: ESEngineModule;
+ private module_: ESEngineModule | null;
private spineController_: SpineModuleController | null = null;
private loaded_ = new Set<string>();
private virtualFSPaths_ = new Set<string>();
private skeletonHandles_ = new Map<string, number>();
- constructor(module: ESEngineModule) {
+ constructor(module: ESEngineModule | null) {
this.module_ = module;
}
@@ -119,7 +119,7 @@ export class SpineAssetLoader implements AssetLoader<SpineResult> {
private writeToVirtualFS(virtualPath: string, data: string | Uint8Array): void {
if (this.virtualFSPaths_.has(virtualPath)) return;
- const fs = this.module_.FS;
+ const fs = this.module_?.FS;
if (!fs) return;
try {
@@ -132,7 +132,7 @@ export class SpineAssetLoader implements AssetLoader<SpineResult> {
}
private cleanupVirtualFS(): void {
- const fs = this.module_.FS;
+ const fs = this.module_?.FS;
if (!fs) return;
for (const path of this.virtualFSPaths_) {
try { fs.unlink(path); } catch { /* already removed */ }
diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.ts
index ea6f2e6da..0bfc16609 100644
--- a/sdk/src/asset/loaders/TextureLoader.ts
+++ b/sdk/src/asset/loaders/TextureLoader.ts
@@ -58,7 +58,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {
readonly type = 'texture';
readonly extensions = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.ktx2'];
- private module_: ESEngineModule;
+ private module_: ESEngineModule | null;
/**
* Basis transcoder for KTX2 assets. Either injected directly via
* {@link setTranscoder} (tests / embedded realms) or acquired lazily on the
@@ -93,7 +93,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {
*/
importSettingsResolver: TextureImportSettingsResolver | null = null;
- constructor(module: ESEngineModule) {
+ constructor(module: ESEngineModule | null) {
this.module_ = module;
}
@@ -135,8 +135,18 @@ export class TextureLoader implements AssetLoader<TextureResult> {
width: number, height: number, pixels: Uint8Array, flipY: boolean,
): Promise<TextureResult> {
const rm = requireResourceManager();
- const handle = withMalloc(this.module_, pixels.length, ptr => {
- this.module_.HEAPU8.set(pixels, ptr);
+ // Native (no wasm heap): upload the bytes directly. Web embind lacks this
+ // method, so it takes the heap path below unchanged.
+ if (rm.createTextureFromBytes) {
+ const handle = rm.createTextureFromBytes(width, height, pixels, 1, flipY);
+ return { handle, width, height };
+ }
+ if (!this.module_) {
+ throw new Error('TextureLoader.loadFromPixels: no wasm module and no native byte-upload path');
+ }
+ const module = this.module_;
+ const handle = withMalloc(module, pixels.length, ptr => {
+ module.HEAPU8.set(pixels, ptr);
return rm.createTexture(width, height, ptr, pixels.length, 1, flipY);
});
return { handle, width, height };
@@ -201,7 +211,9 @@ export class TextureLoader implements AssetLoader<TextureResult> {
}
// KTX2 payloads are color, like the PNG path: linear mode wants the
// sRGB variant of whatever compressed format the device supports.
- const r = loadCompressedTexture(gl, this.module_, transcoder, bytes,
+ // A WebGL2 context implies a wasm module (native has neither, and threw
+ // above on the missing gl); the KTX2 path is web-only.
+ const r = loadCompressedTexture(gl, this.module_!, transcoder, bytes,
{ ...settings, srgb: linearColorSpace() });
return { handle: r.handle, width: r.width, height: r.height };
}
@@ -253,7 +265,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {
}
private getWebGL2Context(): WebGL2RenderingContext | null {
- return findWebGL2Context(this.module_.GL);
+ return findWebGL2Context(this.module_?.GL);
}
private createTextureWebGL2(
@@ -302,7 +314,8 @@ export class TextureLoader implements AssetLoader<TextureResult> {
throw err;
}
- const glObj = this.module_.GL;
+ // This path runs only with a live WebGL2 context, which implies a module.
+ const glObj = this.module_!.GL;
const glTextureId = glObj.getNewId(glObj.textures);
glObj.textures[glTextureId] = texture;
@@ -316,6 +329,14 @@ export class TextureLoader implements AssetLoader<TextureResult> {
width: number, height: number, flip: boolean,
settings?: TextureImportSettings,
): TextureResult {
+ // The 2D-canvas fallback is web-only: it decodes through an offscreen
+ // canvas + wasm heap upload. Native never reaches it — it sets a
+ // pixelDecoder, so decodeAndUpload_ takes the createTextureFromPixels
+ // (byte) path before this — so require the module rather than pretend.
+ if (!this.module_) {
+ throw new Error('TextureLoader: 2D-canvas fallback needs a wasm module (native uses the pixel-decode path)');
+ }
+ const module = this.module_;
const { canvas, ctx } = this.ensureCanvas_();
if (canvas.width < width || canvas.height < height) {
canvas.width = Math.max(canvas.width, nextPowerOf2(width));
@@ -332,8 +353,8 @@ export class TextureLoader implements AssetLoader<TextureResult> {
const rm = requireResourceManager();
// Format 2 = sRGB color under the linear pipeline (see rm_createTexture).
const format = linearColorSpace() && (settings?.srgb ?? true) ? 2 : 1;
- const handle = withMalloc(this.module_, pixels.length, ptr => {
- this.module_.HEAPU8.set(pixels, ptr);
+ const handle = withMalloc(module, pixels.length, ptr => {
+ module.HEAPU8.set(pixels, ptr);
return rm.createTexture(width, height, ptr, pixels.length, format, flip);
});
diff --git a/sdk/src/ecs/nativeResourceManager.ts b/sdk/src/ecs/nativeResourceManager.ts
new file mode 100644
index 000000000..7513496b7
--- /dev/null
+++ b/sdk/src/ecs/nativeResourceManager.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The native ResourceManager — the embedded-Dawn sibling of the embind-bound C++
+// ResourceManager. It presents the CppResourceManager surface the SDK's asset
+// pipeline consumes (createTexture / releaseTexture / getTextureDimensions), so
+// the real Assets channel + TextureLoader run on the native core unchanged.
+//
+// The one wasm-specific op in the texture path — marshal RGBA into the wasm heap,
+// then call embind createTexture(ptr) — becomes createTextureFromBytes here: the
+// native core has no wasm heap, so the host uploads the JS-owned bytes directly
+// (es_createTexture). This mirrors how createNativeRegistry composes the ECS over
+// es_* host globals; the same single generated/marshalling philosophy, one more
+// backend. The upload helpers (runtimeAssets, TextureLoader) prefer this byte
+// method when present, so web (embind, no such method) stays byte-identical.
+
+import type { CppResourceManager } from '../wasm';
+
+/** Invoke a host-provided global by name; throws if the host did not bind it
+ * (these are part of the native ResourceManager contract). */
+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);
+}
+
+/** Optional host global — returns undefined (and does nothing) when unbound, for
+ * the residency/budget hooks a minimal host may not provide 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);
+}
+
+/**
+ * Build the CppResourceManager over the host's native texture bindings. `scope`
+ * holds the globals (the QuickJS global object on a device; a plain object in
+ * tests): the host binds
+ * * es_createTexture(w, h, pixels, format, flip, filter?, wrap?) -> handle
+ * * es_releaseTexture(handle)
+ * * es_getTextureDimensions(handle) -> { width, height } | null
+ * 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 /
+ * 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).
+ */
+export function createNativeResourceManager(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): CppResourceManager {
+ const rm: Partial<CppResourceManager> = {
+ // The module-free upload the SDK prefers on native (no wasm heap).
+ createTextureFromBytes: (
+ width, height, pixels, format, flipY, filterMode, wrapMode,
+ ): number =>
+ hostCall(scope, 'es_createTexture',
+ [width, height, pixels, format, flipY, filterMode, wrapMode]) as number,
+
+ updateTextureSubregionFromBytes: (handle, x, y, width, height, pixels): void => {
+ hostCallOpt(scope, 'es_updateTextureSubregion', [handle, x, y, width, height, pixels]);
+ },
+
+ releaseTexture: (handle): void => {
+ hostCallOpt(scope, 'es_releaseTexture', [handle]);
+ },
+
+ getTextureDimensions: (handle): { width: number; height: number } | null =>
+ (hostCallOpt(scope, 'es_getTextureDimensions', [handle]) as
+ { width: number; height: number } | null | undefined) ?? null,
+
+ // The engine applies RuntimeConfig.textureCacheBudget at startup; forward it
+ // to the native pool when the host wires it, else no-op (eviction off).
+ setTextureBudget: (bytes): void => {
+ hostCallOpt(scope, 'es_setTextureBudget', [bytes]);
+ },
+ };
+
+ // The heap-pointer / GL / bitmap-font surface is not reachable on native (the
+ // asset path takes the byte upload above); fail loud rather than silently
+ // corrupt if some path ever calls one.
+ const unsupported = (name: string) => (): never => {
+ throw new Error(`native ResourceManager: ${name} is not supported (no wasm heap / GL on the embedded-Dawn core)`);
+ };
+ rm.createTexture = unsupported('createTexture(ptr)');
+ 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.ts
index 17b1fe8d1..576b4fb71 100644
--- a/sdk/src/ecs/nativeRuntime.ts
+++ b/sdk/src/ecs/nativeRuntime.ts
@@ -17,6 +17,12 @@ import { ensureBuiltinComponentsRegistered } from '../component';
import { installNativePlatform, type NativeBridge } from '../platform/native';
import { createNativeRegistry } from './nativeRegistry';
import { NativeMemoryProvider } from './memoryProvider';
+import { createNativeResourceManager } from './nativeResourceManager';
+import { initResourceManager } from '../resourceManager';
+import { Assets as AssetsClass } from '../asset/Assets';
+import { Assets as AssetsResource } from '../asset/AssetPlugin';
+import { FileSystemBackend } from '../asset/Backend';
+import { platformLoadImagePixels } from '../platform';
/**
* Create a World bound to the native core. `scope` is where the host installed its
@@ -64,5 +70,35 @@ export function createNativeApp(
memory: new NativeMemoryProvider(scope),
});
app.addPlugin(inputPlugin);
+ installNativeAssets(app, scope);
return app;
}
+
+/**
+ * Install the native asset channel — the same `Assets` class the web build uses,
+ * over the native core. The native analog of the AssetPlugin / runtimeLoader
+ * wiring: no wasm module (the {@link createNativeResourceManager} uploads texture
+ * bytes directly), a filesystem backend that reads packaged files through the
+ * host `NativeBridge`, and the pixel-decode channel (`bridge.loadImagePixels`)
+ * wechat / playable also use — so `Assets.loadTexture(path)` returns a handle the
+ * native ResourceManager tracks, replacing hand-rolled host texture creation.
+ *
+ * Kept deliberately lean (no KTX2 side-module / import-settings / ref-counter
+ * wiring yet) — those arrive with the cooked-asset manifest in the export
+ * pipeline. Same-signature loaders, so it never diverges from the web channel.
+ */
+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.
+ initResourceManager(createNativeResourceManager(scope));
+
+ const assets = AssetsClass.create({
+ backend: new FileSystemBackend(),
+ module: null, // no wasm heap on native — the RM takes bytes directly
+ });
+ // Textures take the Path-2 pixel-decode route: the platform decodes the image
+ // to RGBA (bridge.loadImagePixels), then TextureLoader uploads through the
+ // native ResourceManager's createTextureFromBytes. `flip` is applied on upload.
+ assets.getTextureLoader().setPixelDecoder((path) => platformLoadImagePixels(path));
+ app.insertResource(AssetsResource, assets);
+}
diff --git a/sdk/src/index.native.ts b/sdk/src/index.native.ts
index ac37a78f7..8dc8c02ec 100644
--- a/sdk/src/index.native.ts
+++ b/sdk/src/index.native.ts
@@ -49,6 +49,12 @@ export type { MemoryProvider, ComponentHeap, NativeComponentBufferFn } from './e
// _remove bindings; pass to BuiltinBridge.connect as the cppRegistry.
export { createNativeRegistry } from './ecs/nativeRegistry';
+// The native ResourceManager — the embind-ResourceManager sibling the SDK's asset
+// pipeline drives (createTexture / releaseTexture / dims). Built over the host's
+// es_createTexture / es_releaseTexture / es_getTextureDimensions bindings; uploads
+// texture bytes directly (no wasm heap). createNativeApp installs one automatically.
+export { createNativeResourceManager } from './ecs/nativeResourceManager';
+
// Boot the real SDK ECS World over the native core — the host's entry point for
// running the actual SDK (spawn/insert/query authoring) against native C++ ECS.
export { createNativeWorld } from './ecs/nativeRuntime';
diff --git a/sdk/src/runtimeAssets.ts b/sdk/src/runtimeAssets.ts
index 9a7c3189d..78ce9d42a 100644
--- a/sdk/src/runtimeAssets.ts
+++ b/sdk/src/runtimeAssets.ts
@@ -52,9 +52,11 @@ export interface TextureParams {
const FILTER_MODE_MAP: Record<string, number> = { 'nearest': 0, 'linear': 1 };
const WRAP_MODE_MAP: Record<string, number> = { 'repeat': 0, 'clamp': 1, 'mirror': 2 };
-/** Upload decoded RGBA pixels as a GL texture; returns the engine texture handle. */
+/** Upload decoded RGBA pixels as a GL texture; returns the engine texture handle.
+ * `module` is the wasm-heap marshalling vehicle; it may be null on the native
+ * (embedded-Dawn) backend, whose ResourceManager takes the bytes directly. */
export function createTextureFromPixels(
- module: ESEngineModule,
+ module: ESEngineModule | null,
result: { width: number; height: number; pixels: Uint8Array },
flipY: boolean = true,
params?: TextureParams,
@@ -62,6 +64,17 @@ export function createTextureFromPixels(
const rm = requireResourceManager();
// Format code 2 = sRGB-encoded color (linear pipeline); 1 = plain RGBA8.
const format = linearColorSpace() && (params?.srgb ?? true) ? 2 : 1;
+ // Native path: no wasm heap — the ResourceManager uploads the bytes itself.
+ // The wasm embind object has no createTextureFromBytes, so web falls through
+ // to the heap path below unchanged.
+ if (rm.createTextureFromBytes) {
+ const filter = params?.filterMode ? FILTER_MODE_MAP[params.filterMode] ?? 1 : undefined;
+ const wrap = params?.wrapMode ? WRAP_MODE_MAP[params.wrapMode] ?? 1 : undefined;
+ return rm.createTextureFromBytes(result.width, result.height, result.pixels, format, flipY, filter, wrap);
+ }
+ if (!module) {
+ throw new Error('createTextureFromPixels: a wasm module is required for the heap upload path');
+ }
return withMalloc(module, result.pixels.length, ptr => {
module.HEAPU8.set(result.pixels, ptr);
@@ -81,7 +94,7 @@ export function createTextureFromPixels(
* rect must lie inside the texture (the engine bounds-checks and no-ops if not).
*/
export function updateTextureSubregion(
- module: ESEngineModule,
+ module: ESEngineModule | null,
handle: number,
x: number,
y: number,
@@ -91,7 +104,12 @@ export function updateTextureSubregion(
): void {
if (width <= 0 || height <= 0 || pixels.length === 0) return;
const rm = requireResourceManager();
- if (!rm.updateTextureSubregion) return;
+ // Native byte path (no wasm heap); web embind lacks it and takes the heap path.
+ if (rm.updateTextureSubregionFromBytes) {
+ rm.updateTextureSubregionFromBytes(handle, x, y, width, height, pixels);
+ return;
+ }
+ if (!rm.updateTextureSubregion || !module) return;
withMalloc(module, pixels.length, ptr => {
module.HEAPU8.set(pixels, ptr);
rm.updateTextureSubregion(handle, x, y, width, height, ptr, pixels.length);
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index f918bcd23..690380052 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -42,6 +42,16 @@ export interface CppRegistry extends GeneratedRegistry {
export interface CppResourceManager {
createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
createTextureEx(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number): number;
+ /**
+ * Module-free texture upload: take the RGBA bytes directly instead of a wasm
+ * heap pointer. Present ONLY on the native ResourceManager (embedded Dawn, no
+ * wasm heap to marshal into); the wasm embind object does not implement it, so
+ * the upload helpers fall through to the heap path and web stays byte-identical.
+ * `filterMode`/`wrapMode` mirror {@link createTextureEx}'s codes (optional). */
+ createTextureFromBytes?(width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, filterMode?: number, wrapMode?: number): number;
+ /** Module-free {@link updateTextureSubregion} — native byte upload for the
+ * glyph atlas, symmetric with {@link createTextureFromBytes}. */
+ updateTextureSubregionFromBytes?(handle: number, x: number, y: number, width: number, height: number, pixels: Uint8Array): void;
createShader(vertSrc: string, fragSrc: string): number;
registerExternalTexture(glTextureId: number, width: number, height: number): number;
/** Like registerExternalTexture, but with the actual GPU byte size for the
diff --git a/sdk/tests/binding-surface.test.ts b/sdk/tests/binding-surface.test.ts
index b6a68ab37..47d4e02a6 100644
--- a/sdk/tests/binding-surface.test.ts
+++ b/sdk/tests/binding-surface.test.ts
@@ -359,6 +359,12 @@ describe('WASM binding surface: embind class methods', () => {
it('CppResourceManager mirrors class_<ResourceManager> exactly', () => {
const cpp = parseClassRegistration(webSdkEntry, 'ResourceManager');
const ts = parseInterfaceMethods(wasmTs, 'CppResourceManager');
+ // Native (embedded-Dawn) byte-upload methods: no wasm heap to marshal into,
+ // so they take the RGBA bytes directly and have NO embind counterpart on the
+ // web ResourceManager. Optional + native-only by construction — exempt from
+ // the web mirror the way embind's implicit `delete` is below.
+ ts.delete('createTextureFromBytes');
+ ts.delete('updateTextureSubregionFromBytes');
expect(sorted(ts)).toEqual(sorted(cpp.keys()));
});
diff --git a/sdk/tests/native-adapter.test.ts b/sdk/tests/native-adapter.test.ts
index 1c545f918..5ae5634fd 100644
--- a/sdk/tests/native-adapter.test.ts
+++ b/sdk/tests/native-adapter.test.ts
@@ -239,6 +239,10 @@ describe('node adapter surfaces (fail loud, no render host)', () => {
});
describe('esengine/native entry', () => {
+ // These two transform the WHOLE native entry graph (core + webAppFactory +
+ // every re-export) on first import — several seconds cold, and slower still
+ // under the full suite's parallel load. Give them room past the 5s default so
+ // they measure re-export wiring, not machine contention.
it('re-exports the native surface + the core SDK', async () => {
const native = await import('../src/index.native');
expect(typeof native.installNativePlatform).toBe('function');
@@ -247,7 +251,7 @@ describe('esengine/native entry', () => {
expect(typeof native.createWebApp).toBe('function');
expect(typeof native.createHeadlessApp).toBe('function');
expect(typeof native.App).toBe('function');
- });
+ }, 30000);
it('installNativePlatform from the entry activates the native platform', async () => {
const native = await import('../src/index.native');
@@ -255,5 +259,5 @@ describe('esengine/native entry', () => {
const { getPlatformType, isNative } = await import('../src/platform');
expect(getPlatformType()).toBe('native');
expect(isNative()).toBe(true);
- });
+ }, 30000);
});
diff --git a/sdk/tests/native-assets.test.ts b/sdk/tests/native-assets.test.ts
new file mode 100644
index 000000000..8d429932b
--- /dev/null
+++ b/sdk/tests/native-assets.test.ts
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file native-assets.test.ts
+ * @brief The native asset channel (Stage B): the SAME `Assets` class + loaders
+ * the web build uses, over the native core. A mock host scope stands in
+ * for the QuickJS globals (es_createTexture / es_releaseTexture /
+ * es_getTextureDimensions) and a mock NativeBridge decodes images, so
+ * `Assets.loadTexture` flows end-to-end — TextureLoader -> pixel decode ->
+ * native ResourceManager createTextureFromBytes — with no wasm module,
+ * headless.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createNativeApp } from '../src/ecs/nativeRuntime';
+import { createNativeResourceManager } from '../src/ecs/nativeResourceManager';
+import { Assets } from '../src/asset/AssetPlugin';
+import { shutdownResourceManager } from '../src/resourceManager';
+import { setPlatform } from '../src/platform/base';
+import type { NativeBridge } from '../src/platform/native/bridge';
+
+/** A mock native ResourceManager scope: a Map-backed texture pool addressed by
+ * handle, exposed through the es_* host globals the SDK's native RM binds to. */
+function makeTextureScope() {
+ const textures = new Map<number, { width: number; height: number; pixels: Uint8Array; format: number; flip: boolean }>();
+ let nextHandle = 1;
+ const createSpy = vi.fn(
+ (width: number, height: number, pixels: Uint8Array, format: number, flip: boolean) => {
+ const handle = nextHandle++;
+ textures.set(handle, { width, height, pixels, format, flip });
+ return handle;
+ },
+ );
+ const releaseSpy = vi.fn((handle: number) => { textures.delete(handle); });
+ const scope: Record<string, unknown> = {
+ es_createTexture: createSpy,
+ es_releaseTexture: releaseSpy,
+ es_getTextureDimensions: (handle: number) => {
+ const t = textures.get(handle);
+ return t ? { width: t.width, height: t.height } : null;
+ },
+ };
+ return { scope, textures, createSpy, releaseSpy };
+}
+
+/** RGBA pixels for a solid w×h image (top-first), matching loadImagePixels. */
+function solidImage(width: number, height: number, r = 255, g = 128, b = 64) {
+ const pixels = new Uint8Array(width * height * 4);
+ for (let i = 0; i < pixels.length; i += 4) {
+ pixels[i] = r; pixels[i + 1] = g; pixels[i + 2] = b; pixels[i + 3] = 255;
+ }
+ return { width, height, pixels };
+}
+
+/** A NativeBridge that decodes a known image path; other calls are stubs. */
+function makeBridge(images: Record<string, { width: number; height: number; pixels: Uint8Array }>) {
+ const bridge: NativeBridge = {
+ readFile: async () => new ArrayBuffer(0),
+ fileExists: async (p) => p in images,
+ fetch: async () => ({ ok: false, status: 404 }),
+ loadImagePixels: async (path) => {
+ const img = images[path];
+ if (!img) throw new Error(`no image: ${path}`);
+ return img;
+ },
+ getStorageItem: () => null,
+ setStorageItem: () => {},
+ removeStorageItem: () => {},
+ storageKeys: () => [],
+ registerInput: () => () => {},
+ devicePixelRatio: () => 1,
+ };
+ return bridge;
+}
+
+afterEach(() => {
+ shutdownResourceManager();
+ // Drop the native platform this suite installed so it can't leak into others.
+ setPlatform(null as never);
+});
+
+describe('createNativeResourceManager', () => {
+ it('uploads bytes through es_createTexture and reads dims / releases', () => {
+ const { scope, createSpy, releaseSpy } = makeTextureScope();
+ const rm = createNativeResourceManager(scope);
+
+ const px = new Uint8Array([1, 2, 3, 4]);
+ const handle = rm.createTextureFromBytes!(1, 1, px, 1, true);
+ expect(handle).toBe(1);
+ expect(createSpy).toHaveBeenCalledWith(1, 1, px, 1, true, undefined, undefined);
+ expect(rm.getTextureDimensions(handle)).toEqual({ width: 1, height: 1 });
+
+ rm.releaseTexture(handle);
+ expect(releaseSpy).toHaveBeenCalledWith(handle);
+ expect(rm.getTextureDimensions(handle)).toBeNull();
+ });
+
+ it('fails loud on the wasm/GL-only surface (no heap or GL on native)', () => {
+ const rm = createNativeResourceManager({});
+ expect(() => rm.createTexture(1, 1, 0, 4, 1, true)).toThrow(/not supported/);
+ expect(() => rm.registerExternalTexture(0, 1, 1)).toThrow(/not supported/);
+ });
+});
+
+describe('native Assets.loadTexture', () => {
+ it('decodes through the bridge and uploads via the native ResourceManager', async () => {
+ const { scope, createSpy, releaseSpy } = makeTextureScope();
+ const bridge = makeBridge({ 'logo.png': solidImage(4, 2) });
+ const app = createNativeApp(bridge, scope);
+ await app.tick(0); // finish plugin builds + install platform
+
+ const assets = app.getResource(Assets);
+ const tex = await assets.loadTexture('logo.png');
+
+ // A real handle from the native pool, with the decoded dimensions.
+ expect(tex.handle).toBe(1);
+ expect(tex.width).toBe(4);
+ expect(tex.height).toBe(2);
+
+ // The bytes reached es_createTexture: 4×2 RGBA, format 1 (gamma), flip=true.
+ expect(createSpy).toHaveBeenCalledTimes(1);
+ const [w, h, pixels, format, flip] = createSpy.mock.calls[0];
+ expect([w, h, format, flip]).toEqual([4, 2, 1, true]);
+ expect((pixels as Uint8Array).length).toBe(4 * 2 * 4);
+
+ // A second load hits the cache — no second upload.
+ const again = await assets.loadTexture('logo.png');
+ expect(again.handle).toBe(1);
+ expect(createSpy).toHaveBeenCalledTimes(1);
+
+ // Releasing both references frees the native texture (no residency budget).
+ assets.releaseTexture('logo.png');
+ expect(releaseSpy).not.toHaveBeenCalled(); // still one reference
+ assets.releaseTexture('logo.png');
+ expect(releaseSpy).toHaveBeenCalledWith(1);
+ });
+});