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(rhi): the GL backend can take its context back

esengined2b5f8cab1db
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 44ca64d30..4e0866ed6 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -289,7 +289,7 @@ void RenderFrame::flush() {
// The device can still die between begin() and here — a GL error check, a
// spontaneous WebGPU callback. Marked flushed above first, so end() does not
// come back for a second attempt at a frame that has nowhere to go.
- if (!device_.isDeviceLive()) return;
+ if (!device_.isDeviceUsable()) return;
// Drop any pipeline a prior phase left bound, so the first draw re-applies its state.
device_.invalidatePipelineCache();
@@ -448,7 +448,7 @@ void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {
void RenderFrame::renderToTarget(ecs::Registry& registry, const glm::mat4& viewProjection, u32 w, u32 h) {
if (w == 0 || h == 0) return;
- if (!device_.isDeviceLive()) return;
+ if (!device_.isDeviceUsable()) return;
if (preview_rt_ == 0) {
preview_rt_ = target_manager_.create(w, h, /*depth=*/false, /*linearFilter=*/false);
diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cpp
index 94b46038a..b7be7ca1b 100644
--- a/src/esengine/renderer/rhi/GLDevice.cpp
+++ b/src/esengine/renderer/rhi/GLDevice.cpp
@@ -252,11 +252,72 @@ void GLDevice::init() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- // Ask who we are while the answer still exists: glGetString returns null on a
- // lost context, so a report assembled after the loss would name no driver.
+ captureDeviceIdentity();
+ ES_LOG_DEBUG("GLDevice initialized");
+}
+
+void GLDevice::captureDeviceIdentity() {
+ // Asked while the answer still exists: glGetString returns null on a lost
+ // context, so a report assembled after the loss would name no driver.
setDeviceIdentity("WebGL2", getString(GfxStringName::Vendor),
getString(GfxStringName::Renderer), getString(GfxStringName::Version));
- ES_LOG_DEBUG("GLDevice initialized");
+}
+
+bool GLDevice::recreateDevice() {
+#ifdef __EMSCRIPTEN__
+ // There is no device to build: the browser restores the context on the same
+ // handle, and until it does there is nothing to do but wait.
+ if (emscripten_is_webgl_context_lost(0)) return false;
+#endif
+
+ // Every GL object the old context held is gone. Layout DESCRIPTORS stay:
+ // dropping the vao id routes them back through prepareVertexState's lazy
+ // create, so every VertexLayoutHandle handed out already stays valid.
+ for (LayoutRecord& rec : layouts_) {
+ rec.vao = 0;
+ rec.configured = false;
+ rec.bakedIbo = 0;
+ for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) {
+ rec.bakedVbo[slot] = 0;
+ rec.bakedOffset[slot] = 0;
+ }
+ }
+
+ // Objects whose ids are dead. The engine's own resources come back by
+ // re-running the subsystem init that created them; user content comes back
+ // through the asset layer. Neither is this backend's to rebuild.
+ buffer_meta_.clear();
+ texture_formats_.clear();
+ framebuffer_textures_.clear();
+ readbacks_.clear();
+ live_programs_ = 0;
+
+ // Pipelines are pure GL state here, but they name programs by id, and those
+ // ids die with the context. Dropping the cache makes the next frame resolve
+ // fresh ones instead of binding a program that no longer exists.
+ pipelines_.clear();
+
+ resetStateCache();
+ init();
+ return true;
+}
+
+void GLDevice::resetStateCache() {
+ current_pipeline_ = PipelineHandle::Invalid;
+ current_stencil_mode_ = GfxStencilMode::Off;
+ current_program_ = ShaderHandle::Invalid;
+ current_blend_ = static_cast<BlendMode>(0xFF);
+ current_layout_ = VertexLayoutHandle::Invalid;
+ active_texture_unit_ = 0;
+ for (u32 i = 0; i < kTextureSlots; ++i) bound_texture_[i] = 0;
+ for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) {
+ pending_vbo_[slot] = 0;
+ pending_vbo_offset_[slot] = 0;
+ }
+ pending_ibo_ = 0;
+ bound_vao_ = 0;
+ scissor_test_ = -1;
+ timer_query_state_ = 0;
}
void GLDevice::shutdown() {
@@ -264,7 +325,7 @@ void GLDevice::shutdown() {
}
bool GLDevice::pollDeviceLost() {
- if (!isDeviceLive()) return false;
+ if (!isDeviceUsable()) return false;
#ifdef __EMSCRIPTEN__
// Asked directly rather than waited for: a `webglcontextlost` listener
// attached after the loss never fires, and a renderer that missed the event
@@ -439,7 +500,7 @@ void GLDevice::setCullFace(bool front) {
ShaderHandle GLDevice::createProgram(const GfxShaderSource& source,
const GfxAttribBinding* bindings, u32 bindingCount,
std::string* outLog, GfxShaderStage* outFailedStage) {
- if (!isDeviceLive()) {
+ if (!isDeviceUsable()) {
if (outLog) *outLog = "device lost";
return ShaderHandle::Invalid;
}
@@ -660,7 +721,7 @@ void GLDevice::uploadBufferStore(BufferHandle buffer, u32 offsetBytes, const voi
// calls whose RESULT the caller acts on; state setters are no-ops already.
BufferHandle GLDevice::createBuffer(const BufferDesc& desc, const void* initialData) {
- if (!isDeviceLive()) return BufferHandle::Invalid;
+ if (!isDeviceUsable()) return BufferHandle::Invalid;
GLuint id = 0;
glGenBuffers(1, &id);
buffer_meta_[id] = BufferMeta{desc.usage, desc.dynamic};
@@ -691,7 +752,7 @@ void GLDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {
// =============================================================================
VertexLayoutHandle GLDevice::createVertexLayout(const VertexLayoutDesc& desc) {
- if (!isDeviceLive()) return VertexLayoutHandle::Invalid;
+ if (!isDeviceUsable()) return VertexLayoutHandle::Invalid;
LayoutRecord rec;
rec.desc = desc;
rec.alive = true;
@@ -787,7 +848,7 @@ void GLDevice::uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bin
// =============================================================================
PipelineHandle GLDevice::createPipeline(const PipelineDesc& desc) {
- if (!isDeviceLive()) return PipelineHandle::Invalid;
+ if (!isDeviceUsable()) return PipelineHandle::Invalid;
for (u32 i = 0; i < pipelines_.size(); ++i) {
if (pipelines_[i] == desc) {
return static_cast<PipelineHandle>(i + 1);
@@ -867,20 +928,20 @@ void GLDevice::invalidatePipelineCache() {
// =============================================================================
void GLDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset) {
- if (!isDeviceLive()) return;
+ if (!isDeviceUsable()) return;
prepareVertexState();
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indexCount), toGLDataType(indexType),
reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)));
}
void GLDevice::drawArrays(u32 first, u32 vertexCount) {
- if (!isDeviceLive()) return;
+ if (!isDeviceUsable()) return;
prepareVertexState();
glDrawArrays(GL_TRIANGLES, static_cast<GLint>(first), static_cast<GLsizei>(vertexCount));
}
void GLDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) {
- if (!isDeviceLive()) return;
+ if (!isDeviceUsable()) return;
prepareVertexState();
glDrawElementsInstanced(GL_TRIANGLES, static_cast<GLsizei>(indexCount), toGLDataType(indexType),
reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)),
@@ -926,7 +987,7 @@ void GLDevice::evictSamplerBinding(u32 textureId) {
}
TextureHandle GLDevice::createTexture(const TextureDesc& desc, const void* pixels) {
- if (!isDeviceLive()) return TextureHandle::Invalid;
+ if (!isDeviceUsable()) return TextureHandle::Invalid;
GLuint id = 0;
glGenTextures(1, &id);
texture_formats_[id] = desc.format;
@@ -953,7 +1014,7 @@ TextureHandle GLDevice::createTexture(const TextureDesc& desc, const void* pixel
TextureHandle GLDevice::createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,
const void* data, u32 byteLength, u32 mipLevels) {
- if (!isDeviceLive()) return TextureHandle::Invalid;
+ if (!isDeviceUsable()) return TextureHandle::Invalid;
GLuint id = 0;
glGenTextures(1, &id);
texture_formats_[id] = desc.format;
@@ -988,7 +1049,7 @@ TextureHandle GLDevice::createCompressedTexture(const TextureDesc& desc, GfxComp
}
TextureHandle GLDevice::importExternalTexture(u32 nativeId, const TextureDesc& desc) {
- if (!isDeviceLive()) return TextureHandle::Invalid;
+ if (!isDeviceUsable()) return TextureHandle::Invalid;
texture_formats_[nativeId] = desc.format;
return TextureHandle{nativeId};
}
@@ -1032,7 +1093,7 @@ void GLDevice::generateMipmaps(TextureHandle texture) {
// =============================================================================
FramebufferHandle GLDevice::createFramebuffer(const FramebufferDesc& desc) {
- if (!isDeviceLive()) return FramebufferHandle::Default;
+ if (!isDeviceUsable()) return FramebufferHandle::Default;
GLuint id = 0;
glGenFramebuffers(1, &id);
glBindFramebuffer(GL_FRAMEBUFFER, id);
@@ -1125,7 +1186,7 @@ void GLDevice::endRenderPass() {
// =============================================================================
ReadbackHandle GLDevice::requestReadback(FramebufferHandle target, u32 w, u32 h) {
- if (!isDeviceLive()) return ReadbackHandle::Invalid;
+ if (!isDeviceUsable()) return ReadbackHandle::Invalid;
if (w == 0 || h == 0) return ReadbackHandle::Invalid;
std::vector<u8> pixels(static_cast<usize>(w) * h * 4);
// Called outside a pass (framebuffer 0 bound); bind the source, read, restore.
diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hpp
index b8dc98f23..9e235d1e1 100644
--- a/src/esengine/renderer/rhi/GLDevice.hpp
+++ b/src/esengine/renderer/rhi/GLDevice.hpp
@@ -41,6 +41,12 @@ public:
bool pollDeviceLost() override;
+protected:
+ void captureDeviceIdentity() override;
+ bool recreateDevice() override;
+
+public:
+
void setViewport(i32 x, i32 y, u32 w, u32 h) override;
void clearStencil(i32 value) override;
@@ -154,6 +160,11 @@ private:
void uploadBufferStore(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes, bool respec);
+ // Drops every "what is currently bound" cache. Those answers are only valid
+ // for the context that was asked; after a restore they would suppress the
+ // very binds that re-establish state.
+ void resetStateCache();
+
// Applies the current pipeline's vertex layout to the pending buffer bindings:
// the layout's lazily-created VAO is bound, and any slot whose buffer/offset
// differs from what the VAO has baked is re-pointed. WebGL2 has no explicit
diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hpp
index 6d2738c1a..1573b3aa2 100644
--- a/src/esengine/renderer/rhi/GfxDevice.hpp
+++ b/src/esengine/renderer/rhi/GfxDevice.hpp
@@ -91,9 +91,21 @@ public:
/** @brief Whether the device can be drawn to (see {@link GfxDeviceStatus}). */
GfxDeviceStatus deviceStatus() const { return device_status_; }
- /** @brief True while the device is usable — the one check submission paths make. */
+ /** @brief Strictly Live: recovered but still-refilling counts as false. */
bool isDeviceLive() const { return device_status_ == GfxDeviceStatus::Live; }
+ /**
+ * @brief Whether work may be submitted — the one check the guards make.
+ * @details True while Recovering as well as Live. A device that has been
+ * rebuilt but whose textures are still being re-uploaded must draw:
+ * refusing would leave the screen frozen for the whole reload
+ * instead of filling in as the content lands.
+ */
+ bool isDeviceUsable() const {
+ return device_status_ == GfxDeviceStatus::Live ||
+ device_status_ == GfxDeviceStatus::Recovering;
+ }
+
/** @brief The loss report, or null while the device is Live. */
const GfxDeviceLostInfo* deviceLostInfo() const {
return device_status_ == GfxDeviceStatus::Live ? nullptr : &device_info_;
@@ -111,6 +123,37 @@ public:
markDeviceLost(reason, std::move(message), std::move(context));
}
+ /**
+ * @brief Rebuilds the device and everything it can describe on its own.
+ *
+ * @details A backend rebuilds only what it fully describes: a texture's
+ * pixels were never its to keep, and shadowing all of VRAM in system
+ * memory is the alternative. Content returns through the layer that
+ * loaded it, which ends the resulting Recovering state.
+ *
+ * @return True when the device is usable again.
+ */
+ bool recoverDevice() {
+ if (device_status_ != GfxDeviceStatus::Lost) return isDeviceUsable();
+ device_status_ = GfxDeviceStatus::Recovering;
+ if (!recreateDevice()) {
+ device_status_ = GfxDeviceStatus::Lost;
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * @brief The content is back: the device is fully itself again.
+ * @details Called by the layer that re-uploaded what the backend could not.
+ */
+ void markDeviceRestored() {
+ if (device_status_ != GfxDeviceStatus::Recovering) return;
+ device_status_ = GfxDeviceStatus::Live;
+ device_info_ = GfxDeviceLostInfo{};
+ captureDeviceIdentity();
+ }
+
/**
* @brief Gives up on the device: no further recovery will be attempted.
* @details The clean end of a loss that could not be recovered from. The
@@ -140,12 +183,12 @@ public:
* frame does afterwards — passes, post-process, readbacks — is
* predicated on this having returned true, which is why it is a
* single question at the top rather than a check per submission.
- * @return True when the device is live and the frame may proceed.
+ * @return True when the frame may proceed (see {@link isDeviceUsable}).
*/
bool beginDeviceFrame() {
++device_frame_;
- if (device_status_ == GfxDeviceStatus::Live) pollDeviceLost();
- return device_status_ == GfxDeviceStatus::Live;
+ if (isDeviceUsable()) pollDeviceLost();
+ return isDeviceUsable();
}
/**
@@ -539,9 +582,22 @@ public:
protected:
/**
* @brief Records who this backend is, so a later loss report can name it.
- * @details Call from init(), while the backend still answers. Doing it at
- * loss time is too late — see {@link GfxDeviceLostInfo}.
+ * @details Called from init() while the backend still answers, and again
+ * after a recovery: a rebuilt device can be a DIFFERENT GPU, and a
+ * report naming the one that is gone sends the reader hunting the
+ * wrong hardware. Implementations call setDeviceIdentity.
*/
+ virtual void captureDeviceIdentity() {}
+
+ /**
+ * @brief Backend half of {@link recoverDevice}: rebuild the device and the
+ * resources this backend holds a full description of.
+ * @details Default: this backend cannot rebuild itself, so a loss is final.
+ * @return True when the device is usable again.
+ */
+ virtual bool recreateDevice() { return false; }
+
+ /** @brief Records the backend identity; see {@link captureDeviceIdentity}. */
void setDeviceIdentity(std::string backend, std::string vendor,
std::string renderer, std::string version) {
device_info_.backend = std::move(backend);
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 1663d42c8..e07f276ae 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -80,6 +80,10 @@ WebGPUDevice::~WebGPUDevice() {
}
void WebGPUDevice::init() {
+ captureDeviceIdentity();
+}
+
+void WebGPUDevice::captureDeviceIdentity() {
// Ask the adapter who this GPU is. getString() below answers with constants
// true of every WebGPU build, and so useless in a loss report; the adapter
// knows the vendor, the chip and the driver build.
@@ -448,7 +452,7 @@ void WebGPUDevice::setScissor(i32 x, i32 y, i32 w, i32 h) {
// the backend's half of the contract; the frame loop stops submitting above them.
BufferHandle WebGPUDevice::createBuffer(const BufferDesc& desc, const void* initialData) {
- if (!isDeviceLive()) return BufferHandle::Invalid;
+ if (!isDeviceUsable()) return BufferHandle::Invalid;
if (!device_) {
ES_LOG_ERROR("WebGPUDevice::createBuffer: no device");
return BufferHandle::Invalid;
@@ -570,7 +574,7 @@ void WebGPUDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {
// =============================================================================
VertexLayoutHandle WebGPUDevice::createVertexLayout(const VertexLayoutDesc& desc) {
- if (!isDeviceLive()) return VertexLayoutHandle::Invalid;
+ if (!isDeviceUsable()) return VertexLayoutHandle::Invalid;
// Validate every attribute has a WebGPU spelling up front — a mismatch is an
// engine bug, not a runtime condition.
for (u32 i = 0; i < desc.attributeCount; ++i) {
@@ -618,7 +622,7 @@ const PipelineDesc* WebGPUDevice::pipelineDesc(PipelineHandle handle) const {
// =============================================================================
TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* pixels) {
- if (!isDeviceLive()) return TextureHandle::Invalid;
+ if (!isDeviceUsable()) return TextureHandle::Invalid;
if (!device_) {
ES_LOG_ERROR("WebGPUDevice::createTexture: no device");
return TextureHandle::Invalid;
@@ -660,7 +664,7 @@ TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* p
TextureHandle WebGPUDevice::createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,
const void* data, u32 byteLength, u32 mipLevels) {
- if (!isDeviceLive()) return TextureHandle::Invalid;
+ if (!isDeviceUsable()) return TextureHandle::Invalid;
if (!device_ || !queue_) {
ES_LOG_ERROR("WebGPUDevice::createCompressedTexture: no device");
return TextureHandle::Invalid;
@@ -821,7 +825,7 @@ bool WebGPUDevice::supportsCompressedFormat(GfxCompressedFormat format) {
ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,
const GfxAttribBinding*, u32,
std::string* outLog, GfxShaderStage* outFailedStage) {
- if (!isDeviceLive()) {
+ if (!isDeviceUsable()) {
if (outLog) *outLog = "device lost";
return ShaderHandle::Invalid;
}
@@ -906,7 +910,7 @@ void WebGPUDevice::uniformBlockBinding(ShaderHandle, u32, u32) {}
// =============================================================================
PipelineHandle WebGPUDevice::createPipeline(const PipelineDesc& desc) {
- if (!isDeviceLive()) return PipelineHandle::Invalid;
+ if (!isDeviceUsable()) return PipelineHandle::Invalid;
// Dedup on the descriptor like GLDevice's pipeline cache.
for (const auto& [id, rec] : pipelines_) {
if (rec.desc == desc) return static_cast<PipelineHandle>(id);
@@ -1411,7 +1415,7 @@ void WebGPUDevice::flushBindGroup() {
// =============================================================================
void WebGPUDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) {
- if (!isDeviceLive() || !pass_) return;
+ if (!isDeviceUsable() || !pass_) return;
auto it = buffers_.find(bound_index_buffer_);
if (it == buffers_.end()) return;
flushBindGroup();
@@ -1422,14 +1426,14 @@ void WebGPUDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 index
}
void WebGPUDevice::drawArrays(u32 firstVertex, u32 vertexCount) {
- if (!isDeviceLive() || !pass_) return;
+ if (!isDeviceUsable() || !pass_) return;
flushBindGroup();
wgpuRenderPassEncoderDraw(pass_, vertexCount, 1, firstVertex, 0);
}
void WebGPUDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 indexByteOffset,
u32 instanceCount) {
- if (!isDeviceLive() || !pass_) return;
+ if (!isDeviceUsable() || !pass_) return;
auto it = buffers_.find(bound_index_buffer_);
if (it == buffers_.end()) return;
flushBindGroup();
@@ -1441,7 +1445,7 @@ void WebGPUDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType,
}
FramebufferHandle WebGPUDevice::createFramebuffer(const FramebufferDesc& desc) {
- if (!isDeviceLive()) return FramebufferHandle::Default;
+ if (!isDeviceUsable()) return FramebufferHandle::Default;
FramebufferRec rec{};
rec.color0 = static_cast<u32>(desc.color0);
rec.depthStencil = static_cast<u32>(desc.depthStencil);
@@ -1461,7 +1465,7 @@ void WebGPUDevice::deleteFramebuffer(FramebufferHandle framebuffer) {
}
void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
- if (!isDeviceLive()) return;
+ if (!isDeviceUsable()) return;
if (!device_) return;
if (pass_) endRenderPass(); // defensive: a dangling pass would deadlock the queue
@@ -1664,7 +1668,7 @@ void WebGPUDevice::releaseReadback(u32 id) {
}
ReadbackHandle WebGPUDevice::requestReadback(FramebufferHandle target, u32 w, u32 h) {
- if (!isDeviceLive()) return ReadbackHandle::Invalid;
+ if (!isDeviceUsable()) return ReadbackHandle::Invalid;
if (!device_ || w == 0 || h == 0) return ReadbackHandle::Invalid;
if (inPass()) {
ES_LOG_ERROR("WebGPUDevice::requestReadback: must be called outside a render pass");
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 5af15d2ec..21797a248 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -79,6 +79,14 @@ public:
bool pollDeviceLost() override;
+protected:
+ void captureDeviceIdentity() override;
+ // recreateDevice is deliberately NOT overridden: only whoever created the
+ // device can replace it, and claiming otherwise would report a recovery that
+ // did not happen. A WebGPU loss stays fatal until that host hands one over.
+
+public:
+
void setViewport(i32 x, i32 y, u32 w, u32 h) override;
void clearStencil(i32 value) override;
diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hpp
index 11ecc638e..ab832e255 100644
--- a/tests/renderer/MockGfxDevice.hpp
+++ b/tests/renderer/MockGfxDevice.hpp
@@ -18,6 +18,13 @@ struct MockGfxDevice final : GfxDevice {
using GfxDevice::markDeviceLost;
using GfxDevice::setDeviceIdentity;
+ // Stands in for a backend that can (or cannot) get its device back.
+ bool recreateSucceeds = true;
+ int recreateCalls = 0;
+ int identityCaptures = 0;
+ bool recreateDevice() override { ++recreateCalls; return recreateSucceeds; }
+ void captureDeviceIdentity() override { ++identityCaptures; }
+
// call counters
// The render state a draw resolved to, as the pipeline saw it.
PipelineDesc lastPipelineDesc{};
diff --git a/tests/renderer/test_device_loss.cpp b/tests/renderer/test_device_loss.cpp
index 96713449b..92271a042 100644
--- a/tests/renderer/test_device_loss.cpp
+++ b/tests/renderer/test_device_loss.cpp
@@ -93,6 +93,62 @@ int main() {
"giving up does not overwrite why it was lost");
}
+ // --- Recovery: usable before it is whole ---
+ {
+ MockGfxDevice d;
+ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");
+
+ CHECK(d.recoverDevice(), "recoverDevice succeeds when the backend can rebuild");
+ CHECK(d.recreateCalls == 1, "the backend was asked exactly once");
+ CHECK(d.deviceStatus() == GfxDeviceStatus::Recovering, "a rebuilt device is Recovering");
+ CHECK(!d.isDeviceLive(), "Recovering is not yet Live");
+ // The whole point of the middle state: the device draws while its content
+ // is still being re-uploaded, instead of freezing until the last texture.
+ CHECK(d.isDeviceUsable(), "a Recovering device may be submitted to");
+ CHECK(d.beginDeviceFrame(), "a Recovering device opens frames");
+ CHECK(d.deviceLostInfo() != nullptr, "the report stands until the content is back");
+
+ d.markDeviceRestored();
+ CHECK(d.deviceStatus() == GfxDeviceStatus::Live, "markDeviceRestored completes it");
+ CHECK(d.deviceLostInfo() == nullptr, "a restored device reports no loss");
+ // A rebuilt device can be a different GPU, so the identity is re-asked.
+ CHECK(d.identityCaptures == 1, "identity is captured again on restore");
+ }
+
+ // --- A recovery that fails leaves it retryable, not half-open ---
+ {
+ MockGfxDevice d;
+ d.notifyDeviceLost(GfxDeviceLostReason::Reset, "hung");
+ d.recreateSucceeds = false;
+
+ CHECK(!d.recoverDevice(), "recoverDevice reports the failure");
+ CHECK(d.deviceStatus() == GfxDeviceStatus::Lost, "a failed recovery falls back to Lost");
+ CHECK(!d.isDeviceUsable(), "and nothing may be submitted to it");
+ CHECK(d.deviceLostInfo()->reason == GfxDeviceLostReason::Reset,
+ "the original reason is not lost to the failed attempt");
+
+ // Retryable: a context comes back when the browser is ready, not when asked.
+ d.recreateSucceeds = true;
+ CHECK(d.recoverDevice(), "a later attempt can still succeed");
+ CHECK(d.deviceStatus() == GfxDeviceStatus::Recovering, "and it lands in Recovering");
+ }
+
+ // --- The transitions that must do nothing ---
+ {
+ MockGfxDevice live;
+ CHECK(live.recoverDevice(), "recovering a live device is a no-op that reports usable");
+ CHECK(live.recreateCalls == 0, "a live device is never asked to rebuild");
+ live.markDeviceRestored();
+ CHECK(live.deviceStatus() == GfxDeviceStatus::Live, "restoring a live device changes nothing");
+ CHECK(live.identityCaptures == 0, "and does not re-ask its identity");
+
+ MockGfxDevice dead;
+ dead.markDeviceDead();
+ CHECK(!dead.recoverDevice(), "a device given up on is not recovered");
+ CHECK(dead.recreateCalls == 0, "and its backend is never asked");
+ CHECK(dead.deviceStatus() == GfxDeviceStatus::Dead, "it stays Dead");
+ }
+
std::printf(g_failures ? "\n%d FAILURE(S)\n" : "\nall passed\n", g_failures);
return g_failures ? 1 : 0;
}