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.

fix(assets): the second device loss recovers too

esengineb000cb967e01
diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjs
index a872884ff..eef28d723 100644
--- a/desktop/scripts/headless-verify.mjs
+++ b/desktop/scripts/headless-verify.mjs
@@ -42,6 +42,7 @@ const MANIFEST = process.env.ESTELLA_VERIFY_MANIFEST ?? '/scenes/sprite-renderin
const W = Number(process.env.ESTELLA_VERIFY_W) || 640;
const H = Number(process.env.ESTELLA_VERIFY_H) || 480;
const STEPS = Number(process.env.ESTELLA_VERIFY_STEPS) || 30;
+const ROUNDS = Number(process.env.ESTELLA_VERIFY_LOSS_ROUNDS) || 1;
// ESTELLA_VERIFY_BACKEND=webgpu runs the same scene + assertions on the WebGPU
// backend (needs a real adapter — local runs; CI runners have none).
const BACKEND = process.env.ESTELLA_VERIFY_BACKEND === 'webgpu' ? 'webgpu' : 'webgl2';
@@ -106,7 +107,10 @@ function finish(result, server) {
const dl = result.deviceLoss;
const lossSeen = !dl || (dl.supported && dl.statusAfterLoss === 1
&& (dl.reportAfterLoss?.length ?? 0) > 0);
- const cameBack = !dl || (dl.statusAfterFull === 0 && (dl.awaitingAfterFull?.length ?? 0) === 0);
+ // Every round, not just the last: a recovery can work once and never again,
+ // which is what a single round reports as a pass.
+ const cameBack = !dl || ((dl.statusAfterFull === 0 && (dl.awaitingAfterFull?.length ?? 0) === 0)
+ && (dl.rounds ?? []).every((r) => r.status === 0 && (r.awaiting?.length ?? 0) === 0));
const drivenSteps = !dl || dl.mode === 'auto' || (dl.glLostAfterRestore === false
&& dl.recovered === true && dl.statusAfterRecover === 2 && dl.fullRecovered === true);
const deviceLossOk = lossSeen && cameBack && drivenSteps;
@@ -236,29 +240,36 @@ app.whenReady().then(async () => {
deviceLoss = await exec(`(async () => {
const d = window.__estellaHeadless.device;
const api = window.__estellaHeadless.api;
- const out = { supported: d.lose(), mode: 'auto' };
- if (!out.supported) return out;
+ // Rounds, because losing a context is not a one-off: backgrounding a
+ // tab does it again and again, and what a single round cannot show is
+ // whether the engine hands the last one's objects back.
+ const out = { mode: 'auto', supported: true, rounds: [], tablesBefore: d.glTables() };
+ for (let r = 0; r < ${ROUNDS}; r++) {
+ if (!d.lose()) return { ...out, supported: false };
- for (let i = 0; i < 30 && d.status() === 0; i++) {
- await api.step(1, 1 / 60);
- await new Promise((r) => setTimeout(r, 50));
- }
- out.statusAfterLoss = d.status();
- out.reportAfterLoss = d.report();
+ for (let i = 0; i < 30 && d.status() === 0; i++) {
+ await api.step(1, 1 / 60);
+ await new Promise((r2) => setTimeout(r2, 50));
+ }
+ out.statusAfterLoss = d.status();
+ out.reportAfterLoss = d.report();
- // Standing in for the browser, not for the engine: a page gets its
- // context back on its own, and there is no such event to wait for here.
- out.restoreCalled = d.restore();
- await new Promise((r) => setTimeout(r, 200));
+ // Standing in for the browser, not for the engine: a page gets its
+ // context back on its own, and there is no such event to wait for.
+ out.restoreCalled = d.restore();
+ await new Promise((r2) => setTimeout(r2, 200));
- for (let i = 0; i < 200 && d.status() !== 0; i++) {
- await api.step(1, 1 / 60);
- await new Promise((r) => setTimeout(r, 16));
+ for (let i = 0; i < 200 && d.status() !== 0; i++) {
+ await api.step(1, 1 / 60);
+ await new Promise((r2) => setTimeout(r2, 16));
+ }
+ out.rounds.push({ status: d.status(), tables: d.glTables(), awaiting: d.awaiting() });
}
out.statusAfterFull = d.status();
out.awaitingAfterFull = d.awaiting();
out.recovered = out.statusAfterFull === 0;
out.fullRecovered = out.recovered;
+ out.tablesAfterFull = d.glTables();
await api.step(${STEPS}, 1 / 60);
out.drawCallsAfterRecover = api.getStats ? api.getStats().drawCalls : -1;
return out;
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index c0f86641e..80821d27b 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -144,6 +144,7 @@ valid: (entity: Entity) => boolean
## CppResourceManager — interface @experimental
```
acquireTextureByPath: (path: string) => number
+adoptTextureContent: ((target: number, source: number) => boolean) | undefined
createCompressedTexture: ((width: number, height: number, format: number, dataPtr: number, dataLen: number, mipLevels: number) => number) | undefined
createLabelAtlasFont: (textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number) => number
createShader: (vertSrc: string, fragSrc: string) => number
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 031f24b4c..61efd7d86 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -385,40 +385,34 @@ export class Assets {
}
/**
- * Re-uploads every cached texture behind the handle it already has.
+ * Re-uploads every texture the engine says is still the placeholder.
*
- * The GPU objects died with the device; the handles did not. The load path
- * runs again for its BYTES and the result is retargeted onto the original
- * handle — reusing it keeps this one sweep, not one per upload path.
+ * Driven by that list, not by this cache, which only held the subset this
+ * layer loaded — the difference between the two is exactly what never came
+ * back. The bytes arrive under no path of their own and are then moved onto
+ * the handle that has one, so the pool ends with the records it began with.
*/
async reuploadTexturesAfterDeviceLoss(): Promise<number> {
const rm = requireResourceManager();
- if (!rm.retargetExternalTexture) return 0;
+ if (!rm.adoptTextureContent) return 0;
let restored = 0;
- for (const [key, previous] of [...this.textureCache_.entries()]) {
- const cut = key.lastIndexOf(':');
- if (cut < 0) continue;
- const path = key.slice(0, cut);
- const flip = key.slice(cut + 1) === 'f';
-
- // Removed so the load is a real one: the cached entry names a GPU
- // object that no longer exists.
- this.textureCache_.delete(key);
+ for (const { handle, path } of this.texturesAwaitingReupload()) {
+ // Not this layer's to restore — a render target, a glyph atlas. Its
+ // own subsystem re-creates it, or it stays on the placeholder.
+ if (!path) continue;
+ const cut = path.lastIndexOf(':');
+ const ref = cut < 0 ? path : path.slice(0, cut);
+ const flip = cut < 0 || path.slice(cut + 1) === 'f';
try {
- const fresh = await this.loadTextureVariant_(path, flip);
- const glId = rm.getTextureGLId(fresh.handle);
- if (glId && rm.retargetExternalTexture(previous.handle, glId, fresh.width, fresh.height)) {
- restored++;
- }
- // The fresh POOL entry is scaffolding; its GPU object now belongs
- // to the original handle, and external textures are not owned, so
- // releasing the record does not take it away.
- if (fresh.handle !== previous.handle) rm.releaseTexture(fresh.handle);
+ const fresh = await this.textureLoader_.loadDetached(
+ this.resolveLoadPath_(ref), this.getLoadContext_(), flip,
+ this.textureImportResolver_?.(ref));
+ if (rm.adoptTextureContent(handle, fresh.handle)) restored++;
+ rm.releaseTexture(fresh.handle);
} catch (e) {
- log.warn('assets', `Device recovery: re-upload failed for ${path}`, e);
+ log.warn('assets', `Device recovery: re-upload failed for ${ref}`, e);
}
- this.textureCache_.set(key, previous);
}
log.info('assets', `Device recovery: ${restored} texture(s) re-uploaded`);
return restored;
diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.ts
index aaabaa9c8..a856a3c91 100644
--- a/sdk/src/asset/loaders/TextureLoader.ts
+++ b/sdk/src/asset/loaders/TextureLoader.ts
@@ -167,6 +167,18 @@ export class TextureLoader implements AssetLoader<TextureResult> {
rm.releaseTexture(asset.handle);
}
+ /**
+ * Loads the bytes onto the GPU WITHOUT claiming the path — what a re-upload
+ * after a device loss wants, since the identity belongs to the handle being
+ * recovered. Claiming it leaves the pool holding two records, and the loser
+ * is swept up by the next loss with nobody able to re-upload it.
+ */
+ async loadDetached(
+ path: string, ctx: LoadContext, flip: boolean, settings?: TextureImportSettings,
+ ): Promise<TextureResult> {
+ return this.decodeAndUpload_(path, ctx, flip, settings);
+ }
+
private async loadWithFlip(
path: string, ctx: LoadContext, flip: boolean, settings?: TextureImportSettings,
): Promise<TextureResult> {
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index dcc42b46a..c742c6dba 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -82,6 +82,12 @@ export interface CppResourceManager {
* Optional: absent on an older wasm build.
*/
texturesAwaitingReupload?(): string;
+ /**
+ * Move a freshly loaded texture's GPU object onto an existing handle, so a
+ * re-upload ends with one pool record instead of leaving the loader's
+ * behind. Optional: absent on an older wasm build.
+ */
+ adoptTextureContent?(target: number, source: number): boolean;
getTextureGLId(handle: number): number;
getTextureDimensions(handle: number): { width: number; height: number } | null;
releaseTexture(handle: number): void;
diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cpp
index 6658a6575..caca39c76 100644
--- a/src/esengine/bindings/ResourceManagerBindings.cpp
+++ b/src/esengine/bindings/ResourceManagerBindings.cpp
@@ -131,6 +131,10 @@ bool rm_retargetExternalTexture(resource::ResourceManager& rm, u32 handle,
return rm.retargetExternalTexture(resource::TextureHandle(handle), glTextureId, width, height);
}
+bool rm_adoptTextureContent(resource::ResourceManager& rm, u32 target, u32 source) {
+ return rm.adoptTextureContent(resource::TextureHandle(target), resource::TextureHandle(source));
+}
+
std::string rm_texturesAwaitingReupload(resource::ResourceManager& rm) {
// One crossing: a loss parks every texture at once, so a call per handle is
// a call per texture. A blank path is one no asset layer can bring back —
diff --git a/src/esengine/bindings/ResourceManagerBindings.hpp b/src/esengine/bindings/ResourceManagerBindings.hpp
index 2e90b1774..08744e1f3 100644
--- a/src/esengine/bindings/ResourceManagerBindings.hpp
+++ b/src/esengine/bindings/ResourceManagerBindings.hpp
@@ -41,6 +41,9 @@ bool rm_retargetExternalTexture(resource::ResourceManager& rm, u32 handle,
/** @brief The textures still parked on the placeholder, as `handle|path` lines. */
std::string rm_texturesAwaitingReupload(resource::ResourceManager& rm);
+/** @brief Moves a freshly loaded texture's GPU object onto an existing handle. */
+bool rm_adoptTextureContent(resource::ResourceManager& rm, u32 target, u32 source);
+
u32 rm_registerExternalTextureSized(resource::ResourceManager& rm, u32 glTextureId,
u32 width, u32 height, u32 bytes);
void rm_releaseTexture(resource::ResourceManager& rm, u32 handleId);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 84981a80a..ff80a7ac2 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -458,6 +458,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
.function("registerExternalTextureSized", &esengine::rm_registerExternalTextureSized)
.function("retargetExternalTexture", &esengine::rm_retargetExternalTexture)
.function("texturesAwaitingReupload", &esengine::rm_texturesAwaitingReupload)
+ .function("adoptTextureContent", &esengine::rm_adoptTextureContent)
.function("releaseTexture", &esengine::rm_releaseTexture)
.function("getTextureRefCount", &esengine::rm_getTextureRefCount)
.function("releaseShader", &esengine::rm_releaseShader)
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index cf15c1ec5..cc86f08af 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -313,6 +313,27 @@ bool ResourceManager::retargetExternalTexture(TextureHandle handle, u32 glTextur
return true;
}
+bool ResourceManager::adoptTextureContent(TextureHandle target, TextureHandle source) {
+ Texture* to = textures_.get(target);
+ Texture* from = textures_.get(source);
+ if (!to || !from) return false;
+
+ // Ownership moves with the object: the source record is about to be released,
+ // and a borrowed GPU texture whose owner is freed is a dangling bind.
+ const ::esengine::TextureHandle gpu = from->handle();
+ from->retarget(::esengine::TextureHandle::Invalid, /*owns=*/false);
+ to->retarget(gpu, /*owns=*/true);
+
+ for (usize i = 0; i < awaitingReupload_.size(); ++i) {
+ if (awaitingReupload_[i] == target) {
+ awaitingReupload_[i] = awaitingReupload_.back();
+ awaitingReupload_.pop_back();
+ break;
+ }
+ }
+ return true;
+}
+
std::vector<TextureHandle> ResourceManager::texturesAwaitingReupload() const {
return awaitingReupload_;
}
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index 22cee301f..713500ae1 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -317,6 +317,16 @@ public:
*/
bool retargetExternalTexture(TextureHandle handle, u32 glTextureId, u32 width, u32 height);
+ /**
+ * @brief Moves a freshly loaded texture's GPU object onto an existing handle.
+ * @details A re-upload has to end with ONE record. Getting bytes onto the GPU
+ * creates a second, and leaving it in the pool deposits an orphan
+ * under the same path — swept up by the next loss, re-uploadable by
+ * nobody, so the SECOND loss never finished recovering.
+ * @return False if either handle names no live texture.
+ */
+ bool adoptTextureContent(TextureHandle target, TextureHandle source);
+
/** @brief Texture handles that were invalidated and not yet re-uploaded. */
std::vector<TextureHandle> texturesAwaitingReupload() const;
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index 63ed9f973..f22404045 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -116,10 +116,10 @@ export const SCENES = [
// sample the atlas, so they fail unless the content came back. A vertex-colour
// scene passed with the re-upload deleted. No webgpu — no GL extension there.
{ id: "device-loss", tier: "pr", env: { ESTELLA_VERIFY_DEVICE_LOSS: "1", ESTELLA_VERIFY_SCENE: "/scenes/tilemap-flip.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/tilemap-flip.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.36,\"rgb\":[255,0,0]},{\"x\":0.60,\"y\":0.36,\"rgb\":[0,255,0]},{\"x\":0.40,\"y\":0.58,\"rgb\":[0,0,255]},{\"x\":0.60,\"y\":0.58,\"rgb\":[255,255,0]}]" } },
- // The player's case: nothing asks for the recovery, only frames pass. The
- // scene above proves the path works when driven; this one proves a shipped
- // game reaches it, which is the part that was missing for every caller.
- { id: "device-loss-auto", tier: "pr", env: { ESTELLA_VERIFY_DEVICE_LOSS: "auto", ESTELLA_VERIFY_SCENE: "/scenes/tilemap-flip.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/tilemap-flip.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.36,\"rgb\":[255,0,0]},{\"x\":0.60,\"y\":0.36,\"rgb\":[0,255,0]},{\"x\":0.40,\"y\":0.58,\"rgb\":[0,0,255]},{\"x\":0.60,\"y\":0.58,\"rgb\":[255,255,0]}]" } },
+ // The player's case: nothing asks for the recovery, only frames pass, and it
+ // happens THREE times — backgrounding a tab is not a one-off, and a recovery
+ // that works once and never again passes any single-round check.
+ { id: "device-loss-auto", tier: "pr", env: { ESTELLA_VERIFY_LOSS_ROUNDS: "3", ESTELLA_VERIFY_DEVICE_LOSS: "auto", ESTELLA_VERIFY_SCENE: "/scenes/tilemap-flip.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/tilemap-flip.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.36,\"rgb\":[255,0,0]},{\"x\":0.60,\"y\":0.36,\"rgb\":[0,255,0]},{\"x\":0.40,\"y\":0.58,\"rgb\":[0,0,255]},{\"x\":0.60,\"y\":0.58,\"rgb\":[255,255,0]}]" } },
];
const rank = (tier) => TIERS.indexOf(tier);