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(assets): a game that loses its GPU comes back on its own
esengine93a8bf0db9eb
diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjsindex 30942485d..a872884ff 100644--- a/desktop/scripts/headless-verify.mjs+++ b/desktop/scripts/headless-verify.mjs@@ -100,13 +100,16 @@ function serveDist() {}function finish(result, server) {- // A loss run asserts the whole cycle: the loss is seen and reported, the- // browser gives the context back, and the engine rebuilds to Recovering.+ // Both modes assert the loss was seen and reported and the device ended Live+ // with nothing left on the placeholder. Only the driven mode asserts the steps+ // between: the auto mode has none, which is the point of it.const dl = result.deviceLoss;- const deviceLossOk = !dl || (dl.supported && dl.statusAfterLoss === 1 &&- (dl.reportAfterLoss?.length ?? 0) > 0 && dl.glLostAfterRestore === false &&- dl.recovered === true && dl.statusAfterRecover === 2 &&- dl.fullRecovered === true && dl.statusAfterFull === 0);+ const lossSeen = !dl || (dl.supported && dl.statusAfterLoss === 1+ && (dl.reportAfterLoss?.length ?? 0) > 0);+ const cameBack = !dl || (dl.statusAfterFull === 0 && (dl.awaitingAfterFull?.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;const renderedOk = result.capture?.rendered ?? false;const ok = result.ok && renderedOk && (result.expect?.ok ?? true) &&(result.resize?.ok ?? true) && (result.preview?.ok ?? true) && (result.grid?.ok ?? true) &&@@ -226,6 +229,42 @@ app.whenReady().then(async () => {await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);}+ // ESTELLA_VERIFY_DEVICE_LOSS=auto is the player's case: the GPU goes away,+ // the browser hands a context back, and NOTHING here asks for a recovery.+ // Only frames pass. What comes back has to come back on the engine's own.+ if (process.env.ESTELLA_VERIFY_DEVICE_LOSS === 'auto') {+ 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;++ 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();++ // 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));++ for (let i = 0; i < 200 && d.status() !== 0; i++) {+ await api.step(1, 1 / 60);+ await new Promise((r) => setTimeout(r, 16));+ }+ out.statusAfterFull = d.status();+ out.awaitingAfterFull = d.awaiting();+ out.recovered = out.statusAfterFull === 0;+ out.fullRecovered = out.recovered;+ await api.step(${STEPS}, 1 / 60);+ out.drawCallsAfterRecover = api.getStats ? api.getStats().drawCalls : -1;+ return out;+ })()`);+ }+// ESTELLA_VERIFY_DEVICE_LOSS=1 takes the GPU away for real (WEBGL_lose_context)// and drives the whole cycle, because everything downstream of a loss is// reachable only by actually losing one.diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.tsindex d7d443c6f..c5ec475af 100644--- a/sdk/src/asset/AssetPlugin.ts+++ b/sdk/src/asset/AssetPlugin.ts@@ -1,7 +1,9 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { App, Plugin } from '../app/app';-import { defineResource } from '../ecs/resource';+import { defineResource, Time } from '../ecs/resource';+import { Schedule, defineSystem } from '../ecs/system';+import { DeviceStatus, getDeviceStatus } from '../render/renderer';import { Assets as AssetsClass } from './Assets';import { HttpBackend } from './Backend';import { transcoderFromModule, type BasisWasmModule } from './basisTranscoder';@@ -76,7 +78,59 @@ export class AssetPlugin implements Plugin {app.world.onDespawn((entity) => counter.removeAllRefsForEntity(entity));app.insertResource(Assets, assets);+ this.driveDeviceRecovery_(app, assets);+ }++ /**+ * Recovers the renderer after a device loss, which nothing did: the path+ * existed end to end with no caller but a test probe, so a shipped game that+ * lost its GPU stayed lost. Timed off UNSCALED delta — a paused game still+ * has to come back — and backed off, since each attempt re-fetches content.+ */+ private driveDeviceRecovery_(app: App, assets: AssetsClass): void {+ let inFlight = false;+ let waited = 0;+ let backoff = 0;+ let downtime = 0;++ app.addSystemToSchedule(Schedule.First, defineSystem([], () => {+ const status = getDeviceStatus();+ if (status === DeviceStatus.Live || status === DeviceStatus.Dead) {+ backoff = 0;+ waited = 0;+ downtime = 0;+ return;+ }+ const dt = app.getResource(Time)?.unscaledDelta ?? 0;+ downtime += dt;+ if (inFlight) return;+ waited += dt;+ if (waited < backoff) return;++ waited = 0;+ inFlight = true;+ const lostFor = downtime;+ void assets.recoverFromDeviceLoss()+ .then((whole) => {+ if (whole) {+ log.info('asset', `Device recovered after ${lostFor.toFixed(1)}s`);+ backoff = 0;+ return;+ }+ backoff = Math.min(backoff ? backoff * 2 : RECOVERY_RETRY_S, RECOVERY_RETRY_MAX_S);+ })+ .catch((e) => {+ log.warn('asset', 'Device recovery threw; will retry', e);+ backoff = Math.min(backoff ? backoff * 2 : RECOVERY_RETRY_S, RECOVERY_RETRY_MAX_S);+ })+ .finally(() => { inFlight = false; });+ }));}}+/** First wait after a recovery attempt comes back incomplete, in seconds. */+const RECOVERY_RETRY_S = 0.25;+/** Ceiling for that wait: a context can take a while, but not minutes. */+const RECOVERY_RETRY_MAX_S = 5;+export const assetPlugin = new AssetPlugin();diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 9818007fb..63ed9f973 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -116,6 +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]}]" } },];const rank = (tier) => TIERS.indexOf(tier);