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(render): a lost context stops leaving its objects behind

esengine9694061a22ba
diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjs
index eef28d723..77351487b 100644
--- a/desktop/scripts/headless-verify.mjs
+++ b/desktop/scripts/headless-verify.mjs
@@ -113,7 +113,15 @@ function finish(result, server) {
&& (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;
+ // Objects the dead context minted that nobody released — visible only across
+ // rounds. From the SECOND, so the first recovery's one-off costs are not read
+ // as a slope. Per table per round; unheld, buffers alone grew by 18.
+ const rounds = dl?.rounds ?? [];
+ const growthOk = rounds.length < 3 || ((first, last, spans) =>
+ ['programs', 'buffers', 'textures', 'vaos', 'framebuffers']
+ .every((k) => (last.tables[k] - first.tables[k]) <= spans * 6)
+ )(rounds[1], rounds[rounds.length - 1], rounds.length - 2);
+ const deviceLossOk = lossSeen && cameBack && drivenSteps && growthOk;
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) &&
diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cpp
index 4e8df043a..25125a571 100644
--- a/src/esengine/core/EstellaContext.cpp
+++ b/src/esengine/core/EstellaContext.cpp
@@ -161,8 +161,14 @@ void EstellaContext::initSubsystems(Unique<GfxDevice> gfxDevice) {
// The one place a device loss becomes visible. Logged whether or not
// anything above the engine is listening: a loss nobody recorded is the
// black screen with no explanation.
- gfxDevicePtr->setDeviceLostHandler([](const GfxDeviceLostInfo& info) {
+ gfxDevicePtr->setDeviceLostHandler([this](const GfxDeviceLostInfo& info) {
ES_LOG_ERROR("{}", gfxFormatDeviceLost(info));
+ // While the dead device is still current: recompile() clears the handles
+ // during the REBUILD, where releasing an id would hand a new context an
+ // old one's object — so a wrapper per program per loss was never freed.
+ if (auto* resources = services_.getService<resource::ResourceManager>()) {
+ resources->releaseLostGpuShaders();
+ }
});
services_.registerOwned<GfxDevice>(std::move(gfxDevice));
diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cpp
index 4df65aed8..a2ea84dbe 100644
--- a/src/esengine/renderer/rhi/GLDevice.cpp
+++ b/src/esengine/renderer/rhi/GLDevice.cpp
@@ -282,6 +282,35 @@ void GLDevice::captureDeviceIdentity() {
getString(GfxStringName::Version));
}
+void GLDevice::onDeviceLost() {
+#ifdef __EMSCRIPTEN__
+ // Only where the context is CONFIRMED gone: on a lost one these are silent
+ // no-ops that still free the host's wrapper — its tables are global, so a
+ // dead context otherwise leaks every id it minted. On a live one they delete.
+ const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
+ if (ctx == 0 || !emscripten_is_webgl_context_lost(ctx)) return;
+
+ for (const auto& [id, meta] : buffer_meta_) {
+ GLuint name = id;
+ glDeleteBuffers(1, &name);
+ }
+ for (const auto& [id, format] : texture_formats_) {
+ GLuint name = id;
+ glDeleteTextures(1, &name);
+ }
+ for (const auto& [id, textures] : framebuffer_textures_) {
+ GLuint name = id;
+ glDeleteFramebuffers(1, &name);
+ }
+ for (const LayoutRecord& rec : layouts_) {
+ if (rec.vao) {
+ GLuint name = rec.vao;
+ glDeleteVertexArrays(1, &name);
+ }
+ }
+#endif
+}
+
bool GLDevice::recreateDevice() {
#ifdef __EMSCRIPTEN__
// There is no device to build: the browser restores the context on the same
diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hpp
index 9e235d1e1..1a1200882 100644
--- a/src/esengine/renderer/rhi/GLDevice.hpp
+++ b/src/esengine/renderer/rhi/GLDevice.hpp
@@ -44,6 +44,7 @@ public:
protected:
void captureDeviceIdentity() override;
bool recreateDevice() override;
+ void onDeviceLost() override;
public:
diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hpp
index 3dd667285..829b4532f 100644
--- a/src/esengine/renderer/rhi/GfxDevice.hpp
+++ b/src/esengine/renderer/rhi/GfxDevice.hpp
@@ -640,10 +640,20 @@ protected:
device_info_.message = std::move(message);
device_info_.context = std::move(context);
device_info_.frame = device_frame_;
+ onDeviceLost();
if (device_lost_handler_) device_lost_handler_(device_info_);
return true;
}
+ /**
+ * @brief Release what only this backend can name, while the dead device is
+ * still the current one.
+ * @details The window matters: on a lost device these releases are silent
+ * no-ops, whereas after the rebuild the same calls hand a NEW
+ * device objects belonging to the old one.
+ */
+ virtual void onDeviceLost() {}
+
private:
GfxDeviceStatus device_status_ = GfxDeviceStatus::Live;
GfxDeviceIdentity identity_;
diff --git a/src/esengine/renderer/rhi/Shader.cpp b/src/esengine/renderer/rhi/Shader.cpp
index 9cff405a1..172b74305 100644
--- a/src/esengine/renderer/rhi/Shader.cpp
+++ b/src/esengine/renderer/rhi/Shader.cpp
@@ -147,6 +147,11 @@ void Shader::unbind() const {
if (device_) device_->useProgram(ShaderHandle::Invalid);
}
+void Shader::releaseProgram() {
+ if (device_ && program_ != ShaderHandle::Invalid) device_->deleteProgram(program_);
+ program_ = ShaderHandle::Invalid;
+}
+
bool Shader::recompile() {
if (!device_ || vertexSource_.empty()) return false;
// Copied out first: compile() assigns these members from its arguments, and
diff --git a/src/esengine/renderer/rhi/Shader.hpp b/src/esengine/renderer/rhi/Shader.hpp
index 3b8747217..74bddda4a 100644
--- a/src/esengine/renderer/rhi/Shader.hpp
+++ b/src/esengine/renderer/rhi/Shader.hpp
@@ -249,6 +249,11 @@ public:
/// device that held it went away. The handle naming this Shader is unchanged.
bool recompile();
+ /// Frees the GPU program while keeping everything needed to rebuild it.
+ /// Called while the dead device is still current — recompile() only clears
+ /// the handle, which strands the driver object in the host's table.
+ void releaseProgram();
+
private:
/**
* @brief Compiles and links shader sources
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index cc86f08af..67ad8f12a 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -278,6 +278,15 @@ u32 ResourceManager::recreateGpuShaders() {
return rebuilt;
}
+u32 ResourceManager::releaseLostGpuShaders() {
+ u32 released = 0;
+ shaders_.forEachAlive([&](ShaderHandle, Shader& shader) {
+ shader.releaseProgram();
+ ++released;
+ });
+ return released;
+}
+
void ResourceManager::invalidateGpuTextures(::esengine::TextureHandle placeholder) {
awaitingReupload_.clear();
textures_.forEachAlive([&](TextureHandle handle, Texture& texture) {
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index 713500ae1..2e7a19fb2 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -309,6 +309,15 @@ public:
*/
u32 recreateGpuShaders();
+ /**
+ * @brief Frees every shader's GPU program, keeping the sources to rebuild.
+ * @details Belongs to the moment of the LOSS, not the rebuild: the ids name
+ * a context about to stop existing, and a host keeps a wrapper for
+ * each one until something releases it.
+ * @return How many were released.
+ */
+ u32 releaseLostGpuShaders();
+
void invalidateGpuTextures(::esengine::TextureHandle placeholder);
/**
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index f22404045..c1e64c8a2 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -117,9 +117,10 @@ export const SCENES = [
// 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, 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]}]" } },
+ // happens FOUR times — backgrounding a tab is not a one-off, a recovery that
+ // works once and never again passes any single-round check, and it takes
+ // three rounds to measure whether the host's object tables are growing.
+ { id: "device-loss-auto", tier: "pr", env: { ESTELLA_VERIFY_LOSS_ROUNDS: "4", 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);