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
fix(render): the device rebuilds every object it issued behind the same handle
esenginedb27d6848ef3
diff --git a/cmake/ESEngineSources.cmake b/cmake/ESEngineSources.cmakeindex 8d3648d8c..ea392c026 100644--- a/cmake/ESEngineSources.cmake+++ b/cmake/ESEngineSources.cmake@@ -13,6 +13,7 @@ set(ESENGINE_SOURCES${ESENGINE_ROOT}/src/esengine/resource/ResourceManager.cpp${ESENGINE_ROOT}/src/esengine/resource/ShaderParser.cpp${ESENGINE_ROOT}/src/esengine/renderer/frame/RenderContext.cpp+ ${ESENGINE_ROOT}/src/esengine/renderer/rhi/GfxDevice.cpp${ESENGINE_ROOT}/src/esengine/renderer/rhi/Shader.cpp${ESENGINE_ROOT}/src/esengine/renderer/draw/DrawParams.cpp${ESENGINE_ROOT}/src/esengine/renderer/rhi/Buffer.cppdiff --git a/desktop b/desktopindex 50bb640ea..e95a74b62 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 50bb640ea236de165681076130fe5950a3d08a83+Subproject commit e95a74b6294918bd00811153954b59543ea00413diff --git a/native/host/media/ktx2_decode.cpp b/native/host/media/ktx2_decode.cppindex 78e05772f..1c4c11ecf 100644--- a/native/host/media/ktx2_decode.cpp+++ b/native/host/media/ktx2_decode.cpp@@ -114,8 +114,9 @@ KTX2Result transcodeKTX2(const uint8_t* bytes, size_t n, bool srgb,const ConstSpan<u8> span(out.data(), out.size());const resource::TextureHandle handle = compressed- ? rm.createCompressedTexture(w, h, gfxFmt, span, uploaded)- : rm.createTexture(w, h, span, srgb ? TextureFormat::SRGB8A8 : TextureFormat::RGBA8, false);+ ? rm.createCompressedTexture(resource::ResourceContent::Asset, w, h, gfxFmt, span, uploaded)+ : rm.createTexture(resource::ResourceContent::Asset, w, h, span,+ srgb ? TextureFormat::SRGB8A8 : TextureFormat::RGBA8, false);if (!handle.isValid()) return fail;return KTX2Result{static_cast<int>(handle.id()), static_cast<int>(w), static_cast<int>(h),compressed ? static_cast<int>(gfxFmt) : -1,diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 97033a791..db39e4afb 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 96 beta · 1833 experimental · 3 deprecated+Symbols: 114 public · 96 beta · 1832 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1016,7 +1016,7 @@ loadTextureRaw: (ref: string) => Promise<TextureResult>loadTilemap: (ref: string) => Promise<TilemapResult>loadTileset: (ref: string) => Promise<TilesetResult>loadTimeline: (ref: string) => Promise<TimelineResult>-meshRealizations: () => { handle: number; generation: number; realized: boolean; }[]+meshRealizations: () => { handle: number; realized: boolean; }[]meshesAwaitingRematerialization: () => number[]onInvalidate: (listener: InvalidateListener) => () => voidpathForHandle: (kind: string, handle: number) => string | null@@ -1048,7 +1048,7 @@ setRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReport-texturesAwaitingReupload: () => { handle: number; path: string; }[]+texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClassstatic prototype: AssetsClass@@ -12481,11 +12481,6 @@ EventBindingPlugin(report: DiagnosticReport): string```-## finishDeviceRecovery — function @experimental-```-(): number-```-## fireScriptGraphEvent — function @experimental```<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>, type: string, target: number, other?: number): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex d25cd8d36..781555359 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: 114 public · 101 beta · 1852 experimental · 3 deprecated+Symbols: 114 public · 101 beta · 1851 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1016,7 +1016,7 @@ loadTextureRaw: (ref: string) => Promise<TextureResult>loadTilemap: (ref: string) => Promise<TilemapResult>loadTileset: (ref: string) => Promise<TilesetResult>loadTimeline: (ref: string) => Promise<TimelineResult>-meshRealizations: () => { handle: number; generation: number; realized: boolean; }[]+meshRealizations: () => { handle: number; realized: boolean; }[]meshesAwaitingRematerialization: () => number[]onInvalidate: (listener: InvalidateListener) => () => voidpathForHandle: (kind: string, handle: number) => string | null@@ -1048,7 +1048,7 @@ setRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReport-texturesAwaitingReupload: () => { handle: number; path: string; }[]+texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClassstatic prototype: AssetsClass@@ -12714,11 +12714,6 @@ EventBindingPlugin(report: DiagnosticReport): string```-## finishDeviceRecovery — function @experimental-```-(): number-```-## fireScriptGraphEvent — function @experimental```<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>, type: string, target: number, other?: number): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex c9bb4c734..71b82bab5 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 98 beta · 1832 experimental · 3 deprecated+Symbols: 114 public · 98 beta · 1831 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1011,7 +1011,7 @@ loadTextureRaw: (ref: string) => Promise<TextureResult>loadTilemap: (ref: string) => Promise<TilemapResult>loadTileset: (ref: string) => Promise<TilesetResult>loadTimeline: (ref: string) => Promise<TimelineResult>-meshRealizations: () => { handle: number; generation: number; realized: boolean; }[]+meshRealizations: () => { handle: number; realized: boolean; }[]meshesAwaitingRematerialization: () => number[]onInvalidate: (listener: InvalidateListener) => () => voidpathForHandle: (kind: string, handle: number) => string | null@@ -1043,7 +1043,7 @@ setRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReport-texturesAwaitingReupload: () => { handle: number; path: string; }[]+texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClassstatic prototype: AssetsClass@@ -12476,11 +12476,6 @@ EventBindingPlugin(report: DiagnosticReport): string```-## finishDeviceRecovery — function @experimental-```-(): number-```-## fireScriptGraphEvent — function @experimental```<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>, type: string, target: number, other?: number): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 2bf570d80..0258fdf49 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 96 beta · 1854 experimental · 3 deprecated+Symbols: 114 public · 96 beta · 1853 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1011,7 +1011,7 @@ loadTextureRaw: (ref: string) => Promise<TextureResult>loadTilemap: (ref: string) => Promise<TilemapResult>loadTileset: (ref: string) => Promise<TilesetResult>loadTimeline: (ref: string) => Promise<TimelineResult>-meshRealizations: () => { handle: number; generation: number; realized: boolean; }[]+meshRealizations: () => { handle: number; realized: boolean; }[]meshesAwaitingRematerialization: () => number[]onInvalidate: (listener: InvalidateListener) => () => voidpathForHandle: (kind: string, handle: number) => string | null@@ -1043,7 +1043,7 @@ setRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReport-texturesAwaitingReupload: () => { handle: number; path: string; }[]+texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClassstatic prototype: AssetsClass@@ -12735,11 +12735,6 @@ EventBindingPlugin(report: DiagnosticReport): string```-## finishDeviceRecovery — function @experimental-```-(): number-```-## fireScriptGraphEvent — function @experimental```<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>, type: string, target: number, other?: number): voiddiff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex 4ff21b48d..14c8aa624 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -1,7 +1,7 @@# API surface — esengine/wasm<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 6 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 8 experimental · 0 deprecated## CppEngineContext — interface @experimental```@@ -214,13 +214,14 @@ valid: (entity: Entity) => boolean```acquireTextureByPath: (path: string) => numberadoptTextureContent: ((target: number, source: number) => boolean) | undefined-createCompressedTexture: ((width: number, height: number, format: number, dataPtr: number, dataLen: number, mipLevels: number) => number) | undefined+createCompressedTexture: ((width: number, height: number, format: number, dataPtr: number, dataLen: number, mipLevels: number, content: TextureContent) => number) | undefinedcreateLabelAtlasFont: (textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number) => numbercreateShader: (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+createTexture: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, content: TextureContent) => number+createTextureEx: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number, content: TextureContent) => number+createTextureFromBytes: ((width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, content: TextureContent, filterMode?: number, wrapMode?: number) => number) | undefinedcreateTextureFromKTX2: ((bytes: Uint8Array, srgb: boolean) => { handle: number; width: number; height: number; format?: number; blockRefused?: boolean; } | null) | undefined+forgoTextureContent: ((handle: number) => void) | undefinedgetBitmapFontRefCount: (handle: number) => numbergetResourceStats: () => { shaderCount: number; textureCount: number; vertexBufferCount: number; indexBufferCount: number; cacheHits: number; cacheMisses: number; textureBytes: number; textureBudget: number; textureEvictableCount: number; }getShaderRefCount: (handle: number) => number@@ -232,14 +233,12 @@ loadBitmapFont: (fntContent: string, textureHandle: number, texWidth: number, temeasureBitmapText: (fontHandle: number, text: string, fontSize: number, spacing: number) => { width: number; height: number; }meshRealizations: (() => string) | undefinedmeshesAwaitingRemat: (() => string) | undefined-meshesLostNonRecoverable: (() => number) | undefined-registerExternalTexture: (glTextureId: number, width: number, height: number) => number-registerExternalTextureSized: (glTextureId: number, width: number, height: number, bytes: number) => number+registerExternalTexture: (glTextureId: number, width: number, height: number, content: TextureContent) => number+registerExternalTextureSized: (glTextureId: number, width: number, height: number, bytes: number, content: TextureContent) => numberregisterTextureWithPath: (handle: number, path: string) => voidreleaseBitmapFont: (handle: number) => voidreleaseShader: (handle: number) => voidreleaseTexture: (handle: number) => void-retargetExternalTexture: ((handle: number, glTextureId: number, width: number, height: number) => boolean) | undefinedsetTextureBudget: (bytes: number) => voidsetTextureMetadata: (handle: number, left: number, right: number, top: number, bottom: number) => voidsupportsCompressedFormat: ((format: number) => boolean) | undefined@@ -247,6 +246,7 @@ texturesAwaitingReupload: (() => string) | undefinedtrimTextureCache: () => numberupdateTextureSubregion: (handle: number, x: number, y: number, width: number, height: number, pixels: number, pixelsLen: number) => voidupdateTextureSubregionFromBytes: ((handle: number, x: number, y: number, width: number, height: number, pixels: Uint8Array) => void) | undefined+wrapDeviceTexture: ((textureId: number, width: number, height: number) => number) | undefined```## ESEngineModule — interface @experimental@@ -329,7 +329,6 @@ gl_enableErrorCheck: (enabled: boolean) => voidinitRenderer: () => voidinitRendererWebGPU: (canvasSelector: string, width: number, height: number, readback: boolean, preferBGRA: boolean) => booleaninitRendererWithContext: (contextHandle: number) => boolean-markDeviceRestored: (() => number) | undefinedmaterial_compileEsshader: (source: string, featuresCsv: string) => numbermaterial_define: (materialId: number, shaderHandle: number, blendMode: number, flags: number, depthBias: number) => voidmaterial_setTexture: (materialId: number, name: string, textureHandle: number) => void@@ -529,3 +528,13 @@ renderTargets: numbertextures: number```+## TextureContent — type @experimental+```+typeof TextureContent[keyof typeof TextureContent]+```++## textureContentName — function @experimental+```+(content: TextureContent): string+```+diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 82d805bc9..2e66a88e2 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 96 beta · 1844 experimental · 3 deprecated+Symbols: 114 public · 96 beta · 1843 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1011,7 +1011,7 @@ loadTextureRaw: (ref: string) => Promise<TextureResult>loadTilemap: (ref: string) => Promise<TilemapResult>loadTileset: (ref: string) => Promise<TilesetResult>loadTimeline: (ref: string) => Promise<TimelineResult>-meshRealizations: () => { handle: number; generation: number; realized: boolean; }[]+meshRealizations: () => { handle: number; realized: boolean; }[]meshesAwaitingRematerialization: () => number[]onInvalidate: (listener: InvalidateListener) => () => voidpathForHandle: (kind: string, handle: number) => string | null@@ -1043,7 +1043,7 @@ setRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReport-texturesAwaitingReupload: () => { handle: number; path: string; }[]+texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClassstatic prototype: AssetsClass@@ -12504,11 +12504,6 @@ EventBindingPlugin(report: DiagnosticReport): string```-## finishDeviceRecovery — function @experimental-```-(): number-```-## fireScriptGraphEvent — function @experimental```<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>, type: string, target: number, other?: number): voiddiff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 49de887d2..b6bd2f8c3 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -13,7 +13,7 @@ import type {LocaleResult, FsmResult, BtResult, AnimatorControllerResult, JsonResult,} from './AssetLoader';import { AsyncCache } from './AsyncCache';-import type { ESEngineModule } from '../wasm';+import { TextureContent, textureContentName, type ESEngineModule } from '../wasm';import type { CppResourceManager } from '../wasm';import { requireResourceManager, getResourceManager, evictTextureDimensions } from '../wasm/resourceManager';import type { TextureImportSettings, TextureImportSettingsResolver } from './loaders/TextureLoader';@@ -57,7 +57,7 @@ import { SceneHandle, type ReleaseCallback } from './SceneHandle';import { UUID_REF_PREFIX } from './AssetRegistry';import type { AssetRefCounter } from './AssetRefCounter';import { log } from '../util/logger';-import { recoverDevice, finishDeviceRecovery } from '../render/renderer';+import { recoverDevice, getDeviceStatus, DeviceStatus } from '../render/renderer';/*** One asset generation ending: which ref, what kind of asset it was, and what@@ -445,40 +445,42 @@ export class Assets {}/**- * The textures still on the placeholder, and the path each was registered- * under — the engine's list, not a mirror of this cache. A loss sweeps every- * texture, so restoring only what this layer remembers reports a whole- * device with half the screen white. A blank path is not the asset layer's.+ * The textures the engine is waiting for content for — its ledger, not a+ * mirror of this cache — with who refills each and the path it was+ * registered under. A blank path is not this layer's to fetch.*/- texturesAwaitingReupload(): { handle: number; path: string }[] {+ texturesAwaitingReupload(): { handle: number; content: TextureContent; path: string }[] {const raw = requireResourceManager().texturesAwaitingReupload?.() ?? '';if (!raw) return [];return raw.split('\n').map((line) => {- const cut = line.indexOf('|');+ const [handle, content, ...path] = line.split('|');return {- handle: Number(cut < 0 ? line : line.slice(0, cut)),- path: cut < 0 ? '' : line.slice(cut + 1),+ handle: Number(handle),+ content: Number(content) as TextureContent,+ path: path.join('|'),};});}/**- * Re-uploads every texture the engine says is still the placeholder.+ * Refills every owed texture this layer can, and gives up on the rest.*- * 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.+ * An asset texture is loaded the ordinary way and moved behind the handle+ * everything holds. Content nobody here can remake is forgone by name: waiting+ * for it would keep the device recovering forever.*/async reuploadTexturesAfterDeviceLoss(): Promise<number> {const rm = requireResourceManager();if (!rm.adoptTextureContent) return 0;let restored = 0;- 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;+ for (const { handle, content, path } of this.texturesAwaitingReupload()) {+ if (content !== TextureContent.Asset || !path) {+ log.warn('assets', `Device recovery: texture ${handle} (${textureContentName(content)})`+ + ' has no provider to refill it; it stays blank');+ rm.forgoTextureContent?.(handle);+ continue;+ }const cut = path.lastIndexOf(':');const ref = cut < 0 ? path : path.slice(0, cut);const flip = cut < 0 || path.slice(cut + 1) === 'f';@@ -497,31 +499,21 @@ export class Assets {}/**- * The meshes the engine says lost their geometry, by handle. No path travels- * with them: the engine never knew one, and this layer does — which is the- * division the whole recovery rests on. The engine says WHICH identity is- * owed; only the asset layer can say what it was made from.+ * The meshes the engine is waiting for geometry for, by handle. No path+ * travels with them: the engine never knew one, and this layer does.*/meshesAwaitingRematerialization(): number[] {const raw = requireResourceManager().meshesAwaitingRemat?.() ?? '';return raw ? raw.split(',').map(Number).filter((h) => h > 0) : [];}- /**- * Every live mesh's identity beside the device generation its realization- * belongs to. A recovery that minted new handles and one that put geometry- * back behind the old ones both end with a scene that draws.- */- meshRealizations(): { handle: number; generation: number; realized: boolean }[] {+ /** Every live mesh and whether its geometry is on the device. */+ meshRealizations(): { handle: number; realized: boolean }[] {const raw = requireResourceManager().meshRealizations?.() ?? '';if (!raw) return [];return raw.split(',').map((row) => {- const [handle, generation, realized] = row.split(':');- return {- handle: Number(handle),- generation: Number(generation),- realized: realized === '1',- };+ const [handle, realized] = row.split(':');+ return { handle: Number(handle), realized: realized === '1' };});}@@ -529,10 +521,10 @@ export class Assets {* Replays each owed mesh from its source, into the handle it already has.** A missing provenance is a CONTRACT VIOLATION, not a mesh that turns out to- * be unrecoverable: the engine only enqueues what a producer declared+ * be unrecoverable: the engine only owes what a producer declared* replayable, so an absent path means this layer lost the record.*- * @return How many came back. The rest stay owed, so recovery cannot finish.+ * @return How many came back. The rest stay owed.*/async rematerializeMeshesAfterDeviceLoss(): Promise<number> {const loader = this.getLoader<MeshResult>('mesh');@@ -558,29 +550,21 @@ export class Assets {}/**- * The whole recovery, in the order it has to happen: rebuild what the engine- * can, put the content back, then declare the device whole. Returns false- * while the context is not available yet — a browser restores when it is- * ready, so a caller retries rather than giving up.+ * Pays what the engine owes after rebuilding the device. The rebuild itself+ * is the engine's, once per loss; this only refills content. Returns whether+ * the device is whole — false while the context is not back yet, or while+ * content is still owed, so a caller retries.*/async recoverFromDeviceLoss(): Promise<boolean> {if (!recoverDevice()) return false;await this.reuploadTexturesAfterDeviceLoss();await this.rematerializeMeshesAfterDeviceLoss();- const pending = finishDeviceRecovery();- if (pending > 0) {- log.warn('assets',- `Device recovery: ${pending} texture(s)/mesh(es) have not come back`);- return false;- }- // Host-only geometry cannot come back, and a recovery that says nothing- // about it reads as one where everything did.- const lost = requireResourceManager().meshesLostNonRecoverable?.() ?? 0;- if (lost > 0) {- log.warn('assets', `Device recovery: ${lost} host-only mesh(es) ended with the`- + ' device — no source can replay them');+ const whole = getDeviceStatus() === DeviceStatus.Live;+ if (!whole) {+ const owed = this.texturesAwaitingReupload().length + this.meshesAwaitingRematerialization().length;+ log.warn('assets', `Device recovery: ${owed} texture(s)/mesh(es) have not come back`);}- return true;+ return whole;}private async loadTextureVariant_(ref: string, flip: boolean): Promise<TextureResult> {@@ -2561,11 +2545,11 @@ export class Assets {return fetchDecodePixels(self.backend.resolveUrl(self.catalog.getBuildPath(path)));},async createTextureFromPixels(width, height, pixels, flipY) {- return self.textureLoader_.loadFromPixels(width, height, pixels, flipY);+ return self.textureLoader_.loadFromPixels(width, height, pixels, flipY, TextureContent.Retained);},async createOwnedTexture(width, height, pixels, flipY) {return self.ownedTextureLease_(- await self.textureLoader_.loadFromPixels(width, height, pixels, flipY),+ await self.textureLoader_.loadFromPixels(width, height, pixels, flipY, TextureContent.Retained),);},getAudio() {diff --git a/sdk/src/asset/canvasTexture.ts b/sdk/src/asset/canvasTexture.tsindex be22640ea..fc4ae6e74 100644--- a/sdk/src/asset/canvasTexture.ts+++ b/sdk/src/asset/canvasTexture.ts@@ -17,6 +17,7 @@* no mipmaps (a chain regenerated every frame is pure waste), clamped wrap* (nothing tiles a leaderboard), and `update()`.*/+import { TextureContent } from '../wasm';import { requireResourceManager } from '../wasm/resourceManager';import type { App } from '../app/app';import { findWebGL2Context } from './loaders/TextureLoader';@@ -77,7 +78,7 @@ export function createCanvasTexture(const glTextureId = glObj.getNewId(glObj.textures);glObj.textures[glTextureId] = texture;const rm = requireResourceManager();- const handle = rm.registerExternalTexture(glTextureId, size.width, size.height);+ const handle = rm.registerExternalTexture(glTextureId, size.width, size.height, TextureContent.Canvas);let alive = true;return {diff --git a/sdk/src/asset/compressed.ts b/sdk/src/asset/compressed.tsindex 746521547..1de803dc8 100644--- a/sdk/src/asset/compressed.ts+++ b/sdk/src/asset/compressed.ts@@ -14,7 +14,7 @@* enabled JS-side via `getExtension`. The C++ `GfxDevice::compressedTexImage2D`* entry backs the non-WebGL2 fallback path instead.*/-import type { ESEngineModule } from '../wasm';+import { TextureContent, type ESEngineModule } from '../wasm';import { requireResourceManager } from '../wasm/resourceManager';import { applyBoundTextureSampling } from './glTextureUpload';@@ -245,9 +245,9 @@ function registerGlTexture(// Older wasm builds / minimal mocks lack the sized variant — fall back to// the estimate rather than fail the upload.if (gpuBytes > 0 && typeof rm.registerExternalTextureSized === 'function') {- return rm.registerExternalTextureSized(id, width, height, gpuBytes);+ return rm.registerExternalTextureSized(id, width, height, gpuBytes, TextureContent.Asset);}- return rm.registerExternalTexture(id, width, height);+ return rm.registerExternalTexture(id, width, height, TextureContent.Asset);}/** Upload pre-transcoded compressed blocks via `gl.compressedTexImage2D`. */diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.tsindex 067333ab2..077a600fe 100644--- a/sdk/src/asset/loaders/TextureLoader.ts+++ b/sdk/src/asset/loaders/TextureLoader.ts@@ -6,7 +6,7 @@ import { platformCreateImage } from '../../platform/base';import type { PlatformImage } from '../../platform/types';import { decodeImageBitmap, readImagePixels } from '../imageDecode';import { requireResourceManager } from '../../wasm/resourceManager';-import type { ESEngineModule } from '../../wasm';+import { TextureContent, type ESEngineModule } from '../../wasm';import { withMalloc } from '../../wasm/wasmScratch';import {isKtx2, isKtx2Path, loadCompressedTexture, chooseEngineTargetFormat, engineFormatCode,@@ -146,13 +146,13 @@ export class TextureLoader implements AssetLoader<TextureResult> {}async loadFromPixels(- width: number, height: number, pixels: Uint8Array, flipY: boolean,+ width: number, height: number, pixels: Uint8Array, flipY: boolean, content: TextureContent,): Promise<TextureResult> {const rm = requireResourceManager();// 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);+ const handle = rm.createTextureFromBytes(width, height, pixels, 1, flipY, content);return { handle, width, height };}if (!this.module_) {@@ -161,7 +161,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {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 rm.createTexture(width, height, ptr, pixels.length, 1, flipY, content);});return { handle, width, height };}@@ -215,7 +215,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {const params: TextureParams = {filterMode: settings?.filter, wrapMode: settings?.wrap, srgb: settings?.srgb,};- const handle = createTextureFromPixels(this.module_, result, flip, params);+ const handle = createTextureFromPixels(this.module_, result, TextureContent.Asset, flip, params);return { handle, width: result.width, height: result.height };}const url = ctx.backend.resolveUrl(ctx.catalog.getBuildPath(path));@@ -288,7 +288,8 @@ export class TextureLoader implements AssetLoader<TextureResult> {const code = engineFormatCode(target, srgb);const handle = withMalloc(module, t.data.length, (ptr) => {module.HEAPU8.set(t.data, ptr);- return rm.createCompressedTexture!(t.width, t.height, code, ptr, t.data.length, 1);+ return rm.createCompressedTexture!(t.width, t.height, code, ptr, t.data.length, 1,+ TextureContent.Asset);});if (handle) return { handle, width: t.width, height: t.height };// The upload itself failed after a good transcode — the payload@@ -301,7 +302,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {}const rgba = transcoder.transcodeToRgba(bytes);if (!rgba) throw new Error(`TextureLoader: KTX2 decode failed for ${path}`);- return this.loadFromPixels(rgba.width, rgba.height, rgba.data, false);+ return this.loadFromPixels(rgba.width, rgba.height, rgba.data, false, TextureContent.Asset);}/**@@ -414,7 +415,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {glObj.textures[glTextureId] = texture;const rm = requireResourceManager();- const handle = rm.registerExternalTexture(glTextureId, width, height);+ const handle = rm.registerExternalTexture(glTextureId, width, height, TextureContent.Asset);return { handle, width, height };}@@ -438,7 +439,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {const format = linearColorSpace() && (settings?.srgb ?? true) ? 2 : 1;const handle = withMalloc(module, pixels.length, ptr => {module.HEAPU8.set(pixels, ptr);- return rm.createTexture(width, height, ptr, pixels.length, format, flip);+ return rm.createTexture(width, height, ptr, pixels.length, format, flip, TextureContent.Asset);});return { handle, width, height };diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.tsindex 7e9e3b28d..8528de1d1 100644--- a/sdk/src/core-render.ts+++ b/sdk/src/core-render.ts@@ -190,7 +190,6 @@ export {getDeviceLostReport,reportDeviceLost,recoverDevice,- finishDeviceRecovery,getContextLossGuardInfo,} from './render/renderer';diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex 80b0c0da5..d088a7056 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -193,11 +193,12 @@ export interface NativeEngineApi {renderer_updateTransforms?(registry: unknown): void;rm_acquireTextureByPath?(rm: unknown, path: string): number;rm_adoptTextureContent?(rm: unknown, target: number, source: number): boolean;- rm_createCompressedTexture?(rm: unknown, width: number, height: number, format: number, dataPtr: number, dataLen: number, mipLevels: number): number;+ rm_createCompressedTexture?(rm: unknown, width: number, height: number, format: number, dataPtr: number, dataLen: number, mipLevels: number, content: number): number;rm_createLabelAtlasFont?(rm: unknown, textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;rm_createShader?(rm: unknown, vertSrc: string, fragSrc: string): number;- rm_createTexture?(rm: unknown, width: number, height: number, pixelsPtr: number, pixelsLen: number, format: number, flipY: boolean): number;- rm_createTextureEx?(rm: unknown, width: number, height: number, pixelsPtr: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number): number;+ rm_createTexture?(rm: unknown, width: number, height: number, pixelsPtr: number, pixelsLen: number, format: number, flipY: boolean, content: number): number;+ rm_createTextureEx?(rm: unknown, width: number, height: number, pixelsPtr: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number, content: number): number;+ rm_forgoTextureContent?(rm: unknown, handle: number): void;rm_getBitmapFontRefCount?(rm: unknown, handleId: number): number;rm_getShaderRefCount?(rm: unknown, handleId: number): number;rm_getTextureGLId?(rm: unknown, handleId: number): number;@@ -206,20 +207,19 @@ export interface NativeEngineApi {rm_loadBitmapFont?(rm: unknown, fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;rm_meshRealizations?(rm: unknown): string;rm_meshesAwaitingRemat?(rm: unknown): string;- rm_meshesLostNonRecoverable?(rm: unknown): number;- rm_registerExternalTexture?(rm: unknown, glTextureId: number, width: number, height: number): number;- rm_registerExternalTextureSized?(rm: unknown, glTextureId: number, width: number, height: number, bytes: number): number;+ rm_registerExternalTexture?(rm: unknown, glTextureId: number, width: number, height: number, content: number): number;+ rm_registerExternalTextureSized?(rm: unknown, glTextureId: number, width: number, height: number, bytes: number, content: number): number;rm_registerTextureWithPath?(rm: unknown, handleId: number, path: string): void;rm_releaseBitmapFont?(rm: unknown, handleId: number): void;rm_releaseShader?(rm: unknown, handleId: number): void;rm_releaseTexture?(rm: unknown, handleId: number): void;- rm_retargetExternalTexture?(rm: unknown, handle: number, glTextureId: number, width: number, height: number): boolean;rm_setTextureBudget?(rm: unknown, bytes: number): void;rm_setTextureMetadata?(rm: unknown, handleId: number, left: number, right: number, top: number, bottom: number): void;rm_supportsCompressedFormat?(rm: unknown, format: number): boolean;rm_texturesAwaitingReupload?(rm: unknown): string;rm_trimTextureCache?(rm: unknown): number;rm_updateTextureSubregion?(rm: unknown, handleId: number, x: number, y: number, width: number, height: number, pixelsPtr: number, pixelsLen: number): void;+ rm_wrapDeviceTexture?(rm: unknown, textureId: number, width: number, height: number): number;tilemap_advanceAnimations?(entity: number, dtMs: number): void;tilemap_clearTileAnimations?(entity: number): void;tilemap_destroyLayer?(entity: number): void;@@ -464,6 +464,7 @@ export function createNativeEngineApi(bind('rm_createShader', 'es_rm_createShader', true);bind('rm_createTexture', 'es_rm_createTexture', true);bind('rm_createTextureEx', 'es_rm_createTextureEx', true);+ bind('rm_forgoTextureContent', 'es_rm_forgoTextureContent', true);bind('rm_getBitmapFontRefCount', 'es_rm_getBitmapFontRefCount', true);bind('rm_getShaderRefCount', 'es_rm_getShaderRefCount', true);bind('rm_getTextureGLId', 'es_rm_getTextureGLId', true);@@ -472,20 +473,19 @@ export function createNativeEngineApi(bind('rm_loadBitmapFont', 'es_rm_loadBitmapFont', true);bind('rm_meshRealizations', 'es_rm_meshRealizations', true);bind('rm_meshesAwaitingRemat', 'es_rm_meshesAwaitingRemat', true);- bind('rm_meshesLostNonRecoverable', 'es_rm_meshesLostNonRecoverable', true);bind('rm_registerExternalTexture', 'es_rm_registerExternalTexture', true);bind('rm_registerExternalTextureSized', 'es_rm_registerExternalTextureSized', true);bind('rm_registerTextureWithPath', 'es_rm_registerTextureWithPath', true);bind('rm_releaseBitmapFont', 'es_rm_releaseBitmapFont', true);bind('rm_releaseShader', 'es_rm_releaseShader', true);bind('rm_releaseTexture', 'es_rm_releaseTexture', true);- bind('rm_retargetExternalTexture', 'es_rm_retargetExternalTexture', true);bind('rm_setTextureBudget', 'es_rm_setTextureBudget', true);bind('rm_setTextureMetadata', 'es_rm_setTextureMetadata', true);bind('rm_supportsCompressedFormat', 'es_rm_supportsCompressedFormat', true);bind('rm_texturesAwaitingReupload', 'es_rm_texturesAwaitingReupload', true);bind('rm_trimTextureCache', 'es_rm_trimTextureCache', true);bind('rm_updateTextureSubregion', 'es_rm_updateTextureSubregion', true);+ bind('rm_wrapDeviceTexture', 'es_rm_wrapDeviceTexture', true);bind('tilemap_advanceAnimations', 'es_tilemap_advanceAnimations', false);bind('tilemap_clearTileAnimations', 'es_tilemap_clearTileAnimations', false);bind('tilemap_destroyLayer', 'es_tilemap_destroyLayer', false);diff --git a/sdk/src/ecs/bridge/nativeResourceManager.ts b/sdk/src/ecs/bridge/nativeResourceManager.tsindex 4da1366e2..e23c530f8 100644--- a/sdk/src/ecs/bridge/nativeResourceManager.ts+++ b/sdk/src/ecs/bridge/nativeResourceManager.ts@@ -70,11 +70,11 @@ export function createNativeResourceManager(// path applies — Linear filtering, ClampToEdge wrap (Texture::create's// pixel overload) — so a texture with no settings uploads identically.createTextureFromBytes: (- width, height, pixels, format, flipY, filterMode, wrapMode,+ width, height, pixels, format, flipY, content, filterMode, wrapMode,): number =>hostCall(scope, RESOURCE_BINDINGS.createTexture,[width, height, pixels, pixels.length, format, flipY,- filterMode ?? FILTER_LINEAR, wrapMode ?? WRAP_CLAMP_TO_EDGE]) as number,+ filterMode ?? FILTER_LINEAR, wrapMode ?? WRAP_CLAMP_TO_EDGE, content]) as number,// The host transcodes KTX2 (basis) and uploads the blocks:// { id, width, height, format, blockRefused } → { handle, ... }. A hostdiff --git a/sdk/src/render/renderTexture.ts b/sdk/src/render/renderTexture.tsindex a3c0a53c5..ab67440fb 100644--- a/sdk/src/render/renderTexture.ts+++ b/sdk/src/render/renderTexture.ts@@ -47,10 +47,10 @@ export const RenderTexture = {const handle = Renderer.createRenderTarget(options.width, options.height, flags);const textureId = Renderer.getTargetTexture(handle);- // Same channel video frames use: adopt the device texture into the- // resource table so components can reference it by handle.+ // The target keeps its texture; the resource table only names it, so+ // components can reference it by handle.const texture = textureId !== 0- ? getResourceManager()?.registerExternalTexture(textureId, options.width, options.height) ?? 0+ ? getResourceManager()?.wrapDeviceTexture?.(textureId, options.width, options.height) ?? 0: 0;sizes.set(handle, { width: options.width, height: options.height });diff --git a/sdk/src/render/renderer.ts b/sdk/src/render/renderer.tsindex f42ba6070..bf509392f 100644--- a/sdk/src/render/renderer.ts+++ b/sdk/src/render/renderer.ts@@ -349,25 +349,16 @@ export function getContextLossGuardInfo(): { target: string; lostEventsSeen: num}/**- * Ask the engine to rebuild the renderer after a loss.+ * Ask the engine to rebuild the device and every object it issued, behind the+ * same handles.*- * False means "not yet", not "never": a browser hands a WebGL context back when- * it is ready. On success the device is Recovering — drawing, with placeholder- * textures — until {@link finishDeviceRecovery}.+ * False means "not yet": a browser hands a WebGL context back when it is ready.+ * The device then draws while Recovering and turns Live once nothing is owed.*/export function recoverDevice(): boolean {return module?.recoverDevice?.() ?? false;}-/**- * Ends recovery — the engine decides whether it actually ended, and answers how- * many textures are still the placeholder. Above zero it stays Recovering: a- * device reporting Live with white content is the hardest failure to read.- */-export function finishDeviceRecovery(): number {- return module?.markDeviceRestored?.() ?? 0;-}-/*** Subscribe to the host's `GPUDevice.lost`.*diff --git a/sdk/src/runtime/runtimeAssets.ts b/sdk/src/runtime/runtimeAssets.tsindex 49f44c9ea..853c21955 100644--- a/sdk/src/runtime/runtimeAssets.ts+++ b/sdk/src/runtime/runtimeAssets.ts@@ -9,7 +9,7 @@* runtime loader nor the spine loader has to import the other.import { linearColorSpace } from '../ecs/env';*/-import type { ESEngineModule } from '../wasm';+import { TextureContent, type ESEngineModule } from '../wasm';import { linearColorSpace } from '../ecs/env';import type { Backend } from '../asset/Backend';import type { ParsedTextureImportSettings } from '../asset/textureImportSettings';@@ -98,7 +98,7 @@ export async function createAtlasPageTexture(): Promise<{ handle: number; width: number; height: number }> {if (!isKtx2Path(staged)) {const decoded = await decodePixels(staged);- return { handle: createTextureFromPixels(module, decoded, false), ...decoded };+ return { handle: createTextureFromPixels(module, decoded, TextureContent.Retained, false), ...decoded };}const bytes = new Uint8Array(await fetchBinary(staged));const rm = requireResourceManager();@@ -112,12 +112,13 @@ export async function createAtlasPageTexture(const rgba = transcoder.transcodeToRgba(bytes);if (!rgba) throw new Error(`KTX2 transcode failed: ${staged}`);const decoded = { width: rgba.width, height: rgba.height, pixels: rgba.data };- return { handle: createTextureFromPixels(module, decoded, false), ...decoded };+ return { handle: createTextureFromPixels(module, decoded, TextureContent.Retained, false), ...decoded };}export function createTextureFromPixels(module: ESEngineModule | null,result: { width: number; height: number; pixels: Uint8Array },+ content: TextureContent,flipY: boolean = true,params?: TextureParams,): number {@@ -130,7 +131,7 @@ export function createTextureFromPixels(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);+ return rm.createTextureFromBytes(result.width, result.height, result.pixels, format, flipY, content, filter, wrap);}if (!module) {throw new Error('createTextureFromPixels: a wasm module is required for the heap upload path');@@ -141,9 +142,9 @@ export function createTextureFromPixels(if (params && (params.filterMode || params.wrapMode) && rm.createTextureEx) {const filter = FILTER_MODE_MAP[params.filterMode ?? 'linear'] ?? 1;const wrap = WRAP_MODE_MAP[params.wrapMode ?? 'clamp'] ?? 1;- return rm.createTextureEx(result.width, result.height, ptr, result.pixels.length, format, flipY, filter, wrap);+ return rm.createTextureEx(result.width, result.height, ptr, result.pixels.length, format, flipY, filter, wrap, content);}- return rm.createTexture(result.width, result.height, ptr, result.pixels.length, format, flipY);+ return rm.createTexture(result.width, result.height, ptr, result.pixels.length, format, flipY, content);});}diff --git a/sdk/src/ui/text/atlas-page-store.ts b/sdk/src/ui/text/atlas-page-store.tsindex f6b7ee2d9..3af20b28d 100644--- a/sdk/src/ui/text/atlas-page-store.ts+++ b/sdk/src/ui/text/atlas-page-store.ts@@ -7,7 +7,7 @@* page id IS the texture handle, so the text* renderer can pass it straight to submitTextBatch as the atlas texture.*/-import type { ESEngineModule } from '../../wasm';+import { TextureContent, type ESEngineModule } from '../../wasm';import { createTextureFromPixels, updateTextureSubregion } from '../../runtime/runtimeAssets';import { requireResourceManager } from '../../wasm/resourceManager';import type { AtlasPageStore } from './glyph-atlas';@@ -28,6 +28,7 @@ export class EngineAtlasPageStore implements AtlasPageStore {const handle = createTextureFromPixels(this.module,{ width: size, height: size, pixels },+ TextureContent.Retained,/* flipY */ false,{ filterMode: 'linear', wrapMode: 'clamp' },);diff --git a/sdk/src/video/WasmVideoBackend.ts b/sdk/src/video/WasmVideoBackend.tsindex 6de742004..1820789ab 100644--- a/sdk/src/video/WasmVideoBackend.ts+++ b/sdk/src/video/WasmVideoBackend.ts@@ -18,7 +18,7 @@* arriving late. Muted streams, silent videos, and a track that ends* before the last frame all drive on the engine wall clock instead.*/-import type { ESEngineModule } from '../wasm';+import { TextureContent, type ESEngineModule } from '../wasm';import type { PlatformVideoBackend, VideoBackendContext, VideoStreamHandle, VideoStreamOptions } from './PlatformVideoBackend';import type { SideModule } from '../sideModules/host';import type { AudioAPI } from '../audio/Audio';@@ -323,6 +323,7 @@ class WasmVideoStreamHandle implements VideoStreamHandle {this.texture_ = createTextureFromPixels(module,{ width: this.width_, height: this.height_, pixels },+ TextureContent.Video,/* flipY */ false,{ filterMode: 'linear', wrapMode: 'clamp' },);diff --git a/sdk/src/video/WebVideoBackend.ts b/sdk/src/video/WebVideoBackend.tsindex ba5260776..14049eb20 100644--- a/sdk/src/video/WebVideoBackend.ts+++ b/sdk/src/video/WebVideoBackend.ts@@ -3,7 +3,7 @@// Browser / Electron video backend. An HTMLVideoElement streams and decodes;// on WebGL2 each frame is texImage2D'd straight onto the engine context// (zero-copy), else a canvas readback feeds updateTextureSubregion (WebGPU).-import type { ESEngineModule } from '../wasm';+import { TextureContent, type ESEngineModule } from '../wasm';import type { PlatformVideoBackend, VideoStreamHandle, VideoStreamOptions } from './PlatformVideoBackend';import { createTextureFromPixels, updateTextureSubregion } from '../runtime/runtimeAssets';import { requireResourceManager } from '../wasm/resourceManager';@@ -173,7 +173,7 @@ class WebVideoStreamHandle implements VideoStreamHandle {pool[id] = tex;this.glTexId_ = id;this.glPool_ = pool;- this.texture_ = requireResourceManager().registerExternalTexture(id, this.width_, this.height_);+ this.texture_ = requireResourceManager().registerExternalTexture(id, this.width_, this.height_, TextureContent.Video);}private uploadCPU_(module: ESEngineModule): void {@@ -192,6 +192,7 @@ class WebVideoStreamHandle implements VideoStreamHandle {this.texture_ = createTextureFromPixels(module,{ width: this.width_, height: this.height_, pixels },+ TextureContent.Video,/* flipY */ false,{ filterMode: 'linear', wrapMode: 'clamp' },);diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 2d9ebf8cd..31365c48a 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -43,16 +43,41 @@ export interface CppRegistry extends GeneratedRegistry {// C++ Resource Manager// =============================================================================+/**+ * Who refills a texture after a device loss, stated by whoever creates it —+ * mirroring the engine's `resource::ResourceContent`.+ */+export const TextureContent = {+ /** Rewritten before every use (a decoded video frame). */+ Transient: 0,+ /** The engine keeps the bytes (a glyph page). */+ Retained: 1,+ /** The asset layer loads it again from its path. */+ Asset: 2,+ /** Redrawn from the canvas it mirrors. */+ Canvas: 3,+ /** Refilled by the video it shows. */+ Video: 4,+} as const;+export type TextureContent = typeof TextureContent[keyof typeof TextureContent];++/** A content code's name, for a log that says what could not be refilled. */+export function textureContentName(content: TextureContent): string {+ const entry = Object.entries(TextureContent).find(([, code]) => code === content);+ return entry ? entry[0] : `content ${content}`;+}+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;+ /** `content` is a {@link TextureContent}: who refills the texture after a device loss. */+ createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, content: TextureContent): number;+ createTextureEx(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number, content: TextureContent): 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;+ createTextureFromBytes?(width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, content: TextureContent, filterMode?: number, wrapMode?: number): number;/** Transcode + upload a KTX2/Basis container to a device-supported compressed* format (or RGBA32). Native only (the basis transcoder lives in the host);* the web KTX2 path is WebGL2 + the wasm transcoder instead. */@@ -70,53 +95,39 @@ export interface CppResourceManager {/** Uploads pre-transcoded blocks (level 0 first) as one compressed texture,* whichever backend is running. Absent on an older wasm build. */createCompressedTexture?(width: number, height: number, format: number,- dataPtr: number, dataLen: number, mipLevels: number): number;+ dataPtr: number, dataLen: number, mipLevels: number,+ content: TextureContent): 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;+ registerExternalTexture(glTextureId: number, width: number, height: number, content: TextureContent): number;/** Like registerExternalTexture, but with the actual GPU byte size for the* eviction budget (compressed textures are 4–8× smaller than the RGBA8* estimate the plain variant books). */- registerExternalTextureSized(glTextureId: number, width: number, height: number, bytes: number): number;+ registerExternalTextureSized(glTextureId: number, width: number, height: number, bytes: number, content: TextureContent): number;+ /** A resource handle for a device texture another owner keeps (a render target's colour). */+ wrapDeviceTexture?(textureId: number, width: number, height: number): number;/**- * Point an EXISTING texture handle at a freshly uploaded GPU object, so a- * re-upload after a device loss is invisible to everything holding it.- * Optional: absent on an older wasm build.- */- retargetExternalTexture?(handle: number, glTextureId: number, width: number, height: number): boolean;- /**- * The textures still parked on the placeholder after a loss, one- * `handle|path` per line. A blank path is a texture the asset layer never- * loaded — a render target, a glyph atlas — so it is not one to fetch.- * Optional: absent on an older wasm build.+ * The textures the device is waiting for content for, one+ * `handle|content|path` per line; `content` is the {@link TextureContent}+ * that refills it. Optional: absent on an older wasm build.*/texturesAwaitingReupload?(): string;+ /** Give up on an owed texture's content: it keeps blank storage. */+ forgoTextureContent?(handle: number): void;/**- * 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.+ * Move a freshly loaded texture's pixels behind an owed handle; the source+ * is left empty for its release. Optional: absent on an older wasm build.*/adoptTextureContent?(target: number, source: number): boolean;/**- * The meshes whose GPU realization died with the device, as comma-separated- * handle ids. No path travels with them: the engine never knew one, and the- * asset layer holds the provenance. Optional: absent on an older wasm build.- */- meshesAwaitingRemat?(): string;- /**- * Meshes the loss ended for good — host-only geometry no source can replay.- * Reported rather than skipped, so recovery cannot count them as recovered.- * Optional: absent on an older wasm build.- */- meshesLostNonRecoverable?(): number;- /**- * Every live mesh as `handle:generation:realized`. Identity and realization- * read apart: from outside, a mesh that came back and one that was replaced- * by a new handle both simply draw, and only these tell them apart.+ * Replayable meshes still owed their geometry, as comma-separated handle+ * ids. No path travels with them: the asset layer holds the provenance.* Optional: absent on an older wasm build.*/+ meshesAwaitingRemat?(): string;+ /** Every live mesh as `handle:realized`. Optional: absent on an older wasm build. */meshRealizations?(): string;getTextureGLId(handle: number): number;getTextureDimensions(handle: number): { width: number; height: number } | null;@@ -344,11 +355,6 @@ export interface ESEngineModule {* one; the next {@link recoverDevice} adopts it. WebGL2 answers false.*/provideReplacementDevice?(): boolean;- /**- * End recovery — the engine decides whether it actually ended. Returns how- * many textures are still on the placeholder; 0 means the device is Live.- */- markDeviceRestored?(): number;/*** UI draw order of an entity (its UIVisual.uiOrder, assigned by the UI* render-order pass), so SDF text quads interleave with UI quads. -1 if thediff --git a/sdk/tests/canvas-texture.test.ts b/sdk/tests/canvas-texture.test.tsindex dd126162a..38657211a 100644--- a/sdk/tests/canvas-texture.test.ts+++ b/sdk/tests/canvas-texture.test.ts@@ -11,7 +11,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { initResourceManager, shutdownResourceManager } from '../src/wasm/resourceManager';import { setLinearColorSpace } from '../src/ecs/env';import { createCanvasTexture } from '../src/asset/canvasTexture';-import type { ESEngineModule } from '../src/wasm';+import { TextureContent, type ESEngineModule } from '../src/wasm';import type { App } from '../src/app/app';const SRGB8_ALPHA8 = 0x8c43;@@ -79,7 +79,7 @@ describe('createCanvasTexture', () => {expect(tex.width).toBe(256);expect(tex.height).toBe(128);expect(gl.texImage2D).toHaveBeenCalledTimes(1);- expect(registerExternalTexture).toHaveBeenCalledWith(7, 256, 128);+ expect(registerExternalTexture).toHaveBeenCalledWith(7, 256, 128, TextureContent.Canvas);});it('keeps the handle across a re-take — a component is holding it', () => {diff --git a/sdk/tests/compressed-texture.test.ts b/sdk/tests/compressed-texture.test.tsindex 21d998aac..124d587c3 100644--- a/sdk/tests/compressed-texture.test.ts+++ b/sdk/tests/compressed-texture.test.ts@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { initResourceManager, shutdownResourceManager } from '../src/wasm/resourceManager';+import { TextureContent } from '../src/wasm';import {isKtx2,chooseTargetFormat,@@ -123,7 +124,7 @@ describe('loadCompressedTexture', () => {// internalformat arg = the ASTC extension constantexpect(gl.compressedTexImage2D.mock.calls[0][2]).toBe(ASTC);expect(gl.texImage2D).not.toHaveBeenCalled();- expect(registerExternalTexture).toHaveBeenCalledWith(7, 4, 4);+ expect(registerExternalTexture).toHaveBeenCalledWith(7, 4, 4, TextureContent.Asset);expect(r).toEqual({handle: 42, width: 4, height: 4,decision: {@@ -209,7 +210,7 @@ describe('GPU byte accounting', () => {// 4×4 ASTC block data is 8 bytes here vs a 64-byte RGBA8 estimate.loadCompressedTexture(gl as never, makeModule() as never, makeTranscoder(), KTX2_HEADER);- expect(registerExternalTextureSized).toHaveBeenCalledWith(7, 4, 4, 8);+ expect(registerExternalTextureSized).toHaveBeenCalledWith(7, 4, 4, 8, TextureContent.Asset);expect(registerExternalTexture).not.toHaveBeenCalled();});@@ -217,7 +218,7 @@ describe('GPU byte accounting', () => {const gl = makeGl(); // no compressed support → RGBA pathloadCompressedTexture(gl as never, makeModule() as never, makeTranscoder(), KTX2_HEADER);- expect(registerExternalTexture).toHaveBeenCalledWith(7, 4, 4);+ expect(registerExternalTexture).toHaveBeenCalledWith(7, 4, 4, TextureContent.Asset);expect(registerExternalTextureSized).not.toHaveBeenCalled();});});diff --git a/sdk/tests/native-assets.test.ts b/sdk/tests/native-assets.test.tsindex 70ce759f3..fdde31b64 100644--- a/sdk/tests/native-assets.test.ts+++ b/sdk/tests/native-assets.test.ts@@ -17,6 +17,7 @@ import { builtinMeshTemplate } from '../src/asset/builtinMeshes';import { createNativeResourceManager } from '../src/ecs/bridge/nativeResourceManager';import { Assets } from '../src/asset/AssetPlugin';import { shutdownResourceManager } from '../src/wasm/resourceManager';+import { TextureContent } from '../src/wasm';import { setPlatform } from '../src/platform/base';import type { NativeBridge } from '../src/platform/native/bridge';@@ -91,11 +92,11 @@ describe('createNativeResourceManager', () => {const rm = createNativeResourceManager(scope);const px = new Uint8Array([1, 2, 3, 4]);- const handle = rm.createTextureFromBytes!(1, 1, px, 1, true);+ const handle = rm.createTextureFromBytes!(1, 1, px, 1, true, TextureContent.Asset);expect(handle).toBe(1);// Byte count beside the buffer, and the plain path's defaults where the// caller gave no import settings (filter Linear, wrap ClampToEdge).- expect(createSpy).toHaveBeenCalledWith(1, 1, px, px.length, 1, true, 1, 1);+ expect(createSpy).toHaveBeenCalledWith(1, 1, px, px.length, 1, true, 1, 1, TextureContent.Asset);expect(rm.getTextureDimensions(handle)).toEqual({ width: 1, height: 1 });rm.releaseTexture(handle);@@ -105,8 +106,8 @@ describe('createNativeResourceManager', () => {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/);+ expect(() => rm.createTexture(1, 1, 0, 4, 1, true, TextureContent.Asset)).toThrow(/not supported/);+ expect(() => rm.registerExternalTexture(0, 1, 1, TextureContent.Asset)).toThrow(/not supported/);});});diff --git a/sdk/tests/renderTexture.test.ts b/sdk/tests/renderTexture.test.tsindex 55bd3febd..b4abbdbe8 100644--- a/sdk/tests/renderTexture.test.ts+++ b/sdk/tests/renderTexture.test.ts@@ -144,15 +144,15 @@ describe('RenderTexture', () => {});describe('resize with a live resource manager', () => {- let registerExternalTexture: ReturnType<typeof vi.fn>;+ let wrapDeviceTexture: ReturnType<typeof vi.fn>;let releaseTexture: ReturnType<typeof vi.fn>;beforeEach(() => {let nextTexture = 700;- registerExternalTexture = vi.fn(() => nextTexture++);+ wrapDeviceTexture = vi.fn(() => nextTexture++);releaseTexture = vi.fn();initResourceManager({- registerExternalTexture,+ wrapDeviceTexture,releaseTexture,getTextureDimensions: vi.fn(),} as unknown as CppResourceManager);@@ -175,7 +175,7 @@ describe('RenderTexture', () => {const resized = RenderTexture.resize(rt, 128, 128);expect(resized.texture).toBe(701);- expect(registerExternalTexture).toHaveBeenCalledTimes(2);+ expect(wrapDeviceTexture).toHaveBeenCalledTimes(2);});});diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cppindex 21a8ac8ca..998f0fb10 100644--- a/src/esengine/bindings/ResourceManagerBindings.cpp+++ b/src/esengine/bindings/ResourceManagerBindings.cpp@@ -37,18 +37,19 @@ TextureFormat boundaryTextureFormat(i32 format) {} // namespaceu32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,- uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY) {+ uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY, u32 content) {const u8* pixels = boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_createTexture");if (!pixels) return 0;ConstSpan<u8> pixelSpan(pixels, pixelsLen);- auto handle = rm.createTexture(width, height, pixelSpan, boundaryTextureFormat(format), flipY);+ auto handle = rm.createTexture(static_cast<resource::ResourceContent>(content), width, height,+ pixelSpan, boundaryTextureFormat(format), flipY);return handle.id();}u32 rm_createTextureEx(resource::ResourceManager& rm, u32 width, u32 height,uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY,- i32 filterMode, i32 wrapMode) {+ i32 filterMode, i32 wrapMode, u32 content) {const u8* pixels = pixelsPtr ? boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_createTextureEx") : nullptr;if (pixelsPtr && !pixels) return 0;@@ -70,7 +71,7 @@ u32 rm_createTextureEx(resource::ResourceManager& rm, u32 width, u32 height,default: spec.wrapS = TextureWrap::ClampToEdge; spec.wrapT = TextureWrap::ClampToEdge; break;}- auto handle = rm.createTexture(spec);+ auto handle = rm.createTexture(static_cast<resource::ResourceContent>(content), spec);if (!handle.isValid()) {return 0;}@@ -103,11 +104,11 @@ bool rm_supportsCompressedFormat(resource::ResourceManager& rm, i32 format) {/** Uploads pre-transcoded blocks (level 0 first) as one compressed texture. */u32 rm_createCompressedTexture(resource::ResourceManager& rm, u32 width, u32 height,- i32 format, uintptr_t dataPtr, u32 dataLen, u32 mipLevels) {+ i32 format, uintptr_t dataPtr, u32 dataLen, u32 mipLevels, u32 content) {if (format < 0 || format > static_cast<i32>(GfxCompressedFormat::S3TC_DXT5_SRGB)) return 0;const u8* data = boundarySpan<u8>(dataPtr, dataLen, "rm_createCompressedTexture");if (!data) return 0;- auto handle = rm.createCompressedTexture(width, height,+ auto handle = rm.createCompressedTexture(static_cast<resource::ResourceContent>(content), width, height,static_cast<GfxCompressedFormat>(format),ConstSpan<u8>(data, dataLen),mipLevels ? mipLevels : 1);@@ -121,14 +122,18 @@ u32 rm_createShader(resource::ResourceManager& rm,}u32 rm_registerExternalTexture(resource::ResourceManager& rm, u32 glTextureId,- u32 width, u32 height) {- auto handle = rm.registerExternalTexture(glTextureId, width, height);+ u32 width, u32 height, u32 content) {+ auto handle = rm.registerExternalTexture(static_cast<resource::ResourceContent>(content),+ glTextureId, width, height);return handle.id();}-bool rm_retargetExternalTexture(resource::ResourceManager& rm, u32 handle,- u32 glTextureId, u32 width, u32 height) {- return rm.retargetExternalTexture(resource::TextureHandle(handle), glTextureId, width, height);+u32 rm_wrapDeviceTexture(resource::ResourceManager& rm, u32 textureId, u32 width, u32 height) {+ return rm.wrapDeviceTexture(TextureHandle{textureId}, width, height).id();+}++void rm_forgoTextureContent(resource::ResourceManager& rm, u32 handle) {+ rm.forgoTextureContent(resource::TextureHandle(handle));}bool rm_adoptTextureContent(resource::ResourceManager& rm, u32 target, u32 source) {@@ -136,15 +141,16 @@ bool rm_adoptTextureContent(resource::ResourceManager& rm, u32 target, u32 sourc}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 —- // it lets the caller tell "not mine" from "mine and I failed".+ // One crossing: a loss owes every sourced texture at once, so a call per+ // handle is a call per texture.std::string out;- for (resource::TextureHandle handle : rm.texturesAwaitingReupload()) {+ for (const auto& owed : rm.texturesAwaitingReupload()) {if (!out.empty()) out += '\n';- out += std::to_string(handle.id());+ out += std::to_string(owed.handle.id());+ out += '|';+ out += std::to_string(static_cast<u32>(owed.content));out += '|';- out += rm.getTexturePath(handle);+ out += rm.getTexturePath(owed.handle);}return out;}@@ -164,21 +170,15 @@ std::string rm_meshRealizations(resource::ResourceManager& rm) {if (!out.empty()) out += ',';out += std::to_string(row.handle);out += ':';- out += std::to_string(row.generation);- out += ':';out += row.realized ? '1' : '0';}return out;}-u32 rm_meshesLostNonRecoverable(resource::ResourceManager& rm) {- return rm.meshesLostNonRecoverable();-}-u32 rm_registerExternalTextureSized(resource::ResourceManager& rm, u32 glTextureId,- u32 width, u32 height, u32 bytes) {- auto handle = rm.registerExternalTexture(glTextureId, width, height,- static_cast<usize>(bytes));+ u32 width, u32 height, u32 bytes, u32 content) {+ auto handle = rm.registerExternalTexture(static_cast<resource::ResourceContent>(content),+ glTextureId, width, height, static_cast<usize>(bytes));return handle.id();}diff --git a/src/esengine/bindings/ResourceManagerBindings.hpp b/src/esengine/bindings/ResourceManagerBindings.hppindex 05dfb9b93..f7eca633b 100644--- a/src/esengine/bindings/ResourceManagerBindings.hpp+++ b/src/esengine/bindings/ResourceManagerBindings.hpp@@ -18,11 +18,12 @@ namespace emscripten {namespace esengine {+/** A texture's `content` is a resource::ResourceContent: who refills it after a device loss. */u32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,- uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY);+ uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY, u32 content);u32 rm_createTextureEx(resource::ResourceManager& rm, u32 width, u32 height,uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY,- i32 filterMode, i32 wrapMode);+ i32 filterMode, i32 wrapMode, u32 content);u32 rm_createShader(resource::ResourceManager& rm,const std::string& vertSrc, const std::string& fragSrc);/** Whether the active backend samples this compressed format. */@@ -30,34 +31,32 @@ bool rm_supportsCompressedFormat(resource::ResourceManager& rm, i32 format);/** Uploads pre-transcoded blocks as one compressed texture. */u32 rm_createCompressedTexture(resource::ResourceManager& rm, u32 width, u32 height,- i32 format, uintptr_t dataPtr, u32 dataLen, u32 mipLevels);+ i32 format, uintptr_t dataPtr, u32 dataLen, u32 mipLevels, u32 content);u32 rm_registerExternalTexture(resource::ResourceManager& rm, u32 glTextureId,- u32 width, u32 height);-/** @brief Points an EXISTING texture handle at a freshly uploaded GPU object. */-bool rm_retargetExternalTexture(resource::ResourceManager& rm, u32 handle,- u32 glTextureId, u32 width, u32 height);+ u32 width, u32 height, u32 content);-/** @brief The textures still parked on the placeholder, as `handle|path` lines. */+/** @brief A resource handle for a device texture another owner keeps (a render target's colour). */+u32 rm_wrapDeviceTexture(resource::ResourceManager& rm, u32 textureId, u32 width, u32 height);++/** @brief Gives up on an owed texture's content; it keeps blank storage. */+void rm_forgoTextureContent(resource::ResourceManager& rm, u32 handle);++/** @brief The textures the device is waiting for content for, as `handle|content|path` lines. */std::string rm_texturesAwaitingReupload(resource::ResourceManager& rm);-/** @brief Moves a freshly loaded texture's GPU object onto an existing handle. */+/** @brief Moves a freshly loaded texture's pixels behind an owed handle. */bool rm_adoptTextureContent(resource::ResourceManager& rm, u32 target, u32 source);-/** @brief Meshes whose realization is gone, as comma-separated handle ids. No+/** @brief Replayable meshes still owed their geometry, as comma-separated handle ids. No* path: the engine never knew one, and the asset layer holds it. */std::string rm_meshesAwaitingRemat(resource::ResourceManager& rm);-/** @brief Every live mesh as `handle:generation:realized`, so a criterion can- * tell a mesh that CAME BACK from one that was replaced. */+/** @brief Every live mesh as `handle:realized`. */std::string rm_meshRealizations(resource::ResourceManager& rm);-/** @brief Meshes the last loss ended for good — host-only geometry no source- * can replay. Reported so recovery cannot call them recovered. */-u32 rm_meshesLostNonRecoverable(resource::ResourceManager& rm);-u32 rm_registerExternalTextureSized(resource::ResourceManager& rm, u32 glTextureId,- u32 width, u32 height, u32 bytes);+ u32 width, u32 height, u32 bytes, u32 content);void rm_releaseTexture(resource::ResourceManager& rm, u32 handleId);u32 rm_getTextureRefCount(resource::ResourceManager& rm, u32 handleId);void rm_registerTextureWithPath(resource::ResourceManager& rm, u32 handleId, const std::string& path);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 279f8364a..e4f09d1b2 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -327,25 +327,13 @@ bool provideReplacementDevice() {}/**- * @brief Rebuilds the renderer after a loss; see EstellaContext::recoverDevice.- * @details Leaves the device Recovering — drawable, but its textures are- * placeholders until the asset layer re-uploads and calls- * markDeviceRestored.+ * @brief Rebuilds the device and everything it issued; see GfxDevice::recoverDevice.+ * @details The device stays Recovering, drawing, until the content it is owed+ * has been refilled or given up on, then turns Live by itself.*/bool recoverDevice() {- return g_activeContext ? g_activeContext->recoverDevice() : false;-}--/**- * @brief Ends recovery, and answers whether it actually ended.- * @details Routed through the context rather than straight to the device: the- * device cannot see the textures still parked on the placeholder, and- * the context is the one layer that knows both. Reaching for the- * device here is the shorter path that skips the only criterion.- * @return Textures still awaiting re-upload; 0 means the device is Live.- */-u32 markDeviceRestored() {- return g_activeContext ? g_activeContext->finishDeviceRecovery() : 0;+ GfxDevice* device = activeGfxDevice();+ return device && device->recoverDevice();}/**@@ -481,7 +469,6 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("notifyDeviceLost", &esengine::notifyDeviceLost);emscripten::function("recoverDevice", &esengine::recoverDevice);emscripten::function("provideReplacementDevice", &esengine::provideReplacementDevice);- emscripten::function("markDeviceRestored", &esengine::markDeviceRestored);emscripten::class_<esengine::resource::ResourceManager>("ResourceManager").function("createTexture", &esengine::rm_createTexture)@@ -491,10 +478,10 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {.function("createCompressedTexture", &esengine::rm_createCompressedTexture).function("registerExternalTexture", &esengine::rm_registerExternalTexture).function("registerExternalTextureSized", &esengine::rm_registerExternalTextureSized)- .function("retargetExternalTexture", &esengine::rm_retargetExternalTexture)+ .function("wrapDeviceTexture", &esengine::rm_wrapDeviceTexture).function("texturesAwaitingReupload", &esengine::rm_texturesAwaitingReupload)+ .function("forgoTextureContent", &esengine::rm_forgoTextureContent).function("meshesAwaitingRemat", &esengine::rm_meshesAwaitingRemat)- .function("meshesLostNonRecoverable", &esengine::rm_meshesLostNonRecoverable).function("meshRealizations", &esengine::rm_meshRealizations).function("adoptTextureContent", &esengine::rm_adoptTextureContent).function("releaseTexture", &esengine::rm_releaseTexture)diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cppindex 7d4397590..11680fcf7 100644--- a/src/esengine/core/EstellaContext.cpp+++ b/src/esengine/core/EstellaContext.cpp@@ -114,51 +114,6 @@ bool EstellaContext::init(Unique<GfxDevice> device) {return true;}-bool EstellaContext::recoverDevice() {- auto* device = services_.getService<GfxDevice>();- if (!device || !device->recoverDevice()) return false;-- // The order is the substance. Shaders first: every program id cached- // downstream is read back from these handles. RenderContext next, because- // its white texture is the placeholder the textures get swept onto.- auto* resources = services_.getService<resource::ResourceManager>();- auto* renderContext = services_.getService<RenderContext>();- if (!resources || !renderContext) return false;-- resources->recreateGpuShaders();- renderContext->recreateGpuResources();- renderContext->materials().refreshShaderPrograms(*resources);-- if (auto* immediateDraw = services_.getService<ImmediateDraw>()) {- immediateDraw->recreateGpuResources();- }- if (auto* renderFrame = services_.getService<RenderFrame>()) {- renderFrame->recreateGpuResources();- }-- // Last: the placeholder now exists to park them on. Their CONTENT is still- // missing, which is why this leaves the device Recovering, not Live.- resources->invalidateGpuTextures(renderContext->getWhiteTexture());- // Meshes have no placeholder to park on — geometry cannot be stood in for —- // so they lose their realization outright and the draw path skips them until- // a source replaces it.- resources->invalidateGpuMeshes();- return true;-}--u32 EstellaContext::finishDeviceRecovery() {- auto* resources = services_.getService<resource::ResourceManager>();- // Both debts, not just the textures: a device declared Live with geometry- // still missing is a screen with holes in it reporting that it recovered.- const u32 pending = resources- ? static_cast<u32>(resources->texturesAwaitingReupload().size()- + resources->meshesAwaitingRematerialization().size())- : 0;- if (pending > 0) return pending;- if (auto* device = services_.getService<GfxDevice>()) device->markDeviceRestored();- return 0;-}-void EstellaContext::initSubsystems(Unique<GfxDevice> gfxDevice) {// The device arrives first: ResourceManager (the GPU-resource factory) and// every other renderer subsystem borrow this single device. Which backend@@ -168,14 +123,8 @@ 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([this](const GfxDeviceLostInfo& info) {+ gfxDevicePtr->setDeviceLostHandler([](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/core/EstellaContext.hpp b/src/esengine/core/EstellaContext.hppindex 0868039fc..433b1d1d2 100644--- a/src/esengine/core/EstellaContext.hpp+++ b/src/esengine/core/EstellaContext.hpp@@ -47,26 +47,6 @@ public:*/bool init(Unique<GfxDevice> device);- /**- * @brief Brings the renderer back after a device loss.- * @details Rebuilds the device, then every subsystem that owns GPU objects,- * in the one order that works (see the definition). Leaves the- * device Recovering: it draws, but its textures are placeholders- * until the asset layer re-uploads them.- * @return True when the renderer is usable again.- */- bool recoverDevice();-- /**- * @brief Ends recovery — if the content is actually back.- * @details The engine holds the criterion, so declaring the device whole is- * not the caller's to assert: one that restored half its textures- * would report Live and draw the rest white, the hardest state to- * read — the report says healthy and the screen disagrees.- * @return Textures still on the placeholder; 0 means the device is Live.- */- u32 finishDeviceRecovery();-/*** @brief Shut down all subsystems and release resources*/diff --git a/src/esengine/renderer/draw/CustomGeometry.cpp b/src/esengine/renderer/draw/CustomGeometry.cppindex cd3903e6c..0c281d4c9 100644--- a/src/esengine/renderer/draw/CustomGeometry.cpp+++ b/src/esengine/renderer/draw/CustomGeometry.cpp@@ -53,10 +53,12 @@ void CustomGeometry::init(GfxDevice& device, const f32* vertices, u32 vertexCounvertexCount_ = vertexCount * sizeof(f32) / stride_;if (dynamic) {- vbo_ = Shared<VertexBuffer>(VertexBuffer::create(device, vertexCount * sizeof(f32)));+ vbo_ = Shared<VertexBuffer>(VertexBuffer::create(device, GfxContent::retained(),+ vertexCount * sizeof(f32)));vbo_->setDataRaw(vertices, vertexCount * sizeof(f32));} else {- vbo_ = Shared<VertexBuffer>(VertexBuffer::createRaw(device, vertices, vertexCount * sizeof(f32)));+ vbo_ = Shared<VertexBuffer>(VertexBuffer::createRaw(device, GfxContent::retained(), vertices,+ vertexCount * sizeof(f32)));}vbo_->setLayout(layout);@@ -77,12 +79,12 @@ void CustomGeometry::init(GfxDevice& device, const f32* vertices, u32 vertexCounvoid CustomGeometry::setIndices(const u16* indices, u32 indexCount) {if (!isValid() || !device_) return;- ibo_ = Shared<IndexBuffer>(IndexBuffer::create(*device_, indices, indexCount));+ ibo_ = Shared<IndexBuffer>(IndexBuffer::create(*device_, GfxContent::retained(), indices, indexCount));}void CustomGeometry::setIndices(const u32* indices, u32 indexCount) {if (!isValid() || !device_) return;- ibo_ = Shared<IndexBuffer>(IndexBuffer::create(*device_, indices, indexCount));+ ibo_ = Shared<IndexBuffer>(IndexBuffer::create(*device_, GfxContent::retained(), indices, indexCount));}void CustomGeometry::updateVertices(const f32* vertices, u32 vertexCount, u32 offset) {diff --git a/src/esengine/renderer/draw/ImmediateDraw.cpp b/src/esengine/renderer/draw/ImmediateDraw.cppindex 06718ded7..5ae3cff0a 100644--- a/src/esengine/renderer/draw/ImmediateDraw.cpp+++ b/src/esengine/renderer/draw/ImmediateDraw.cpp@@ -102,18 +102,6 @@ ImmediateDraw::~ImmediateDraw() {}}-void ImmediateDraw::recreateGpuResources() {- if (!initialized_) return;- pool_.recreateGpuResources();- white_texture_id_ = context_.getWhiteTextureId();- // NOT re-created: the manager re-compiled it behind the same handle, so the- // only stale thing here is the program id cached from it.- batch_shader_ = ShaderHandle::Invalid;- if (Shader* shader = resource_manager_.getShader(batch_shader_ref_)) {- if (shader->isValid()) batch_shader_ = shader->handle();- }-}-void ImmediateDraw::init() {if (initialized_) return;diff --git a/src/esengine/renderer/draw/ImmediateDraw.hpp b/src/esengine/renderer/draw/ImmediateDraw.hppindex 71e7dd0bb..d1aa084dd 100644--- a/src/esengine/renderer/draw/ImmediateDraw.hpp+++ b/src/esengine/renderer/draw/ImmediateDraw.hpp@@ -76,9 +76,6 @@ public:void init();- /// Re-creates the pool's buffers and re-reads the batch program id after a- /// device loss. The shader itself is rebuilt by the manager, behind its handle.- void recreateGpuResources();void shutdown();// =========================================================================diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cppindex abf0c5bbd..68ad1126f 100644--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp@@ -194,25 +194,6 @@ void PostProcessPipeline::shutdown() {ES_LOG_INFO("PostProcessPipeline shutdown");}-void PostProcessPipeline::recreateGpuResources() {- if (!initialized_) return;- // Handles dropped, not deleted; the framebuffers are Unique<> and simply let- // go of objects that no longer exist. ensureFBOs re-creates them at the- // current size on the next frame, exactly as a resize does.- screen_quad_vbo_ = BufferHandle::Invalid;- screen_quad_layout_ = VertexLayoutHandle::Invalid;- sceneTexture_ = TextureHandle::Invalid;- for (auto& pass : passes_) { pass.paramUbo = BufferHandle::Invalid; pass.paramDirty = true; }- for (auto& pass : screenPasses_) { pass.paramUbo = BufferHandle::Invalid; pass.paramDirty = true; }-- if (graph_) graph_->releasePool();- screenFBO_.reset();- sceneResource_ = rg::kNoResource;- screenFBOCreated_ = false;- screenCaptureActive_ = false;- ensureGraph();-}-void PostProcessPipeline::resize(u32 width, u32 height) {if (!initialized_) return;if (width == width_ && height == height_) return;@@ -334,7 +315,8 @@ void PostProcessPipeline::ensureScreenQuad() {-1.0f, 3.0f, 0.0f, 2.0f,};screen_quad_vbo_ = device_.createBuffer(- {GfxBufferUsage::Vertex, static_cast<u32>(sizeof(vertices)), /*dynamic=*/false}, vertices);+ {GfxBufferUsage::Vertex, static_cast<u32>(sizeof(vertices)), /*dynamic=*/false},+ GfxContent::retained(), vertices);VertexLayoutDesc desc;desc.attributeCount = 2;@@ -485,7 +467,7 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContexif (pass.paramUbo == BufferHandle::Invalid) {pass.paramUbo = device->createBuffer({GfxBufferUsage::Uniform, layout->blockSize, /*dynamic=*/true},- pass.paramBytes.data());+ GfxContent::retained(), pass.paramBytes.data());} else {device->updateBuffer(pass.paramUbo, 0, pass.paramBytes.data(),static_cast<u32>(pass.paramBytes.size()));diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hppindex b6c6dcb09..c4d5d2f0d 100644--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp@@ -123,10 +123,6 @@ public:*/void resize(u32 width, u32 height);- /// Rebuilds the intermediates and per-pass buffers after a device loss. The- /// blit shader is not re-created — the manager rebuilt it behind its handle.- void recreateGpuResources();-/*** @brief Adds a post-processing pass* @param name Unique name for the passdiff --git a/src/esengine/renderer/frame/RenderContext.cpp b/src/esengine/renderer/frame/RenderContext.cppindex 0548b37bd..146d9e847 100644--- a/src/esengine/renderer/frame/RenderContext.cpp+++ b/src/esengine/renderer/frame/RenderContext.cpp@@ -83,33 +83,13 @@ void RenderContext::shutdown() {ES_LOG_INFO("RenderContext shutdown");}-void RenderContext::recreateGpuResources() {- if (!initialized_) return;- // Handles are dropped, not deleted: the objects died with the device, and- // asking it to free their ids would look up metadata the backend just wiped.- whiteTexture_ = TextureHandle::Invalid;- blackTexture_ = TextureHandle::Invalid;- flatNormalTexture_ = TextureHandle::Invalid;- frameUbo_ = BufferHandle::Invalid;- timeUbo_ = BufferHandle::Invalid;- drawParamsFallback_ = BufferHandle::Invalid;-- initDefaultTextures();- initFrameUbo();- // The built-ins are new objects, so the materials falling back to them have- // to be told; otherwise every unset texture param samples a dead id.- materials_.setBuiltinDefaults(whiteTexture_, blackTexture_, flatNormalTexture_);- materials_.recreateGpuResources();- lights_.recreateGpuResources();-}-TextureHandle RenderContext::make1x1Texture(u32 rgba) {TextureDesc desc;desc.width = 1;desc.height = 1;desc.minFilter = TextureFilter::Nearest;desc.magFilter = TextureFilter::Nearest;- return device_.createTexture(desc, &rgba);+ return device_.createTexture(desc, GfxContent::retained(), &rgba);}void RenderContext::initDefaultTextures() {@@ -125,7 +105,8 @@ void RenderContext::initDefaultTextures() {void RenderContext::initFrameUbo() {FrameConstants initial{};frameUbo_ = device_.createBuffer(- {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(FrameConstants)), /*dynamic=*/true}, &initial);+ {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(FrameConstants)), /*dynamic=*/true},+ GfxContent::retained(), &initial);// The binding slot persists for the context lifetime; only the contents change// per frame. Every engine shader's FrameConstants block is linked to this slot@@ -134,7 +115,8 @@ void RenderContext::initFrameUbo() {TimeConstants time{};timeUbo_ = device_.createBuffer(- {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(TimeConstants)), /*dynamic=*/true}, &time);+ {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(TimeConstants)), /*dynamic=*/true},+ GfxContent::retained(), &time);device_.setUniformBuffer(TIME_CONSTANTS_BINDING, timeUbo_);// Zeroed fallback for the shared per-draw params slot: a shader whose loose@@ -144,7 +126,8 @@ void RenderContext::initFrameUbo() {// what their loose-uniform ancestors read.const std::vector<u8> zeros(DRAW_PARAMS_FALLBACK_SIZE, 0);drawParamsFallback_ = device_.createBuffer(- {GfxBufferUsage::Uniform, DRAW_PARAMS_FALLBACK_SIZE, /*dynamic=*/false}, zeros.data());+ {GfxBufferUsage::Uniform, DRAW_PARAMS_FALLBACK_SIZE, /*dynamic=*/false},+ GfxContent::retained(), zeros.data());device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);// A pose, a set of shapes, and the indirect light where a draw stands. A POOLdiff --git a/src/esengine/renderer/frame/RenderContext.hpp b/src/esengine/renderer/frame/RenderContext.hppindex 0d7ca550e..c748e3f35 100644--- a/src/esengine/renderer/frame/RenderContext.hpp+++ b/src/esengine/renderer/frame/RenderContext.hpp@@ -84,10 +84,6 @@ public:*/void shutdown();- /// Rebuilds the built-in textures and frame UBOs after a device loss, and- /// re-points the stores that depend on them.- void recreateGpuResources();-/*** @brief Checks if the context is initialized* @return True if init() has been called successfullydiff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 5b594d575..bdd3e4f84 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -203,51 +203,6 @@ void RenderFrame::shutdown() {ES_LOG_INFO("RenderFrame shutdown");}-void RenderFrame::recreateGpuResources() {- pool_.recreateGpuResources();- shadow_pool_.recreateGpuResources();- // The buffers behind these died with the device; the next pass makes as many- // as it needs. Kept here rather than recreated eagerly: how many is a property- // of the frame that has not been collected yet.- releaseShadowFrameUbos();- // The mask's buffer and layout died with the device too, and its shader has to be- // compiled again against the new one. Forgotten rather than deleted: the handles- // name nothing now, and the next frame that needs a mask makes its own.- shadow_2d_vbo_ = BufferHandle::Invalid;- shadow_2d_vbo_bytes_ = 0;- shadow_2d_layout_ = VertexLayoutHandle::Invalid;- shadow_2d_shader_ = {};- shadow_2d_shader_tried_ = false;- target_manager_.recreateGpuResources();- // The framebuffers the pool is holding died with the device: the loans go- // back and the memory behind them goes with it, or the next frame would draw- // its shadows into a handle that names nothing. Re-borrowed on demand.- releaseFrameTargets();- target_pool_.clear();- // The variant handles are unchanged; this re-reads the program ids behind them.- batch_shader_id_ = initBatchShader();-#ifdef ES_ENABLE_POSTPROCESS- if (post_process_) post_process_->recreateGpuResources();-#endif-- // Plugins cache the batch program id at init, and that id died with the- // device — a collect pass would keep keying draws to a program the restored- // context rejects. init() is where they take it, so init() is what runs.- RenderFrameContext ctx{- context_,- resource_manager_,- context_.getWhiteTextureId(),- batch_shader_id_,- RenderStage::Transparent,- glm::mat4(1.0f),- nullptr,- this- };- for (auto& plugin : plugins_) {- plugin->init(ctx);- }-}-void RenderFrame::resize(u32 width, u32 height) {width_ = width;height_ = height;@@ -1746,7 +1701,7 @@ void RenderFrame::ensureShadowFrameUbos(u32 count) {const u32 bytes = RenderContext::frameConstantsSize();while (shadow_frame_ubos_.size() < count) {const BufferHandle ubo = device_.createBuffer(- {GfxBufferUsage::Uniform, bytes, /*dynamic=*/true}, nullptr);+ {GfxBufferUsage::Uniform, bytes, /*dynamic=*/true}, GfxContent::transient(), nullptr);if (ubo == BufferHandle::Invalid) break;shadow_frame_ubos_.push_back(ubo);}diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex 45b9daab8..58b756c8a 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -109,10 +109,6 @@ public:/** Geometry collected for this camera and drawn after its scene. */void setPresentedOverlayDraw(ImmediateDraw* draw) { presented_overlay_draw_ = draw; }- /// Rebuilds everything this frame owns after a device loss: the transient- /// pool, the render targets, the batch program ids and the post-process chain.- void recreateGpuResources();-/** @brief The frame's main-pass load-op: which attachments to clear, the color,* and an optional region (w == 0 = full target — per-camera flows clear* only their viewport on the shared default target). */diff --git a/src/esengine/renderer/frame/RenderFrameShadow2D.cpp b/src/esengine/renderer/frame/RenderFrameShadow2D.cppindex fe77f27da..2284c3f23 100644--- a/src/esengine/renderer/frame/RenderFrameShadow2D.cpp+++ b/src/esengine/renderer/frame/RenderFrameShadow2D.cpp@@ -334,7 +334,7 @@ void RenderFrame::executeShadow2DPass() {// lights are moving, and a re-create every frame is a re-create every frame.shadow_2d_vbo_bytes_ = std::max(bytes * 2u, 4096u);shadow_2d_vbo_ = device_.createBuffer(- {GfxBufferUsage::Vertex, shadow_2d_vbo_bytes_, /*dynamic=*/true}, nullptr);+ {GfxBufferUsage::Vertex, shadow_2d_vbo_bytes_, /*dynamic=*/true}, GfxContent::transient(), nullptr);if (shadow_2d_vbo_ == BufferHandle::Invalid) return;}device_.updateBuffer(shadow_2d_vbo_, 0, shadow_2d_vertices_.data(), bytes);@@ -521,7 +521,7 @@ void RenderFrame::executeShape2DPass() {if (shape_2d_vbo_ != BufferHandle::Invalid) device_.deleteBuffer(shape_2d_vbo_);shape_2d_vbo_bytes_ = std::max(bytes * 2u, 1024u);shape_2d_vbo_ = device_.createBuffer(- {GfxBufferUsage::Vertex, shape_2d_vbo_bytes_, /*dynamic=*/true}, nullptr);+ {GfxBufferUsage::Vertex, shape_2d_vbo_bytes_, /*dynamic=*/true}, GfxContent::transient(), nullptr);if (shape_2d_vbo_ == BufferHandle::Invalid) return;}device_.updateBuffer(shape_2d_vbo_, 0, shape_2d_vertices_.data(), bytes);diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cppindex 8ce6e5264..4b4a99ca4 100644--- a/src/esengine/renderer/plugins/MeshPlugin.cpp+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp@@ -305,11 +305,9 @@ MeshDrawKeys meshDrawFor(RenderFrameContext& ctx, ecs::Registry& registry, Entit} // namespacevoid MeshPlugin::init(RenderFrameContext& ctx) {- // A rebuild after a lost device runs this again, and every program minted- // against the dead context is gone — so the cache empties here rather than- // handing out ids that name nothing. The RESOURCES are released, not just- // forgotten: a shader nobody holds still sits in the pool, gets recompiled- // on the next loss, and keeps a host program object alive for good.+ // A renderer initialized again runs this on a cache that compiled before. The+ // RESOURCES are released, not just forgotten: a shader nobody holds still+ // sits in the pool and keeps its program alive for good.for (auto& shader : mesh_shaders_) {if (shader.isValid()) ctx.resources.releaseShader(shader);shader = {};diff --git a/src/esengine/renderer/rhi/Buffer.cpp b/src/esengine/renderer/rhi/Buffer.cppindex bca956482..8bff2b2ad 100644--- a/src/esengine/renderer/rhi/Buffer.cpp+++ b/src/esengine/renderer/rhi/Buffer.cpp@@ -80,17 +80,17 @@ VertexBuffer& VertexBuffer::operator=(VertexBuffer&& other) noexcept {return *this;}-Unique<VertexBuffer> VertexBuffer::createRaw(GfxDevice& device, const void* data, u32 sizeBytes) {+Unique<VertexBuffer> VertexBuffer::createRaw(GfxDevice& device, GfxContent content, const void* data, u32 sizeBytes) {auto buffer = makeUnique<VertexBuffer>();buffer->device_ = &device;- buffer->handle_ = device.createBuffer({GfxBufferUsage::Vertex, sizeBytes, /*dynamic=*/false}, data);+ buffer->handle_ = device.createBuffer({GfxBufferUsage::Vertex, sizeBytes, /*dynamic=*/false}, content, data);return buffer;}-Unique<VertexBuffer> VertexBuffer::create(GfxDevice& device, u32 size) {+Unique<VertexBuffer> VertexBuffer::create(GfxDevice& device, GfxContent content, u32 size) {auto buffer = makeUnique<VertexBuffer>();buffer->device_ = &device;- buffer->handle_ = device.createBuffer({GfxBufferUsage::Vertex, size, /*dynamic=*/true}, nullptr);+ buffer->handle_ = device.createBuffer({GfxBufferUsage::Vertex, size, /*dynamic=*/true}, content, nullptr);return buffer;}@@ -135,23 +135,23 @@ IndexBuffer& IndexBuffer::operator=(IndexBuffer&& other) noexcept {return *this;}-Unique<IndexBuffer> IndexBuffer::create(GfxDevice& device, const u32* indices, u32 count) {+Unique<IndexBuffer> IndexBuffer::create(GfxDevice& device, GfxContent content, const u32* indices, u32 count) {auto buffer = makeUnique<IndexBuffer>();buffer->device_ = &device;buffer->count_ = count;buffer->is16Bit_ = false;buffer->handle_ = device.createBuffer(- {GfxBufferUsage::Index, count * static_cast<u32>(sizeof(u32)), /*dynamic=*/false}, indices);+ {GfxBufferUsage::Index, count * static_cast<u32>(sizeof(u32)), /*dynamic=*/false}, content, indices);return buffer;}-Unique<IndexBuffer> IndexBuffer::create(GfxDevice& device, const u16* indices, u32 count) {+Unique<IndexBuffer> IndexBuffer::create(GfxDevice& device, GfxContent content, const u16* indices, u32 count) {auto buffer = makeUnique<IndexBuffer>();buffer->device_ = &device;buffer->count_ = count;buffer->is16Bit_ = true;buffer->handle_ = device.createBuffer(- {GfxBufferUsage::Index, count * static_cast<u32>(sizeof(u16)), /*dynamic=*/false}, indices);+ {GfxBufferUsage::Index, count * static_cast<u32>(sizeof(u16)), /*dynamic=*/false}, content, indices);return buffer;}diff --git a/src/esengine/renderer/rhi/Buffer.hpp b/src/esengine/renderer/rhi/Buffer.hppindex d62063442..ae4af616a 100644--- a/src/esengine/renderer/rhi/Buffer.hpp+++ b/src/esengine/renderer/rhi/Buffer.hpp@@ -21,6 +21,7 @@// Project includes#include "../../core/Types.hpp"+#include "./GfxContent.hpp"#include "./GfxEnums.hpp"// Standard library@@ -182,21 +183,7 @@ private:// =============================================================================/**- * @brief GPU buffer for vertex data- *- * @details Wraps a GfxDevice vertex buffer object. Supports both static and- * dynamic usage. All GPU work is delegated to the device.- *- * @code- * struct Vertex { float x, y, u, v; };- * std::vector<Vertex> vertices = {...};- *- * auto vbo = VertexBuffer::create(device, std::span(vertices));- * vbo->setLayout({- * {ShaderDataType::Float2, "a_position"},- * {ShaderDataType::Float2, "a_texCoord"}- * });- * @endcode+ * @brief GPU buffer for vertex data, static or dynamic; all GPU work goes through the device.*/class VertexBuffer {public:@@ -221,24 +208,24 @@ public:* @return Unique pointer to the buffer*/template<typename T>- static Unique<VertexBuffer> create(GfxDevice& device, std::span<const T> data) {- return createRaw(device, data.data(), static_cast<u32>(data.size_bytes()));+ static Unique<VertexBuffer> create(GfxDevice& device, GfxContent content, std::span<const T> data) {+ return createRaw(device, content, data.data(), static_cast<u32>(data.size_bytes()));}/*** @brief Creates a static buffer from a vector*/template<typename T>- static Unique<VertexBuffer> create(GfxDevice& device, const std::vector<T>& data) {- return create(device, std::span<const T>(data));+ static Unique<VertexBuffer> create(GfxDevice& device, GfxContent content, const std::vector<T>& data) {+ return create(device, content, std::span<const T>(data));}/*** @brief Creates a static buffer from a C array*/template<typename T, usize N>- static Unique<VertexBuffer> create(GfxDevice& device, const T (&data)[N]) {- return create(device, std::span<const T>(data, N));+ static Unique<VertexBuffer> create(GfxDevice& device, GfxContent content, const T (&data)[N]) {+ return create(device, content, std::span<const T>(data, N));}/**@@ -249,7 +236,7 @@ public:** @details Use setData() to upload data later.*/- static Unique<VertexBuffer> create(GfxDevice& device, u32 sizeBytes);+ static Unique<VertexBuffer> create(GfxDevice& device, GfxContent content, u32 sizeBytes);// =========================================================================// Operations@@ -298,14 +285,6 @@ public:/** @brief Gets the device buffer handle */BufferHandle handle() const { return handle_; }- /**- * @brief Forgets the GPU buffer, which died with its device.- * @details Not a delete: the object is already gone, and asking a dead device- * to free an id it no longer has is at best a no-op. Forgetting it- * is what keeps the destructor from doing exactly that later.- */- void abandonGpuBuffer() { handle_ = BufferHandle::Invalid; }-// =========================================================================// Raw API for internal use only// =========================================================================@@ -317,7 +296,7 @@ public:* @param sizeBytes Size of data in bytes* @return Unique pointer to the buffer*/- static Unique<VertexBuffer> createRaw(GfxDevice& device, const void* data, u32 sizeBytes);+ static Unique<VertexBuffer> createRaw(GfxDevice& device, GfxContent content, const void* data, u32 sizeBytes);/*** @brief Updates buffer data from raw pointer (internal use)@@ -352,7 +331,7 @@ private:** @code* std::vector<u32> indices = {0, 1, 2, 2, 3, 0};- * auto ebo = IndexBuffer::create(device, std::span(indices));+ * auto ebo = IndexBuffer::create(device, GfxContent::retained(), std::span(indices));* @endcode*/class IndexBuffer {@@ -371,34 +350,34 @@ public:// =========================================================================/** @brief Creates an index buffer from a span of 32-bit indices */- static Unique<IndexBuffer> create(GfxDevice& device, std::span<const u32> indices) {- return create(device, indices.data(), static_cast<u32>(indices.size()));+ static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, std::span<const u32> indices) {+ return create(device, content, indices.data(), static_cast<u32>(indices.size()));}/** @brief Creates an index buffer from a span of 16-bit indices */- static Unique<IndexBuffer> create(GfxDevice& device, std::span<const u16> indices) {- return create(device, indices.data(), static_cast<u32>(indices.size()));+ static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, std::span<const u16> indices) {+ return create(device, content, indices.data(), static_cast<u32>(indices.size()));}/** @brief Creates an index buffer from a vector of 32-bit indices */- static Unique<IndexBuffer> create(GfxDevice& device, const std::vector<u32>& indices) {- return create(device, std::span<const u32>(indices));+ static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, const std::vector<u32>& indices) {+ return create(device, content, std::span<const u32>(indices));}/** @brief Creates an index buffer from a vector of 16-bit indices */- static Unique<IndexBuffer> create(GfxDevice& device, const std::vector<u16>& indices) {- return create(device, std::span<const u16>(indices));+ static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, const std::vector<u16>& indices) {+ return create(device, content, std::span<const u16>(indices));}/** @brief Creates an index buffer with 32-bit indices from pointer */- static Unique<IndexBuffer> create(GfxDevice& device, const u32* indices, u32 count);+ static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, const u32* indices, u32 count);/*** @brief Creates an index buffer with 16-bit indices from pointer* @details Use 16-bit indices for better performance when vertex* count is under 65536.*/- static Unique<IndexBuffer> create(GfxDevice& device, const u16* indices, u32 count);+ static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, const u16* indices, u32 count);// =========================================================================// Operations@@ -410,14 +389,6 @@ public:/** @brief Gets the device buffer handle */BufferHandle handle() const { return handle_; }- /**- * @brief Forgets the GPU buffer, which died with its device.- * @details Not a delete: the object is already gone, and asking a dead device- * to free an id it no longer has is at best a no-op. Forgetting it- * is what keeps the destructor from doing exactly that later.- */- void abandonGpuBuffer() { handle_ = BufferHandle::Invalid; }-/** @brief Returns true if using 16-bit indices */bool is16Bit() const { return is16Bit_; }diff --git a/src/esengine/renderer/rhi/Framebuffer.cpp b/src/esengine/renderer/rhi/Framebuffer.cppindex 566f31353..e2f8bf546 100644--- a/src/esengine/renderer/rhi/Framebuffer.cpp+++ b/src/esengine/renderer/rhi/Framebuffer.cpp@@ -124,7 +124,7 @@ bool Framebuffer::initialize() {colorDesc.minFilter = filter;colorDesc.magFilter = filter;colorDesc.samples = samples;- colorAttachment_ = device_->createTexture(colorDesc, nullptr);+ colorAttachment_ = device_->createTexture(colorDesc, GfxContent::transient(), nullptr);TextureDesc depthDesc;depthDesc.width = spec_.width;@@ -134,7 +134,7 @@ bool Framebuffer::initialize() {depthDesc.magFilter = TextureFilter::Nearest;if (spec_.depthStencil) {depthDesc.samples = samples;- depthAttachment_ = device_->createTexture(depthDesc, nullptr);+ depthAttachment_ = device_->createTexture(depthDesc, GfxContent::transient(), nullptr);}// The single-sample twins the multisampled attachments resolve into. They@@ -142,10 +142,10 @@ bool Framebuffer::initialize() {// and no pass or effect has to know it happened.if (samples > 1) {colorDesc.samples = 1;- resolveColor_ = device_->createTexture(colorDesc, nullptr);+ resolveColor_ = device_->createTexture(colorDesc, GfxContent::transient(), nullptr);if (spec_.depthStencil) {depthDesc.samples = 1;- resolveDepth_ = device_->createTexture(depthDesc, nullptr);+ resolveDepth_ = device_->createTexture(depthDesc, GfxContent::transient(), nullptr);}}diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cppindex f1b48da6d..355e61c13 100644--- a/src/esengine/renderer/rhi/GLDevice.cpp+++ b/src/esengine/renderer/rhi/GLDevice.cpp@@ -94,14 +94,6 @@ namespace esengine {namespace {-// A multisampled attachment is a RENDERBUFFER in WebGL2, and renderbuffer ids-// live in their own namespace where id 3 and texture 3 both exist — hence a tag-// bit rather than a lookup that would confuse the two.-constexpr u32 kRenderbufferTag = 0x80000000u;-inline bool isRenderbuffer(u32 handle) { return (handle & kRenderbufferTag) != 0; }-inline GLuint rbId(u32 handle) { return static_cast<GLuint>(handle & ~kRenderbufferTag); }--GLenum toGLFilter(TextureFilter filter) {switch (filter) {case TextureFilter::Nearest: return GL_NEAREST;@@ -311,23 +303,32 @@ void GLDevice::onDeviceLost() {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 (usize id = 0; id < buffer_names_.size(); ++id) {+ GLuint name = buffer_names_[id];+ if (name) glDeleteBuffers(1, &name);}- for (const auto& [id, format] : texture_formats_) {- GLuint name = id;- glDeleteTextures(1, &name);+ for (usize id = 0; id < texture_names_.size(); ++id) {+ GLuint name = texture_names_[id];+ if (!name) continue;+ if (isRenderbuffer(static_cast<u32>(id))) glDeleteRenderbuffers(1, &name);+ else glDeleteTextures(1, &name);}- for (const auto& [id, textures] : framebuffer_textures_) {- GLuint name = id;- glDeleteFramebuffers(1, &name);+ for (usize id = 0; id < framebuffer_names_.size(); ++id) {+ GLuint name = framebuffer_names_[id];+ if (name) glDeleteFramebuffers(1, &name);}- for (const LayoutRecord& rec : layouts_) {- if (rec.vao) {- GLuint name = rec.vao;- glDeleteVertexArrays(1, &name);- }+ for (auto& [id, resolve] : framebuffer_resolve_) {+ if (resolve.destFbo) glDeleteFramebuffers(1, &resolve.destFbo);+ }+ for (usize id = 0; id < program_names_.size(); ++id) {+ if (program_names_[id]) glDeleteProgram(program_names_[id]);+ }+ for (usize id = 0; id < query_names_.size(); ++id) {+ GLuint name = query_names_[id];+ if (name) glDeleteQueries(1, &name);+ }+ for (auto& [id, cache] : vaos_) {+ if (cache.vao) glDeleteVertexArrays(1, &cache.vao);}#endif}@@ -339,33 +340,21 @@ bool GLDevice::recreateDevice() {const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();if (ctx == 0 || emscripten_is_webgl_context_lost(ctx)) 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();+ // Every name belonged to the old context. The registry rebuilds each object+ // behind its id; nothing here survives but the maps' shape.+ buffer_names_.clear();+ texture_names_.clear();+ program_names_.clear();+ framebuffer_names_.clear();+ query_names_.clear();+ framebuffer_resolve_.clear();+ vaos_.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();+ max_samples_ = 0;+ // A timer query in flight was begun on the old context, so the timings are+ // disjoint; the extension itself is enabled per context and must be again.+ timer_query_state_ = 0;+ timer_disjoint_pending_ = true;resetStateCache();init();@@ -373,11 +362,11 @@ bool GLDevice::recreateDevice() {}void GLDevice::resetStateCache() {- current_pipeline_ = PipelineHandle::Invalid;+ current_pipeline_id_ = 0;current_stencil_mode_ = GfxStencilMode::Off;- current_program_ = ShaderHandle::Invalid;+ current_program_name_ = 0;current_blend_ = static_cast<BlendMode>(0xFF);- current_layout_ = VertexLayoutHandle::Invalid;+ current_layout_ = 0;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) {@@ -387,6 +376,8 @@ void GLDevice::resetStateCache() {pending_ibo_ = 0;bound_vao_ = 0;scissor_test_ = -1;+ current_depth_bias_ = 0;+ current_framebuffer_ = 0;timer_query_state_ = 0;}@@ -414,6 +405,11 @@ bool GLDevice::pollDeviceLost() {return false;}+bool GLDevice::isRenderbuffer(u32 textureId) const {+ const TextureDesc* desc = textureDesc(TextureHandle{textureId});+ return desc && desc->samples > 1;+}+// =============================================================================// Viewport & Clear// =============================================================================@@ -573,18 +569,14 @@ void GLDevice::setCullFace(bool front) {// Shader Program// =============================================================================-ShaderHandle GLDevice::createProgram(const GfxShaderSource& source,- const GfxAttribBinding* bindings, u32 bindingCount,- std::string* outLog, GfxShaderStage* outFailedStage) {- if (!isDeviceUsable()) {- if (outLog) *outLog = "device lost";- return ShaderHandle::Invalid;- }+bool GLDevice::backendCreateProgram(u32 id, const GfxShaderSource& source,+ const GfxAttribBinding* bindings, u32 bindingCount,+ std::string* outLog, GfxShaderStage* outFailedStage) {if (source.language != GfxShaderLanguage::GLSL_ES300) {if (outLog) *outLog = "GLDevice compiles GLSL ES 300 only (got another language)";if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;ES_LOG_ERROR("GLDevice::createProgram: unsupported shader language");- return ShaderHandle::Invalid;+ return false;}const char* vertexSrc = source.vertexSrc;const char* fragmentSrc = source.fragmentSrc;@@ -604,7 +596,7 @@ ShaderHandle GLDevice::createProgram(const GfxShaderSource& source,ES_LOG_ERROR("Vertex shader compilation failed: {}", log);setFailure(GfxShaderStage::Vertex, std::move(log));glDeleteShader(vertexShader);- return ShaderHandle::Invalid;+ return false;}GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);@@ -618,7 +610,7 @@ ShaderHandle GLDevice::createProgram(const GfxShaderSource& source,setFailure(GfxShaderStage::Fragment, std::move(log));glDeleteShader(vertexShader);glDeleteShader(fragmentShader);- return ShaderHandle::Invalid;+ return false;}GLuint program = glCreateProgram();@@ -639,64 +631,56 @@ ShaderHandle GLDevice::createProgram(const GfxShaderSource& source,glDeleteShader(vertexShader);glDeleteShader(fragmentShader);glDeleteProgram(program);- return ShaderHandle::Invalid;+ return false;}glDeleteShader(vertexShader);glDeleteShader(fragmentShader);if (outFailedStage) *outFailedStage = GfxShaderStage::None;- ++live_programs_;- return ShaderHandle{program};-}--void GLDevice::deleteProgram(ShaderHandle program) {- if (program != ShaderHandle::Invalid) {- glDeleteProgram(static_cast<GLuint>(program));- if (live_programs_ > 0) --live_programs_;- }-}--void GLDevice::useProgram(ShaderHandle program) {- if (program == current_program_) return;- glUseProgram(static_cast<GLuint>(program));- current_program_ = program;-}--i32 GLDevice::getUniformLocation(ShaderHandle program, const char* name) {- return glGetUniformLocation(static_cast<GLuint>(program), name);-}--i32 GLDevice::getAttribLocation(ShaderHandle program, const char* name) {- return glGetAttribLocation(static_cast<GLuint>(program), name);-}--void GLDevice::setUniform1i(i32 location, i32 value) {- if (location >= 0) glUniform1i(location, value);-}--void GLDevice::setUniform1f(i32 location, f32 value) {- if (location >= 0) glUniform1f(location, value);+ setName(program_names_, id, program);+ return true;}-void GLDevice::setUniform2f(i32 location, f32 x, f32 y) {- if (location >= 0) glUniform2f(location, x, y);+void GLDevice::backendDeleteProgram(u32 id) {+ const u32 name = nameOf(program_names_, id);+ if (!name) return;+ glDeleteProgram(name);+ if (current_program_name_ == name) current_program_name_ = 0;+ setName(program_names_, id, 0);}-void GLDevice::setUniform3f(i32 location, f32 x, f32 y, f32 z) {- if (location >= 0) glUniform3f(location, x, y, z);+void GLDevice::backendUseProgram(u32 id) {+ const u32 name = nameOf(program_names_, id);+ if (name == current_program_name_) return;+ glUseProgram(name);+ current_program_name_ = name;}-void GLDevice::setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) {- if (location >= 0) glUniform4f(location, x, y, z, w);+i32 GLDevice::backendUniformLocation(u32 program, const char* name) {+ const u32 programName = nameOf(program_names_, program);+ return programName ? glGetUniformLocation(programName, name) : -1;}-void GLDevice::setUniformMat3(i32 location, const f32* data) {- if (location >= 0) glUniformMatrix3fv(location, 1, GL_FALSE, data);+i32 GLDevice::backendAttribLocation(u32 program, const char* name) {+ const u32 programName = nameOf(program_names_, program);+ return programName ? glGetAttribLocation(programName, name) : -1;}-void GLDevice::setUniformMat4(i32 location, const f32* data) {- if (location >= 0) glUniformMatrix4fv(location, 1, GL_FALSE, data);+void GLDevice::backendSetUniform(i32 location, const GfxUniformValue& value) {+ if (location < 0) return;+ switch (value.type) {+ case GfxUniformValue::Type::Int: glUniform1i(location, value.i); break;+ case GfxUniformValue::Type::Float: glUniform1f(location, value.f[0]); break;+ case GfxUniformValue::Type::Vec2: glUniform2f(location, value.f[0], value.f[1]); break;+ case GfxUniformValue::Type::Vec3: glUniform3f(location, value.f[0], value.f[1], value.f[2]); break;+ case GfxUniformValue::Type::Vec4:+ glUniform4f(location, value.f[0], value.f[1], value.f[2], value.f[3]);+ break;+ case GfxUniformValue::Type::Mat3: glUniformMatrix3fv(location, 1, GL_FALSE, value.f); break;+ case GfxUniformValue::Type::Mat4: glUniformMatrix4fv(location, 1, GL_FALSE, value.f); break;+ case GfxUniformValue::Type::None: break;+ }}namespace {@@ -723,10 +707,10 @@ GfxUniformType fromGLUniformType(GLenum type) {} // namespace-std::vector<GfxUniformInfo> GLDevice::getActiveUniforms(ShaderHandle program) {+std::vector<GfxUniformInfo> GLDevice::backendActiveUniforms(u32 program) {std::vector<GfxUniformInfo> result;- if (program == ShaderHandle::Invalid) return result;- const GLuint programId = static_cast<GLuint>(program);+ const GLuint programId = nameOf(program_names_, program);+ if (!programId) return result;GLint count = 0;glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &count);@@ -765,107 +749,106 @@ std::vector<GfxUniformInfo> GLDevice::getActiveUniforms(ShaderHandle program) {return result;}+u32 GLDevice::backendUniformBlockIndex(u32 program, const char* name) {+ const u32 programName = nameOf(program_names_, program);+ if (!programName) return GFX_INVALID_UNIFORM_BLOCK;+ return static_cast<u32>(glGetUniformBlockIndex(programName, name));+}++void GLDevice::backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint) {+ const u32 programName = nameOf(program_names_, program);+ if (programName) glUniformBlockBinding(programName, nativeBlockIndex, bindingPoint);+}+// =============================================================================// Buffer Operations// =============================================================================-void GLDevice::uploadBufferStore(BufferHandle buffer, u32 offsetBytes, const void* data,- u32 sizeBytes, bool respec) {- const u32 id = static_cast<u32>(buffer);- auto it = buffer_meta_.find(id);- if (it == buffer_meta_.end()) return;- const BufferMeta& meta = it->second;+void GLDevice::uploadBufferStore(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes, bool respec) {+ const u32 name = nameOf(buffer_names_, id);+ const BufferDesc* desc = bufferDesc(BufferHandle{id});+ if (!name || !desc) return;// GL_ELEMENT_ARRAY_BUFFER binding is VAO state: uploading through it while some// VAO is bound would silently rewire that VAO's index buffer. Detach first.- if (meta.usage == GfxBufferUsage::Index) {+ if (desc->usage == GfxBufferUsage::Index) {glBindVertexArray(0);bound_vao_ = 0;}- const GLenum target = toGLBufferTarget(meta.usage);- glBindBuffer(target, id);+ const GLenum target = toGLBufferTarget(desc->usage);+ glBindBuffer(target, name);if (respec) {- glBufferData(target, sizeBytes, data, meta.dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);+ glBufferData(target, sizeBytes, data, desc->dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);} else {glBufferSubData(target, offsetBytes, sizeBytes, data);}}-// A lost GL context accepts every call silently, so the danger is not a crash:-// creation appears to succeed and returns an id naming nothing. Guarded are the-// calls whose RESULT the caller acts on; state setters are no-ops already.--BufferHandle GLDevice::createBuffer(const BufferDesc& desc, const void* initialData) {- if (!isDeviceUsable()) return BufferHandle::Invalid;- GLuint id = 0;- glGenBuffers(1, &id);- buffer_meta_[id] = BufferMeta{desc.usage, desc.dynamic};- uploadBufferStore(BufferHandle{id}, 0, initialData, desc.size, /*respec=*/true);- return BufferHandle{id};+bool GLDevice::backendCreateBuffer(u32 id, const BufferDesc& desc, const void* data) {+ GLuint name = 0;+ glGenBuffers(1, &name);+ if (!name) return false;+ setName(buffer_names_, id, name);+ uploadBufferStore(id, 0, data, desc.size, /*respec=*/true);+ // A slot keeps naming the buffer across a rebuild; the context it was bound in does not.+ for (usize slot = 0; slot < uniform_slots_.size(); ++slot) {+ if (uniform_slots_[slot] == id) glBindBufferBase(GL_UNIFORM_BUFFER, static_cast<GLuint>(slot), name);+ }+ return true;}-void GLDevice::deleteBuffer(BufferHandle buffer) {- GLuint id = static_cast<GLuint>(buffer);- glDeleteBuffers(1, &id);- buffer_meta_.erase(static_cast<u32>(buffer));+void GLDevice::backendDeleteBuffer(u32 id) {+ GLuint name = nameOf(buffer_names_, id);+ if (!name) return;+ glDeleteBuffers(1, &name);+ setName(buffer_names_, id, 0);}-void GLDevice::updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) {- uploadBufferStore(buffer, offsetBytes, data, sizeBytes, /*respec=*/false);+void GLDevice::backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) {+ uploadBufferStore(id, offsetBytes, data, sizeBytes, /*respec=*/false);}-void GLDevice::resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) {- uploadBufferStore(buffer, 0, data, sizeBytes, /*respec=*/true);+void GLDevice::backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) {+ uploadBufferStore(id, 0, data, desc.size, /*respec=*/true);}void GLDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {- glBindBufferBase(GL_UNIFORM_BUFFER, slot, static_cast<GLuint>(buffer));+ setName(uniform_slots_, slot, static_cast<u32>(buffer));+ glBindBufferBase(GL_UNIFORM_BUFFER, slot, nameOf(buffer_names_, static_cast<u32>(buffer)));}// =============================================================================// Vertex Input// =============================================================================-VertexLayoutHandle GLDevice::createVertexLayout(const VertexLayoutDesc& desc) {- if (!isDeviceUsable()) return VertexLayoutHandle::Invalid;- LayoutRecord rec;- rec.desc = desc;- rec.alive = true;- layouts_.push_back(rec);- return static_cast<VertexLayoutHandle>(layouts_.size()); // 1-based; 0 == Invalid-}--void GLDevice::deleteVertexLayout(VertexLayoutHandle layout) {- const u32 index = static_cast<u32>(layout);- if (index == 0 || index > layouts_.size()) return;- LayoutRecord& rec = layouts_[index - 1];- if (rec.vao != 0) {- if (bound_vao_ == rec.vao) {+void GLDevice::backendDeleteVertexLayout(u32 id) {+ auto it = vaos_.find(id);+ if (it == vaos_.end()) return;+ if (it->second.vao != 0) {+ if (bound_vao_ == it->second.vao) {glBindVertexArray(0);bound_vao_ = 0;}- glDeleteVertexArrays(1, &rec.vao);- rec.vao = 0;+ glDeleteVertexArrays(1, &it->second.vao);}- rec.alive = false;+ vaos_.erase(it);}void GLDevice::setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) {if (slot >= MAX_VERTEX_BUFFER_SLOTS) return;- pending_vbo_[slot] = static_cast<u32>(buffer);+ pending_vbo_[slot] = nameOf(buffer_names_, static_cast<u32>(buffer));pending_vbo_offset_[slot] = offsetBytes;}void GLDevice::setIndexBuffer(BufferHandle buffer) {- pending_ibo_ = static_cast<u32>(buffer);+ pending_ibo_ = nameOf(buffer_names_, static_cast<u32>(buffer));}void GLDevice::prepareVertexState() {- const u32 index = static_cast<u32>(current_layout_);- if (index == 0 || index > layouts_.size()) return;- LayoutRecord& rec = layouts_[index - 1];- if (!rec.alive) return;+ const VertexLayoutDesc* desc = vertexLayoutDesc(VertexLayoutHandle{current_layout_});+ if (!desc) return;+ VaoCache& rec = vaos_[current_layout_];if (rec.vao == 0) {glGenVertexArrays(1, &rec.vao);@@ -883,8 +866,8 @@ void GLDevice::prepareVertexState() {for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) {bool slotUsed = false;- for (u32 a = 0; a < rec.desc.attributeCount; ++a) {- if (rec.desc.attributes[a].bufferSlot == slot) { slotUsed = true; break; }+ for (u32 a = 0; a < desc->attributeCount; ++a) {+ if (desc->attributes[a].bufferSlot == slot) { slotUsed = true; break; }}if (!slotUsed) continue;if (rec.configured && rec.bakedVbo[slot] == pending_vbo_[slot]@@ -893,8 +876,8 @@ void GLDevice::prepareVertexState() {}glBindBuffer(GL_ARRAY_BUFFER, pending_vbo_[slot]);- for (u32 a = 0; a < rec.desc.attributeCount; ++a) {- const GfxVertexAttribute& attr = rec.desc.attributes[a];+ for (u32 a = 0; a < desc->attributeCount; ++a) {+ const GfxVertexAttribute& attr = desc->attributes[a];if (attr.bufferSlot != slot) continue;glEnableVertexAttribArray(attr.location);const void* at = reinterpret_cast<const void*>(@@ -905,14 +888,14 @@ void GLDevice::prepareVertexState() {if (!attr.normalized && isIntegerAttribute(attr.type)) {glVertexAttribIPointer(attr.location, attr.components, toGLDataType(attr.type),- static_cast<GLsizei>(rec.desc.strides[slot]), at);+ static_cast<GLsizei>(desc->strides[slot]), at);} else {glVertexAttribPointer(attr.location, attr.components, toGLDataType(attr.type),attr.normalized ? GL_TRUE : GL_FALSE,- static_cast<GLsizei>(rec.desc.strides[slot]), at);+ static_cast<GLsizei>(desc->strides[slot]), at);}- glVertexAttribDivisor(attr.location, rec.desc.instanceStep[slot] ? 1 : 0);+ glVertexAttribDivisor(attr.location, desc->instanceStep[slot] ? 1 : 0);}rec.bakedVbo[slot] = pending_vbo_[slot];rec.bakedOffset[slot] = pending_vbo_offset_[slot];@@ -920,29 +903,10 @@ void GLDevice::prepareVertexState() {rec.configured = true;}-u32 GLDevice::getUniformBlockIndex(ShaderHandle program, const char* name) {- return static_cast<u32>(glGetUniformBlockIndex(static_cast<GLuint>(program), name));-}--void GLDevice::uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) {- glUniformBlockBinding(static_cast<GLuint>(program), blockIndex, bindingPoint);-}-// =============================================================================// Pipeline State// =============================================================================-PipelineHandle GLDevice::createPipeline(const PipelineDesc& desc) {- if (!isDeviceUsable()) return PipelineHandle::Invalid;- for (u32 i = 0; i < pipelines_.size(); ++i) {- if (pipelines_[i] == desc) {- return static_cast<PipelineHandle>(i + 1);- }- }- pipelines_.push_back(desc);- return static_cast<PipelineHandle>(pipelines_.size()); // 1-based; 0 == Invalid-}-void GLDevice::applyStencilMode(GfxStencilMode mode) {// Mirrors the former StateTracker stencil sequences. The reference value is applied// separately by setStencilReference (it is dynamic, not pipeline state).@@ -968,14 +932,9 @@ void GLDevice::applyStencilMode(GfxStencilMode mode) {}}-void GLDevice::setPipeline(PipelineHandle handle) {- if (handle == current_pipeline_ || handle == PipelineHandle::Invalid) return;-- u32 index = static_cast<u32>(handle) - 1;- if (index >= pipelines_.size()) return;- const PipelineDesc& desc = pipelines_[index];-- useProgram(desc.program);+void GLDevice::backendSetPipeline(u32 id, const PipelineDesc& desc) {+ if (id == current_pipeline_id_) return;+ backendUseProgram(static_cast<u32>(desc.program));setBlendEnabled(desc.blendEnabled);setBlendMode(desc.blend);setDepthTest(desc.depthTest);@@ -985,9 +944,9 @@ void GLDevice::setPipeline(PipelineHandle handle) {setDepthBias(desc.depthBias);applyStencilMode(desc.stencil);- current_pipeline_ = handle;+ current_pipeline_id_ = id;current_stencil_mode_ = desc.stencil;- current_layout_ = desc.vertexLayout;+ current_layout_ = static_cast<u32>(desc.vertexLayout);}/**@@ -1024,10 +983,10 @@ void GLDevice::setStencilReference(i32 ref) {}}-void GLDevice::invalidatePipelineCache() {- current_pipeline_ = PipelineHandle::Invalid;+void GLDevice::backendInvalidatePipelineCache() {+ current_pipeline_id_ = 0;current_stencil_mode_ = GfxStencilMode::Off;- current_program_ = ShaderHandle::Invalid;+ current_program_name_ = 0;current_blend_ = static_cast<BlendMode>(0xFF);}@@ -1061,30 +1020,30 @@ void GLDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32// =============================================================================void GLDevice::bindTexture(u32 slot, TextureHandle texture) {+ const u32 name = nameOf(texture_names_, static_cast<u32>(texture));if (slot >= kTextureSlots) { // beyond the cache — bind directlyglActiveTexture(GL_TEXTURE0 + slot);- glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));+ glBindTexture(GL_TEXTURE_2D, name);return;}- const u32 id = static_cast<u32>(texture);- if (bound_texture_[slot] == id) return; // already bound to this sampler unit+ if (bound_texture_[slot] == name) return; // already bound to this sampler unitif (active_texture_unit_ != slot) {glActiveTexture(GL_TEXTURE0 + slot);active_texture_unit_ = slot;}- glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));- bound_texture_[slot] = id;+ glBindTexture(GL_TEXTURE_2D, name);+ bound_texture_[slot] = name;}-void GLDevice::bindTextureForEdit(u32 id) {- glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(id));- if (active_texture_unit_ < kTextureSlots) bound_texture_[active_texture_unit_] = id;+void GLDevice::bindTextureForEdit(u32 name) {+ glBindTexture(GL_TEXTURE_2D, name);+ if (active_texture_unit_ < kTextureSlots) bound_texture_[active_texture_unit_] = name;}-void GLDevice::evictSamplerBinding(u32 textureId) {- if (textureId == 0) return;+void GLDevice::evictSamplerBinding(u32 name) {+ if (name == 0) return;for (u32 slot = 0; slot < kTextureSlots; ++slot) {- if (bound_texture_[slot] != textureId) continue;+ if (bound_texture_[slot] != name) continue;if (active_texture_unit_ != slot) {glActiveTexture(GL_TEXTURE0 + slot);active_texture_unit_ = slot;@@ -1094,9 +1053,7 @@ void GLDevice::evictSamplerBinding(u32 textureId) {}}-TextureHandle GLDevice::createTexture(const TextureDesc& desc, const void* pixels) {- if (!isDeviceUsable()) return TextureHandle::Invalid;-+bool GLDevice::backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) {// Multisampled: a renderbuffer, never sampled, only drawn into and resolved// from. It takes no filter or wrap because nothing reads it through a sampler.if (desc.samples > 1) {@@ -1109,17 +1066,18 @@ TextureHandle GLDevice::createTexture(const TextureDesc& desc, const void* pixelstatic_cast<GLsizei>(desc.width),static_cast<GLsizei>(desc.height));glBindRenderbuffer(GL_RENDERBUFFER, 0);- if (rb == 0) return TextureHandle::Invalid;- texture_formats_[rb | kRenderbufferTag] = desc.format;- return TextureHandle{rb | kRenderbufferTag};+ if (rb == 0) return false;+ setName(texture_names_, id, rb);+ return true;}- GLuint id = 0;- glGenTextures(1, &id);- texture_formats_[id] = desc.format;+ GLuint name = 0;+ glGenTextures(1, &name);+ if (name == 0) return false;+ setName(texture_names_, id, name);auto gl = toGLPixelFormat(desc.format);- bindTextureForEdit(id);+ bindTextureForEdit(name);const TightRowScope rows(desc.format, desc.width);if (pixels && desc.flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_TRUE);glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(gl.internalFormat),@@ -1132,19 +1090,19 @@ TextureHandle GLDevice::createTexture(const TextureDesc& desc, const void* pixelglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));- if (desc.mipmaps) {+ if (desc.mipmaps && pixels) {glGenerateMipmap(GL_TEXTURE_2D);}- return TextureHandle{id};+ return true;}-TextureHandle GLDevice::createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,- const void* data, u32 byteLength, u32 mipLevels) {- if (!isDeviceUsable()) return TextureHandle::Invalid;- GLuint id = 0;- glGenTextures(1, &id);- texture_formats_[id] = desc.format;- bindTextureForEdit(id);+bool GLDevice::backendCreateCompressedTexture(u32 id, const TextureDesc& desc, GfxCompressedFormat format,+ const void* data, u32 byteLength, u32 mipLevels) {+ GLuint name = 0;+ glGenTextures(1, &name);+ if (name == 0) return false;+ setName(texture_names_, id, name);+ bindTextureForEdit(name);// Upload each mip level from the concatenated, block-aligned pyramid.const u32 levels = mipLevels ? mipLevels : 1;@@ -1171,33 +1129,38 @@ TextureHandle GLDevice::createCompressedTexture(const TextureDesc& desc, GfxCompglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));- return TextureHandle{id};+ return true;}-TextureHandle GLDevice::importExternalTexture(u32 nativeId, const TextureDesc& desc) {- if (!isDeviceUsable()) return TextureHandle::Invalid;- texture_formats_[nativeId] = desc.format;- return TextureHandle{nativeId};+bool GLDevice::backendAdoptTexture(u32 id, u32 nativeId, const TextureDesc&) {+ if (nativeId == 0) return false;+ setName(texture_names_, id, nativeId);+ return true;}-void GLDevice::deleteTexture(TextureHandle texture) {- const u32 handle = static_cast<u32>(texture);- if (isRenderbuffer(handle)) {- GLuint rb = rbId(handle);- glDeleteRenderbuffers(1, &rb);+void GLDevice::backendDeleteTexture(u32 id) {+ GLuint name = nameOf(texture_names_, id);+ if (!name) return;+ if (isRenderbuffer(id)) {+ glDeleteRenderbuffers(1, &name);} else {- GLuint id = static_cast<GLuint>(texture);- glDeleteTextures(1, &id);+ evictSamplerBinding(name);+ glDeleteTextures(1, &name);}- texture_formats_.erase(handle);+ setName(texture_names_, id, 0);+}++void GLDevice::backendMoveTexture(u32 into, u32 from) {+ setName(texture_names_, into, nameOf(texture_names_, from));+ setName(texture_names_, from, 0);}-void GLDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,- const void* pixels, bool flipY) {- auto it = texture_formats_.find(static_cast<u32>(texture));- const GfxPixelFormat fmt = it != texture_formats_.end() ? it->second : GfxPixelFormat::RGBA8;+void GLDevice::backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY) {+ const TextureDesc* desc = textureDesc(TextureHandle{id});+ const GfxPixelFormat fmt = desc ? desc->format : GfxPixelFormat::RGBA8;auto gl = toGLPixelFormat(fmt);- bindTextureForEdit(static_cast<u32>(texture));+ bindTextureForEdit(nameOf(texture_names_, id));const TightRowScope rows(fmt, width);if (flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_TRUE);glTexSubImage2D(GL_TEXTURE_2D, 0, x, y,@@ -1206,17 +1169,16 @@ void GLDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32if (flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_FALSE);}-void GLDevice::setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag,- TextureWrap wrapS, TextureWrap wrapT) {- bindTextureForEdit(static_cast<u32>(texture));- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLFilter(min));- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(mag));- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(wrapS));- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(wrapT));+void GLDevice::backendSetTextureParams(u32 id, const TextureDesc& desc) {+ bindTextureForEdit(nameOf(texture_names_, id));+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLFilter(desc.minFilter));+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));}-void GLDevice::generateMipmaps(TextureHandle texture) {- bindTextureForEdit(static_cast<u32>(texture));+void GLDevice::backendGenerateMipmaps(u32 id) {+ bindTextureForEdit(nameOf(texture_names_, id));glGenerateMipmap(GL_TEXTURE_2D);}@@ -1224,45 +1186,40 @@ void GLDevice::generateMipmaps(TextureHandle texture) {// Framebuffer// =============================================================================-FramebufferHandle GLDevice::createFramebuffer(const FramebufferDesc& desc) {- if (!isDeviceUsable()) return FramebufferHandle::Default;- GLuint id = 0;- glGenFramebuffers(1, &id);- glBindFramebuffer(GL_FRAMEBUFFER, id);-- auto attachDepth = [&](u32 handle) {- auto it = texture_formats_.find(handle);- const bool depthOnly = it != texture_formats_.end()- && it->second == GfxPixelFormat::DepthComponent24;- const GLenum point = depthOnly ? GL_DEPTH_ATTACHMENT : GL_DEPTH_STENCIL_ATTACHMENT;- if (isRenderbuffer(handle)) {- glFramebufferRenderbuffer(GL_FRAMEBUFFER, point, GL_RENDERBUFFER, rbId(handle));+bool GLDevice::backendCreateFramebuffer(u32 id, const FramebufferDesc& desc) {+ GLuint fbo = 0;+ glGenFramebuffers(1, &fbo);+ glBindFramebuffer(GL_FRAMEBUFFER, fbo);++ auto attach = [&](GLenum point, TextureHandle texture) {+ const u32 textureId = static_cast<u32>(texture);+ const u32 name = nameOf(texture_names_, textureId);+ if (isRenderbuffer(textureId)) {+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, point, GL_RENDERBUFFER, name);} else {- glFramebufferTexture2D(GL_FRAMEBUFFER, point, GL_TEXTURE_2D,- static_cast<GLuint>(handle), 0);+ glFramebufferTexture2D(GL_FRAMEBUFFER, point, GL_TEXTURE_2D, name, 0);}};+ auto depthPoint = [&](TextureHandle texture) {+ const TextureDesc* d = textureDesc(texture);+ return d && d->format == GfxPixelFormat::DepthComponent24 ? GL_DEPTH_ATTACHMENT+ : GL_DEPTH_STENCIL_ATTACHMENT;+ };- if (desc.color0 != TextureHandle::Invalid) {- const u32 c = static_cast<u32>(desc.color0);- if (isRenderbuffer(c)) {- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbId(c));- } else {- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,- static_cast<GLuint>(c), 0);- }- }+ if (desc.color0 != TextureHandle::Invalid) attach(GL_COLOR_ATTACHMENT0, desc.color0);if (desc.depthStencil != TextureHandle::Invalid) {// Attach point follows the texture's pixel format (depth-only vs packed depth+stencil).- attachDepth(static_cast<u32>(desc.depthStencil));+ attach(depthPoint(desc.depthStencil), desc.depthStencil);}const bool complete = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;glBindFramebuffer(GL_FRAMEBUFFER, 0);if (!complete) {- glDeleteFramebuffers(1, &id);- return FramebufferHandle::Default;+ glDeleteFramebuffers(1, &fbo);+ return false;}+ setName(framebuffer_names_, id, fbo);+// A multisampled target keeps a second, single-sample framebuffer of its own// to resolve into. It is the target's, not a pass's: whoever leaves the// target gets the resolve for free and never has to ask for it.@@ -1270,10 +1227,9 @@ FramebufferHandle GLDevice::createFramebuffer(const FramebufferDesc& desc) {GLuint dst = 0;glGenFramebuffers(1, &dst);glBindFramebuffer(GL_FRAMEBUFFER, dst);- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,- static_cast<GLuint>(desc.resolveColor0), 0);+ attach(GL_COLOR_ATTACHMENT0, desc.resolveColor0);if (desc.resolveDepthStencil != TextureHandle::Invalid) {- attachDepth(static_cast<u32>(desc.resolveDepthStencil));+ attach(depthPoint(desc.resolveDepthStencil), desc.resolveDepthStencil);}const bool ok = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;glBindFramebuffer(GL_FRAMEBUFFER, 0);@@ -1285,8 +1241,7 @@ FramebufferHandle GLDevice::createFramebuffer(const FramebufferDesc& desc) {ES_LOG_ERROR("GLDevice: multisample resolve target incomplete");}}- framebuffer_textures_[id] = {static_cast<u32>(desc.color0), static_cast<u32>(desc.depthStencil)};- return FramebufferHandle{id};+ return true;}/**@@ -1295,12 +1250,12 @@ FramebufferHandle GLDevice::createFramebuffer(const FramebufferDesc& desc) {* multisampled depth attachment cannot be sampled — GL_NEAREST is the only* filter a depth blit accepts.*/-void GLDevice::resolveFramebuffer(u32 fbo) {- auto it = framebuffer_resolve_.find(fbo);+void GLDevice::resolveFramebuffer(u32 framebufferId) {+ auto it = framebuffer_resolve_.find(framebufferId);if (it == framebuffer_resolve_.end() || it->second.destFbo == 0) return;const auto& r = it->second;if (r.width == 0 || r.height == 0) return;- glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);+ glBindFramebuffer(GL_READ_FRAMEBUFFER, nameOf(framebuffer_names_, framebufferId));glBindFramebuffer(GL_DRAW_FRAMEBUFFER, r.destFbo);const GLsizei w = static_cast<GLsizei>(r.width), h = static_cast<GLsizei>(r.height);glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_LINEAR);@@ -1309,17 +1264,17 @@ void GLDevice::resolveFramebuffer(u32 fbo) {// differs, and depth refuses anything but NEAREST.glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_DEPTH_BUFFER_BIT, GL_NEAREST);}- glBindFramebuffer(GL_FRAMEBUFFER, static_cast<GLuint>(current_fbo_));+ glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, current_framebuffer_));}-void GLDevice::deleteFramebuffer(FramebufferHandle framebuffer) {- GLuint id = static_cast<GLuint>(framebuffer);+void GLDevice::backendDeleteFramebuffer(u32 id) {if (auto it = framebuffer_resolve_.find(id); it != framebuffer_resolve_.end()) {if (it->second.destFbo != 0) glDeleteFramebuffers(1, &it->second.destFbo);framebuffer_resolve_.erase(it);}- if (id != 0) glDeleteFramebuffers(1, &id);- framebuffer_textures_.erase(id);+ GLuint name = nameOf(framebuffer_names_, id);+ if (name != 0) glDeleteFramebuffers(1, &name);+ setName(framebuffer_names_, id, 0);}void GLDevice::clearStencil(i32 value) {@@ -1328,26 +1283,20 @@ void GLDevice::clearStencil(i32 value) {}void GLDevice::beginRenderPass(const RenderPassDesc& desc) {- const GLuint target = static_cast<GLuint>(desc.target);+ const u32 target = static_cast<u32>(desc.target);// Retargeting LEAVES the previous target, and the model has no explicit pass// object to hang the resolve on — so leaving is the event, whether it comes// from endRenderPass or from being retargeted out from under.- if (current_fbo_ != target) resolveFramebuffer(current_fbo_);- current_fbo_ = target;- glBindFramebuffer(GL_FRAMEBUFFER, target);-- // Feedback-loop guard: a render target's own attachment must not remain bound to- // a sampler unit while the target is drawn into — GL leaves that undefined and- // some drivers raise GL_INVALID_OPERATION ("feedback loop"). This bites when a- // pass samples a render texture to composite it on screen and the NEXT frame- // draws back into that same texture (e.g. a live minimap). Detach it up front;- // the default framebuffer (0) owns no texture, so skip it.- if (target != 0) {- auto it = framebuffer_textures_.find(target);- if (it != framebuffer_textures_.end()) {- evictSamplerBinding(it->second.color);- evictSamplerBinding(it->second.depthStencil);- }+ if (current_framebuffer_ != target) resolveFramebuffer(current_framebuffer_);+ current_framebuffer_ = target;+ glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, target));++ // A target's own attachment must not stay bound to a sampler while it is drawn+ // into: GL leaves that undefined and some drivers raise a feedback-loop error+ // (a minimap composited last frame and drawn into this one).+ if (const FramebufferDesc* fb = framebufferDesc(desc.target)) {+ evictSamplerBinding(nameOf(texture_names_, static_cast<u32>(fb->color0)));+ evictSamplerBinding(nameOf(texture_names_, static_cast<u32>(fb->depthStencil)));}if (!desc.clearColor && !desc.clearDepth && !desc.clearStencil) return;@@ -1377,8 +1326,8 @@ void GLDevice::beginRenderPass(const RenderPassDesc& desc) {}void GLDevice::endRenderPass() {- resolveFramebuffer(current_fbo_);- current_fbo_ = 0;+ resolveFramebuffer(current_framebuffer_);+ current_framebuffer_ = 0;glBindFramebuffer(GL_FRAMEBUFFER, 0);}@@ -1399,7 +1348,7 @@ ReadbackHandle GLDevice::requestReadback(FramebufferHandle target, u32 w, u32 h)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.- glBindFramebuffer(GL_FRAMEBUFFER, static_cast<GLuint>(target));+ glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, static_cast<u32>(target)));auto gl = toGLPixelFormat(GfxPixelFormat::RGBA8);glReadPixels(0, 0, static_cast<GLsizei>(w), static_cast<GLsizei>(h), gl.format, gl.type,pixels.data());@@ -1430,7 +1379,7 @@ void GLDevice::discardReadback(ReadbackHandle handle) {// GPU Timing// =============================================================================-u32 GLDevice::createTimerQuery() {+bool GLDevice::backendCreateTimerQuery(u32 id) {if (timer_query_state_ == 0) {#ifdef __EMSCRIPTEN__// Must ENABLE the extension (not just check presence) so emscripten routes the@@ -1442,14 +1391,16 @@ u32 GLDevice::createTimerQuery() {timer_query_state_ = 2;#endif}- if (timer_query_state_ != 1) return 0;- GLuint id = 0;- glGenQueries(1, &id);- return static_cast<u32>(id);+ if (timer_query_state_ != 1) return false;+ GLuint name = 0;+ glGenQueries(1, &name);+ if (name == 0) return false;+ setName(query_names_, id, name);+ return true;}void GLDevice::beginTimerQuery(u32 query) {- glBeginQuery(GL_TIME_ELAPSED_EXT, query);+ glBeginQuery(GL_TIME_ELAPSED_EXT, nameOf(query_names_, query));}void GLDevice::endTimerQuery() {@@ -1457,17 +1408,23 @@ void GLDevice::endTimerQuery() {}bool GLDevice::timerDisjoint() {+ if (timer_disjoint_pending_) {+ timer_disjoint_pending_ = false;+ return true;+ }GLint disjoint = 0;glGetIntegerv(GL_GPU_DISJOINT_EXT, &disjoint);return disjoint != 0;}bool GLDevice::getTimerQueryNs(u32 query, u64* outNanoseconds) {+ const u32 name = nameOf(query_names_, query);+ if (!name) return false;GLuint available = 0;- glGetQueryObjectuiv(query, GL_QUERY_RESULT_AVAILABLE, &available);+ glGetQueryObjectuiv(name, GL_QUERY_RESULT_AVAILABLE, &available);if (!available) return false;GLuint ns = 0;- glGetQueryObjectuiv(query, GL_QUERY_RESULT, &ns);+ glGetQueryObjectuiv(name, GL_QUERY_RESULT, &ns);if (outNanoseconds) *outNanoseconds = ns;return true;}@@ -1550,19 +1507,4 @@ bool GLDevice::supportsFloatTargets() {|| glExtensionPresent("EXT_color_buffer_float");}-GfxLiveObjects GLDevice::liveObjects() const {- // Buffers and textures need no counter: the per-handle metadata maps are- // written on create and erased on delete, so their size IS the live set —- // and unlike a parallel counter it cannot drift out of agreement with them.- return GfxLiveObjects{- static_cast<u32>(buffer_meta_.size()),- static_cast<u32>(texture_formats_.size()),- live_programs_,- static_cast<u32>(layouts_.size()),- static_cast<u32>(pipelines_.size()),- static_cast<u32>(framebuffer_textures_.size()),- static_cast<u32>(readbacks_.size()),- };-}-} // namespace esenginediff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hppindex 872beb1de..b26adddf8 100644--- a/src/esengine/renderer/rhi/GLDevice.hpp+++ b/src/esengine/renderer/rhi/GLDevice.hpp@@ -3,7 +3,9 @@/*** @file GLDevice.hpp* @brief OpenGL ES / WebGL implementation of GfxDevice- * @details Implements all GfxDevice virtual methods using OpenGL ES 3.0 calls.+ * @details Implements the backend primitives with OpenGL ES 3.0 calls. A handle is+ * the registry's id; the GL name behind it belongs to one generation of+ * the context and lives only in this backend's maps.** @author ESEngine Team* @date 2026@@ -43,40 +45,16 @@ public:bool pollDeviceLost() override;-protected:- void captureDeviceIdentity() override;- bool recreateDevice() override;- void onDeviceLost() override;--public:-void setViewport(i32 x, i32 y, u32 w, u32 h) override;void clearStencil(i32 value) override;void setScissorTest(bool enabled) override;void setScissor(i32 x, i32 y, i32 w, i32 h) override;- BufferHandle createBuffer(const BufferDesc& desc, const void* initialData) override;- void deleteBuffer(BufferHandle buffer) override;- void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) override;- void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) override;void setUniformBuffer(u32 slot, BufferHandle buffer) override;-- VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc) override;- void deleteVertexLayout(VertexLayoutHandle layout) override;void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override;void setIndexBuffer(BufferHandle buffer) override;- TextureHandle createTexture(const TextureDesc& desc, const void* pixels) override;- TextureHandle createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,- const void* data, u32 byteLength, u32 mipLevels) override;- TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc) override;- void deleteTexture(TextureHandle texture) override;- void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,- const void* pixels, bool flipY) override;- void setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag,- TextureWrap wrapS, TextureWrap wrapT) override;- void generateMipmaps(TextureHandle texture) override;void bindTexture(u32 slot, TextureHandle texture) override;bool supportsCompressedFormat(GfxCompressedFormat format) override;bool supportsFloatTargets() override;@@ -88,37 +66,13 @@ public:/// GL reads a framebuffer from the bottom up.bool textureOriginTopLeft() const override { return false; }- ShaderHandle createProgram(const GfxShaderSource& source,- const GfxAttribBinding* bindings, u32 bindingCount,- std::string* outLog, GfxShaderStage* outFailedStage) override;- void deleteProgram(ShaderHandle program) override;- void useProgram(ShaderHandle program) override;- i32 getUniformLocation(ShaderHandle program, const char* name) override;- i32 getAttribLocation(ShaderHandle program, const char* name) override;- void setUniform1i(i32 location, i32 value) override;- void setUniform1f(i32 location, f32 value) override;- void setUniform2f(i32 location, f32 x, f32 y) override;- void setUniform3f(i32 location, f32 x, f32 y, f32 z) override;- void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) override;- void setUniformMat3(i32 location, const f32* data) override;- void setUniformMat4(i32 location, const f32* data) override;-- std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle program) override;-- u32 getUniformBlockIndex(ShaderHandle program, const char* name) override;- void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) override;-- PipelineHandle createPipeline(const PipelineDesc& desc) override;- void setPipeline(PipelineHandle handle) override;+void setStencilReference(i32 ref) override;- void invalidatePipelineCache() override;void drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset) override;void drawArrays(u32 first, u32 vertexCount) override;void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) override;- FramebufferHandle createFramebuffer(const FramebufferDesc& desc) override;- void deleteFramebuffer(FramebufferHandle framebuffer) override;void beginRenderPass(const RenderPassDesc& desc) override;void endRenderPass() override;@@ -127,7 +81,6 @@ public:bool takeReadback(ReadbackHandle handle, void* dest, usize destSize) override;void discardReadback(ReadbackHandle handle) override;- u32 createTimerQuery() override;void beginTimerQuery(u32 query) override;void endTimerQuery() override;bool timerDisjoint() override;@@ -137,9 +90,64 @@ public:u32 getError() override;std::string getString(GfxStringName name) override;i32 getInt(GfxIntParam name) override;- GfxLiveObjects liveObjects() const override;++ /** @brief This generation's GL name behind a texture, for a host uploading into it. */+ u32 nativeTextureName(TextureHandle texture) const { return nameOf(texture_names_, static_cast<u32>(texture)); }++protected:+ void captureDeviceIdentity() override;+ bool recreateDevice() override;+ void onDeviceLost() override;++ bool backendCreateBuffer(u32 id, const BufferDesc& desc, const void* data) override;+ void backendDeleteBuffer(u32 id) override;+ void backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) override;+ void backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) override;++ bool backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) override;+ bool backendCreateCompressedTexture(u32 id, const TextureDesc& desc, GfxCompressedFormat format,+ const void* data, u32 byteLength, u32 mipLevels) override;+ bool backendAdoptTexture(u32 id, u32 nativeId, const TextureDesc& desc) override;+ void backendDeleteTexture(u32 id) override;+ void backendMoveTexture(u32 into, u32 from) override;+ void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY) override;+ void backendSetTextureParams(u32 id, const TextureDesc& desc) override;+ void backendGenerateMipmaps(u32 id) override;++ bool backendCreateProgram(u32 id, const GfxShaderSource& source,+ const GfxAttribBinding* bindings, u32 bindingCount,+ std::string* outLog, GfxShaderStage* outFailedStage) override;+ void backendDeleteProgram(u32 id) override;+ void backendUseProgram(u32 id) override;+ i32 backendUniformLocation(u32 program, const char* name) override;+ i32 backendAttribLocation(u32 program, const char* name) override;+ void backendSetUniform(i32 nativeLocation, const GfxUniformValue& value) override;+ std::vector<GfxUniformInfo> backendActiveUniforms(u32 program) override;+ u32 backendUniformBlockIndex(u32 program, const char* name) override;+ void backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint) override;++ void backendDeleteVertexLayout(u32 id) override;+ void backendSetPipeline(u32 id, const PipelineDesc& desc) override;+ void backendInvalidatePipelineCache() override;++ bool backendCreateFramebuffer(u32 id, const FramebufferDesc& desc) override;+ void backendDeleteFramebuffer(u32 id) override;++ bool backendCreateTimerQuery(u32 id) override;+ u32 backendReadbackCount() const override { return static_cast<u32>(readbacks_.size()); }private:+ static u32 nameOf(const std::vector<u32>& names, u32 id) {+ return id < names.size() ? names[id] : 0u;+ }+ static void setName(std::vector<u32>& names, u32 id, u32 name) {+ if (id >= names.size()) names.resize(static_cast<usize>(id) + 1, 0u);+ names[id] = name;+ }+ /** A multisampled texture is a renderbuffer in WebGL2, in its own GL namespace. */+ bool isRenderbuffer(u32 textureId) const;+// Clear machinery: backend-internal since RenderPassDesc became the only way// to request clears (it carries the values; beginRenderPass applies them).void setClearColor(f32 r, f32 g, f32 b, f32 a);@@ -161,12 +169,9 @@ private:void setCullFace(bool front);void setDepthBias(i16 bias);- // Pipeline cache: a handle is (index + 1) into pipelines_; PipelineHandle::Invalid is 0.- // WebGL2 has no native pipeline object, so a pipeline is applied as a bundle of GL- // state, deduped by comparing handles (same pipeline -> skip the whole state apply).void applyStencilMode(GfxStencilMode mode);- void uploadBufferStore(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes, bool respec);+ void uploadBufferStore(u32 id, 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@@ -182,72 +187,56 @@ private:// Binds a texture on the active unit for a create/update/mipmap edit while// keeping the sampler-binding cache coherent, so bindTexture() can skip// redundant per-draw binds (every gl* call is a WASM→JS FFI crossing).- void bindTextureForEdit(u32 id);+ void bindTextureForEdit(u32 name);// Detach a texture from every sampler slot it lingers in, keeping the sampler// cache coherent. Used by beginRenderPass to break feedback loops: a render// target's own attachment must not stay bound to a sampler while it is drawn to.- void evictSamplerBinding(u32 textureId);-- std::vector<PipelineDesc> pipelines_;- PipelineHandle current_pipeline_ = PipelineHandle::Invalid;+ void evictSamplerBinding(u32 name);++ /** GL names by registry id for this generation; 0 = none. */+ std::vector<u32> buffer_names_;+ std::vector<u32> texture_names_;+ std::vector<u32> program_names_;+ std::vector<u32> framebuffer_names_;+ std::vector<u32> query_names_;+ /** Buffer id per uniform binding slot, as the renderer set it. */+ std::vector<u32> uniform_slots_;++ u32 current_pipeline_id_ = 0;GfxStencilMode current_stencil_mode_ = GfxStencilMode::Off;- // Redundant-state caches for setPipeline: the program and blend func are only- // ever set through useProgram / setBlendMode, so caching the last value lets a- // pipeline switch that shares them skip the (FFI-crossing) GL call. Reset in- // invalidatePipelineCache. 0xFF is an out-of-range BlendMode sentinel so the- // first real set always issues (init sets the GL blend directly, not via here).- ShaderHandle current_program_ = ShaderHandle::Invalid;+ // Redundant-state caches: a pipeline switch sharing the program or blend func+ // skips the FFI-crossing GL call. 0xFF is an out-of-range BlendMode, so the+ // first real set always issues.+ u32 current_program_name_ = 0;BlendMode current_blend_ = static_cast<BlendMode>(0xFF);// Redundant-state caches for the two per-draw hot paths. glActiveTexture is// the only site that moves the active unit, so active_texture_unit_ is- // authoritative; bound_texture_[unit] mirrors the sampler bindings.+ // authoritative; bound_texture_[unit] mirrors the sampler bindings by GL name.static constexpr u32 kTextureSlots = 16;u32 active_texture_unit_ = 0;u32 bound_texture_[kTextureSlots] = {};i16 current_depth_bias_ = 0;int scissor_test_ = -1; // tri-state: -1 unknown, 0 disabled, 1 enabled- struct LayoutRecord {- VertexLayoutDesc desc;+ struct VaoCache {u32 vao = 0;- bool alive = false;bool configured = false;u32 bakedVbo[MAX_VERTEX_BUFFER_SLOTS] = {};u32 bakedOffset[MAX_VERTEX_BUFFER_SLOTS] = {};u32 bakedIbo = 0;};- std::vector<LayoutRecord> layouts_;- VertexLayoutHandle current_layout_ = VertexLayoutHandle::Invalid;+ std::unordered_map<u32, VaoCache> vaos_;+ u32 current_layout_ = 0;u32 pending_vbo_[MAX_VERTEX_BUFFER_SLOTS] = {};u32 pending_vbo_offset_[MAX_VERTEX_BUFFER_SLOTS] = {};u32 pending_ibo_ = 0;u32 bound_vao_ = 0;- // Per-handle metadata the GL bind-to-edit protocol needs but the interface no- // longer carries: buffer target/usage for uploads, texture transfer format for- // sub-image updates.- struct BufferMeta {- GfxBufferUsage usage;- bool dynamic;- };- std::unordered_map<u32, BufferMeta> buffer_meta_;- std::unordered_map<u32, GfxPixelFormat> texture_formats_;-- // The textures a framebuffer owns (color + depth/stencil attachment ids),- // recorded at createFramebuffer. beginRenderPass consults this to detach the- // target's own attachments from any sampler slot before drawing into it — the- // GL feedback-loop guard. 0 = no such attachment.- struct FramebufferTextures {- u32 color = 0;- u32 depthStencil = 0;- };- std::unordered_map<u32, FramebufferTextures> framebuffer_textures_;-- // Where a multisampled framebuffer resolves to, and how big. The blit runs- // whenever the target is left, which is the only reason anything above the- // RHI can sample a target it drew into multisampled.+ // Where a multisampled framebuffer resolves to, and how big, by framebuffer id.+ // The blit runs whenever the target is left, which is the only reason anything+ // above the RHI can sample a target it drew into multisampled.struct ResolvePair {u32 destFbo = 0;u32 width = 0;@@ -257,9 +246,9 @@ private:std::unordered_map<u32, ResolvePair> framebuffer_resolve_;/// Blit a multisampled target into the single-sample one it owns; no-op for/// a target that owns none. Called whenever a target is left.- void resolveFramebuffer(u32 fbo);- /// The target a pass is currently drawing into, so leaving it can resolve it.- u32 current_fbo_ = 0;+ void resolveFramebuffer(u32 framebufferId);+ /// The framebuffer id a pass is currently drawing into (0 = default).+ u32 current_framebuffer_ = 0;/// 0 = unprobed; otherwise GL_MAX_SAMPLES, floored at 1.u32 max_samples_ = 0;@@ -270,11 +259,7 @@ private:// 0 = unprobed, 1 = timer queries available, 2 = unavailable.int timer_query_state_ = 0;-- // Linked programs alive. Unlike buffers and textures, programs have no- // per-handle metadata map whose size would answer this, and a program leaked- // by shader hot reload is the exact failure the census exists to catch.- u32 live_programs_ = 0;+ bool timer_disjoint_pending_ = false;};} // namespace esenginediff --git a/src/esengine/renderer/rhi/GfxContent.hpp b/src/esengine/renderer/rhi/GfxContent.hppnew file mode 100644index 000000000..64df24338--- /dev/null+++ b/src/esengine/renderer/rhi/GfxContent.hpp@@ -0,0 +1,51 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file GfxContent.hpp+ * @brief Who restores a GPU object's contents after the device is lost.+ *+ * @details Declared when the object is created, and not defaultable: a buffer or+ * texture whose recovery nobody decided is exactly how content went+ * missing after a loss while the handle kept pointing at storage.+ */+#pragma once++#include "../../core/Types.hpp"++namespace esengine {++enum class GfxContentKind : u8 {+ /// Rewritten before every use. Recovery recreates the storage zero-filled.+ Transient,+ /// The device keeps the last bytes it was given and uploads them again.+ Retained,+ /// A provider outside the device refills it; until then it is owed.+ Sourced,+};++/**+ * @brief A content policy. `provider` names who refills a Sourced object and `key`+ * what it refills; both are the provider's own vocabulary.+ */+class GfxContent {+public:+ static constexpr GfxContent transient() { return GfxContent{GfxContentKind::Transient, 0, 0}; }+ static constexpr GfxContent retained() { return GfxContent{GfxContentKind::Retained, 0, 0}; }+ static constexpr GfxContent sourced(u32 provider, u32 key) {+ return GfxContent{GfxContentKind::Sourced, provider, key};+ }++ constexpr GfxContentKind kind() const { return kind_; }+ constexpr u32 provider() const { return provider_; }+ constexpr u32 key() const { return key_; }++private:+ constexpr GfxContent(GfxContentKind kind, u32 provider, u32 key)+ : kind_(kind), provider_(provider), key_(key) {}++ GfxContentKind kind_;+ u32 provider_;+ u32 key_;+};++} // namespace esenginediff --git a/src/esengine/renderer/rhi/GfxDevice.cpp b/src/esengine/renderer/rhi/GfxDevice.cppnew file mode 100644index 000000000..b26e34436--- /dev/null+++ b/src/esengine/renderer/rhi/GfxDevice.cpp@@ -0,0 +1,738 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file GfxDevice.cpp+ * @brief The device's record of its objects, and recovery as one transaction over it.+ */++#include "./GfxDevice.hpp"+#include "../../core/Log.hpp"++#include <algorithm>+#include <cstring>++namespace esengine {++namespace {++bool isDepthFormat(GfxPixelFormat format) {+ return format == GfxPixelFormat::DepthComponent24 || format == GfxPixelFormat::Depth24Stencil8;+}++/**+ * Writes a block of pixels into an image kept as it would be uploaded without a+ * flip, so replaying the image never needs one. A flipped block lands its first+ * row at the top of its rectangle, which is what the upload flag means on both backends.+ */+void patchImage(std::vector<u8>& image, u32 imageWidth, u32 imageHeight, u32 bpp,+ i32 x, i32 y, u32 width, u32 height, const u8* pixels, bool flipY) {+ if (x < 0 || y < 0 || static_cast<u32>(x) + width > imageWidth+ || static_cast<u32>(y) + height > imageHeight) {+ return;+ }+ const usize rowBytes = static_cast<usize>(width) * bpp;+ for (u32 row = 0; row < height; ++row) {+ const u32 source = flipY ? height - 1 - row : row;+ std::memcpy(&image[(static_cast<usize>(y) + row) * imageWidth * bpp + static_cast<usize>(x) * bpp],+ pixels + static_cast<usize>(source) * rowBytes, rowBytes);+ }+}++std::vector<u8> uploadOrderImage(const TextureDesc& desc, const void* pixels) {+ const u32 bpp = gfxBytesPerPixel(desc.format);+ std::vector<u8> image(static_cast<usize>(desc.width) * desc.height * bpp, 0);+ if (pixels) {+ patchImage(image, desc.width, desc.height, bpp, 0, 0, desc.width, desc.height,+ static_cast<const u8*>(pixels), desc.flipY);+ }+ return image;+}++} // namespace++// =============================================================================+// Loss and recovery+// =============================================================================++bool GfxDevice::markDeviceLost(GfxDeviceLostReason reason, std::string message, std::string context) {+ if (device_status_ != GfxDeviceStatus::Live && device_status_ != GfxDeviceStatus::Recovering) {+ return false;+ }+ device_status_ = GfxDeviceStatus::Lost;+ device_info_.reason = reason;+ device_info_.identity = identity_;+ device_info_.message = std::move(message);+ device_info_.context = std::move(context);+ device_info_.frame = device_frame_;+ onDeviceLost();++ // Every object is rebuilt by the next recovery, owed or not.+ for (auto& [id, record] : registry_.buffers.all()) { record.realized = false; record.owed = false; }+ for (auto& [id, record] : registry_.textures.all()) { record.realized = false; record.owed = false; }+ for (auto& [id, record] : registry_.programs.all()) record.realized = false;+ for (auto& [id, record] : registry_.framebuffers.all()) record.realized = false;+ for (auto& [id, record] : registry_.timerQueries.all()) record.realized = false;+ owed_count_ = 0;+ native_locations_.clear();+ current_pipeline_ = PipelineHandle::Invalid;++ if (device_lost_handler_) device_lost_handler_(device_info_);+ return true;+}++bool GfxDevice::recoverDevice() {+ if (device_status_ == GfxDeviceStatus::Live || device_status_ == GfxDeviceStatus::Recovering) {+ return true;+ }+ if (device_status_ == GfxDeviceStatus::Dead) return false;++ device_status_ = GfxDeviceStatus::Recovering;+ if (!recreateDevice()) {+ device_status_ = GfxDeviceStatus::Lost;+ return false;+ }+ ++device_generation_;+ realizeRegistry();+ if (device_status_ != GfxDeviceStatus::Recovering) return isDeviceUsable();+ settleRecovery();+ return true;+}++void GfxDevice::realizeRegistry() {+ for (auto& [id, record] : registry_.programs.all()) {+ std::vector<GfxAttribBinding> bindings;+ bindings.reserve(record.attribBindings.size());+ for (const auto& [index, name] : record.attribBindings) bindings.push_back({index, name.c_str()});+ const GfxShaderSource source{record.language, record.vertex.c_str(), record.fragment.c_str()};+ std::string log;+ GfxShaderStage stage = GfxShaderStage::None;+ record.realized = backendCreateProgram(id, source, bindings.data(),+ static_cast<u32>(bindings.size()), &log, &stage);+ if (record.realized) {+ realizeProgramState(id, record);+ } else {+ ES_LOG_ERROR("Device recovery: program {} did not rebuild: {}", id, log);+ }+ }++ for (auto& [id, record] : registry_.buffers.all()) {+ const bool hasBytes = !record.bytes.empty();+ record.realized = backendCreateBuffer(id, record.desc, hasBytes ? record.bytes.data() : nullptr);+ record.owed = record.realized && !hasBytes && record.content.kind() == GfxContentKind::Sourced;+ if (record.owed) ++owed_count_;+ if (record.content.kind() != GfxContentKind::Retained) record.bytes.clear();+ }++ for (auto& [id, record] : registry_.textures.all()) {+ const bool hasBytes = !record.bytes.empty();+ if (record.compressed && hasBytes) {+ record.realized = backendCreateCompressedTexture(+ id, record.desc, record.compressedFormat, record.bytes.data(),+ static_cast<u32>(record.bytes.size()), record.mipLevels);+ } else {+ TextureDesc desc = record.desc;+ desc.flipY = false;+ if (record.compressed) desc.format = GfxPixelFormat::RGBA8;+ record.realized = backendCreateTexture(id, desc, hasBytes ? record.bytes.data() : nullptr);+ }+ record.owed = record.realized && !hasBytes && record.content.kind() == GfxContentKind::Sourced;+ if (record.owed) ++owed_count_;+ if (record.content.kind() != GfxContentKind::Retained) record.bytes.clear();+ if (!record.realized) ES_LOG_ERROR("Device recovery: texture {} did not rebuild", id);+ }++ for (auto& [id, record] : registry_.framebuffers.all()) {+ record.realized = backendCreateFramebuffer(id, record.desc);+ }+ for (auto& [id, record] : registry_.timerQueries.all()) {+ record.realized = backendCreateTimerQuery(id);+ }+}++void GfxDevice::realizeProgramState(u32 id, GfxProgramRecord& record) {+ const bool anyValue = std::any_of(record.uniformValues.begin(), record.uniformValues.end(),+ [](const GfxUniformValue& v) { return v.type != GfxUniformValue::Type::None; });+ if (anyValue) {+ backendUseProgram(id);+ for (usize i = 0; i < record.uniformValues.size(); ++i) {+ if (record.uniformValues[i].type == GfxUniformValue::Type::None) continue;+ const i32 native = nativeUniformLocation(record, id, static_cast<i32>(i));+ if (native >= 0) backendSetUniform(native, record.uniformValues[i]);+ }+ }+ for (usize i = 0; i < record.blockNames.size(); ++i) {+ if (record.blockBindings[i] == GFX_UNBOUND_BLOCK) continue;+ const u32 native = backendUniformBlockIndex(id, record.blockNames[i].c_str());+ if (native != GFX_INVALID_UNIFORM_BLOCK) {+ backendUniformBlockBinding(id, native, record.blockBindings[i]);+ }+ }+}++void GfxDevice::settleRecovery() {+ if (device_status_ != GfxDeviceStatus::Recovering || owed_count_ != 0) return;+ device_status_ = GfxDeviceStatus::Live;+ device_info_ = GfxDeviceLostInfo{};+ captureDeviceIdentity();+}++void GfxDevice::payTexture(u32 id, GfxTextureRecord& record) {+ if (!record.owed) return;+ record.owed = false;+ --owed_count_;+ if (record.desc.mipmaps && record.realized) backendGenerateMipmaps(id);+ settleRecovery();+}++void GfxDevice::forgoContent(const GfxOwedContent& owed) {+ if (owed.kind == GfxOwedContent::Kind::Buffer) {+ if (auto* record = registry_.buffers.find(owed.id); record && record->owed) {+ record->owed = false;+ --owed_count_;+ }+ } else if (auto* record = registry_.textures.find(owed.id); record && record->owed) {+ record->owed = false;+ --owed_count_;+ }+ settleRecovery();+}++// =============================================================================+// Buffers+// =============================================================================++BufferHandle GfxDevice::createBuffer(const BufferDesc& desc, GfxContent content, const void* initialData) {+ if (device_status_ == GfxDeviceStatus::Dead) return BufferHandle::Invalid;+ const bool usable = isDeviceUsable();+ GfxBufferRecord record{desc, content};+ if (content.kind() == GfxContentKind::Retained || (!usable && initialData)) {+ record.bytes.assign(desc.size, 0);+ if (initialData && desc.size > 0) std::memcpy(record.bytes.data(), initialData, desc.size);+ }+ const u32 id = registry_.buffers.insert(std::move(record));+ if (!usable) return BufferHandle{id};+ if (!backendCreateBuffer(id, desc, initialData)) {+ registry_.buffers.erase(id);+ return BufferHandle::Invalid;+ }+ registry_.buffers.find(id)->realized = true;+ return BufferHandle{id};+}++void GfxDevice::deleteBuffer(BufferHandle buffer) {+ const u32 id = static_cast<u32>(buffer);+ auto* record = registry_.buffers.find(id);+ if (!record) return;+ if (record->realized) backendDeleteBuffer(id);+ if (record->owed) --owed_count_;+ registry_.buffers.erase(id);+ settleRecovery();+}++void GfxDevice::updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) {+ const u32 id = static_cast<u32>(buffer);+ auto* record = registry_.buffers.find(id);+ if (!record || !data || sizeBytes == 0) return;+ const bool whole = offsetBytes == 0 && sizeBytes >= record->desc.size;+ if (!record->bytes.empty() && static_cast<usize>(offsetBytes) + sizeBytes <= record->bytes.size()) {+ std::memcpy(record->bytes.data() + offsetBytes, data, sizeBytes);+ } else if (!record->realized && whole) {+ record->bytes.assign(static_cast<const u8*>(data), static_cast<const u8*>(data) + record->desc.size);+ }+ if (record->realized) backendUpdateBuffer(id, offsetBytes, data, sizeBytes);+ if (record->owed && whole) {+ record->owed = false;+ --owed_count_;+ settleRecovery();+ }+}++void GfxDevice::resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) {+ const u32 id = static_cast<u32>(buffer);+ auto* record = registry_.buffers.find(id);+ if (!record) return;+ record->desc.size = sizeBytes;+ if (record->content.kind() == GfxContentKind::Retained || (!record->realized && data)) {+ record->bytes.assign(sizeBytes, 0);+ if (data && sizeBytes > 0) std::memcpy(record->bytes.data(), data, sizeBytes);+ } else {+ record->bytes.clear();+ }+ if (record->realized) backendResizeBuffer(id, record->desc, data);+ if (record->owed && data) {+ record->owed = false;+ --owed_count_;+ settleRecovery();+ }+}++const BufferDesc* GfxDevice::bufferDesc(BufferHandle buffer) const {+ const auto* record = registry_.buffers.find(static_cast<u32>(buffer));+ return record ? &record->desc : nullptr;+}++// =============================================================================+// Vertex layouts and pipelines+// =============================================================================++VertexLayoutHandle GfxDevice::createVertexLayout(const VertexLayoutDesc& desc) {+ if (device_status_ == GfxDeviceStatus::Dead || !backendAcceptsVertexLayout(desc)) {+ return VertexLayoutHandle::Invalid;+ }+ return VertexLayoutHandle{registry_.layouts.insert(GfxLayoutRecord{desc})};+}++void GfxDevice::deleteVertexLayout(VertexLayoutHandle layout) {+ const u32 id = static_cast<u32>(layout);+ if (!registry_.layouts.find(id)) return;+ backendDeleteVertexLayout(id);+ registry_.layouts.erase(id);+}++const VertexLayoutDesc* GfxDevice::vertexLayoutDesc(VertexLayoutHandle layout) const {+ const auto* record = registry_.layouts.find(static_cast<u32>(layout));+ return record ? &record->desc : nullptr;+}++PipelineHandle GfxDevice::createPipeline(const PipelineDesc& desc) {+ if (device_status_ == GfxDeviceStatus::Dead) return PipelineHandle::Invalid;+ if (const u32 existing = registry_.findPipeline(desc)) return PipelineHandle{existing};+ return PipelineHandle{registry_.pipelines.insert(GfxPipelineRecord{desc})};+}++const PipelineDesc* GfxDevice::pipelineDesc(PipelineHandle handle) const {+ const auto* record = registry_.pipelines.find(static_cast<u32>(handle));+ return record ? &record->desc : nullptr;+}++void GfxDevice::setPipeline(PipelineHandle handle) {+ if (handle == PipelineHandle::Invalid) return;+ const auto* record = registry_.pipelines.find(static_cast<u32>(handle));+ if (!record) return;+ current_pipeline_ = handle;+ current_program_ = record->desc.program;+ backendSetPipeline(static_cast<u32>(handle), record->desc);+}++void GfxDevice::invalidatePipelineCache() {+ current_pipeline_ = PipelineHandle::Invalid;+ backendInvalidatePipelineCache();+}++// =============================================================================+// Textures+// =============================================================================++TextureHandle GfxDevice::createTexture(const TextureDesc& desc, GfxContent content, const void* pixels) {+ if (device_status_ == GfxDeviceStatus::Dead) return TextureHandle::Invalid;+ const bool usable = isDeviceUsable();+ GfxTextureRecord record{desc, content};+ if (content.kind() == GfxContentKind::Retained && (desc.samples > 1 || isDepthFormat(desc.format))) {+ ES_LOG_ERROR("GfxDevice::createTexture: an attachment-only texture cannot keep its contents");+ } else if (content.kind() == GfxContentKind::Retained || (!usable && pixels)) {+ record.bytes = uploadOrderImage(desc, pixels);+ record.desc.flipY = false;+ }+ const u32 id = registry_.textures.insert(std::move(record));+ if (!usable) return TextureHandle{id};+ if (!backendCreateTexture(id, desc, pixels)) {+ registry_.textures.erase(id);+ return TextureHandle::Invalid;+ }+ registry_.textures.find(id)->realized = true;+ return TextureHandle{id};+}++TextureHandle GfxDevice::createCompressedTexture(const TextureDesc& desc, GfxContent content,+ GfxCompressedFormat format, const void* data,+ u32 byteLength, u32 mipLevels) {+ if (device_status_ == GfxDeviceStatus::Dead) return TextureHandle::Invalid;+ const bool usable = isDeviceUsable();+ GfxTextureRecord record{desc, content};+ record.compressed = true;+ record.compressedFormat = format;+ record.mipLevels = mipLevels ? mipLevels : 1;+ if (data && (content.kind() == GfxContentKind::Retained || !usable)) {+ record.bytes.assign(static_cast<const u8*>(data), static_cast<const u8*>(data) + byteLength);+ }+ const u32 id = registry_.textures.insert(std::move(record));+ if (!usable) return TextureHandle{id};+ if (!backendCreateCompressedTexture(id, desc, format, data, byteLength, mipLevels)) {+ registry_.textures.erase(id);+ return TextureHandle::Invalid;+ }+ registry_.textures.find(id)->realized = true;+ return TextureHandle{id};+}++bool GfxDevice::restoreCompressedTexture(TextureHandle texture, GfxCompressedFormat format,+ const void* data, u32 byteLength, u32 mipLevels) {+ const u32 id = static_cast<u32>(texture);+ auto* record = registry_.textures.find(id);+ if (!record || !isDeviceUsable()) return false;+ if (record->realized) backendDeleteTexture(id);+ record->compressed = true;+ record->compressedFormat = format;+ record->mipLevels = mipLevels ? mipLevels : 1;+ if (record->content.kind() == GfxContentKind::Retained) {+ record->bytes.assign(static_cast<const u8*>(data), static_cast<const u8*>(data) + byteLength);+ }+ record->realized = backendCreateCompressedTexture(id, record->desc, format, data, byteLength, mipLevels);+ if (record->realized) payTexture(id, *record);+ return record->realized;+}++TextureHandle GfxDevice::importExternalTexture(u32 nativeId, const TextureDesc& desc, GfxContent content) {+ if (device_status_ == GfxDeviceStatus::Dead) return TextureHandle::Invalid;+ if (content.kind() == GfxContentKind::Retained) {+ ES_LOG_ERROR("GfxDevice::importExternalTexture: the device never saw these pixels to keep them");+ return TextureHandle::Invalid;+ }+ const u32 id = registry_.textures.insert(GfxTextureRecord{desc, content});+ if (!isDeviceUsable()) return TextureHandle{id};+ if (!backendAdoptTexture(id, nativeId, desc)) {+ registry_.textures.erase(id);+ return TextureHandle::Invalid;+ }+ registry_.textures.find(id)->realized = true;+ return TextureHandle{id};+}++bool GfxDevice::restoreTextureFromNative(TextureHandle texture, u32 nativeId) {+ const u32 id = static_cast<u32>(texture);+ auto* record = registry_.textures.find(id);+ if (!record || !isDeviceUsable()) return false;+ if (record->realized) backendDeleteTexture(id);+ record->realized = backendAdoptTexture(id, nativeId, record->desc);+ if (record->realized) payTexture(id, *record);+ return record->realized;+}++bool GfxDevice::adoptTextureContent(TextureHandle into, TextureHandle from) {+ const u32 intoId = static_cast<u32>(into);+ const u32 fromId = static_cast<u32>(from);+ auto* target = registry_.textures.find(intoId);+ auto* source = registry_.textures.find(fromId);+ if (!target || !source || intoId == fromId || !source->realized) return false;+ if (target->content.kind() == GfxContentKind::Retained && source->bytes.empty()) {+ ES_LOG_ERROR("GfxDevice::adoptTextureContent: texture {} keeps its bytes and {} has none to give",+ intoId, fromId);+ return false;+ }+ if (target->realized) backendDeleteTexture(intoId);+ backendMoveTexture(intoId, fromId);++ target->desc = source->desc;+ target->compressed = source->compressed;+ target->compressedFormat = source->compressedFormat;+ target->mipLevels = source->mipLevels;+ target->realized = true;+ if (target->content.kind() == GfxContentKind::Retained) {+ target->bytes = std::move(source->bytes);+ } else {+ target->bytes.clear();+ }+ if (source->owed) --owed_count_;+ const bool owed = target->owed;+ registry_.textures.erase(fromId);+ if (owed) {+ target->owed = false;+ --owed_count_;+ }+ settleRecovery();+ return true;+}++void GfxDevice::deleteTexture(TextureHandle texture) {+ const u32 id = static_cast<u32>(texture);+ auto* record = registry_.textures.find(id);+ if (!record) return;+ if (record->realized) backendDeleteTexture(id);+ if (record->owed) --owed_count_;+ registry_.textures.erase(id);+ settleRecovery();+}++void GfxDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY) {+ const u32 id = static_cast<u32>(texture);+ auto* record = registry_.textures.find(id);+ if (!record || !pixels || record->compressed) return;+ const TextureDesc& desc = record->desc;+ const bool whole = x == 0 && y == 0 && width >= desc.width && height >= desc.height;+ if (!record->bytes.empty()) {+ patchImage(record->bytes, desc.width, desc.height, gfxBytesPerPixel(desc.format),+ x, y, width, height, static_cast<const u8*>(pixels), flipY);+ } else if (!record->realized && whole) {+ TextureDesc upload = desc;+ upload.flipY = flipY;+ record->bytes = uploadOrderImage(upload, pixels);+ }+ if (record->realized) backendUpdateTexture(id, x, y, width, height, pixels, flipY);+ if (whole) payTexture(id, *record);+}++void GfxDevice::setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag,+ TextureWrap wrapS, TextureWrap wrapT) {+ const u32 id = static_cast<u32>(texture);+ auto* record = registry_.textures.find(id);+ if (!record) return;+ record->desc.minFilter = min;+ record->desc.magFilter = mag;+ record->desc.wrapS = wrapS;+ record->desc.wrapT = wrapT;+ if (record->realized) backendSetTextureParams(id, record->desc);+}++void GfxDevice::generateMipmaps(TextureHandle texture) {+ const u32 id = static_cast<u32>(texture);+ auto* record = registry_.textures.find(id);+ if (!record) return;+ record->desc.mipmaps = true;+ if (record->realized) backendGenerateMipmaps(id);+}++const TextureDesc* GfxDevice::textureDesc(TextureHandle texture) const {+ const auto* record = registry_.textures.find(static_cast<u32>(texture));+ return record ? &record->desc : nullptr;+}++// =============================================================================+// Programs+// =============================================================================++ShaderHandle GfxDevice::createProgram(const GfxShaderSource& source,+ const GfxAttribBinding* bindings, u32 bindingCount,+ std::string* outLog, GfxShaderStage* outFailedStage) {+ if (device_status_ == GfxDeviceStatus::Dead) {+ if (outLog) *outLog = "device dead";+ return ShaderHandle::Invalid;+ }+ GfxProgramRecord record;+ record.language = source.language;+ record.vertex = source.vertexSrc ? source.vertexSrc : "";+ record.fragment = source.fragmentSrc ? source.fragmentSrc : "";+ for (u32 i = 0; i < bindingCount; ++i) {+ record.attribBindings.emplace_back(bindings[i].index, bindings[i].name ? bindings[i].name : "");+ }+ const u32 id = registry_.programs.insert(std::move(record));+ if (!isDeviceUsable()) return ShaderHandle{id};+ if (!backendCreateProgram(id, source, bindings, bindingCount, outLog, outFailedStage)) {+ registry_.programs.erase(id);+ return ShaderHandle::Invalid;+ }+ registry_.programs.find(id)->realized = true;+ return ShaderHandle{id};+}++void GfxDevice::deleteProgram(ShaderHandle program) {+ const u32 id = static_cast<u32>(program);+ auto* record = registry_.programs.find(id);+ if (!record) return;+ if (record->realized) backendDeleteProgram(id);+ registry_.programs.erase(id);+ native_locations_.erase(id);+ if (current_program_ == program) current_program_ = ShaderHandle::Invalid;+}++void GfxDevice::useProgram(ShaderHandle program) {+ const u32 id = static_cast<u32>(program);+ current_program_ = program;+ if (!isDeviceUsable()) return;+ const auto* record = registry_.programs.find(id);+ if (!record) {+ backendUseProgram(0);+ } else if (record->realized) {+ backendUseProgram(id);+ }+}++i32 GfxDevice::nativeUniformLocation(GfxProgramRecord& record, u32 id, i32 location) {+ auto& natives = native_locations_[id];+ if (natives.size() < record.uniformNames.size()) natives.resize(record.uniformNames.size(), -2);+ i32& native = natives[static_cast<usize>(location)];+ if (native == -2) native = backendUniformLocation(id, record.uniformNames[static_cast<usize>(location)].c_str());+ return native;+}++i32 GfxDevice::getUniformLocation(ShaderHandle program, const char* name) {+ const u32 id = static_cast<u32>(program);+ auto* record = registry_.programs.find(id);+ if (!record || !name) return -1;+ auto it = std::find(record->uniformNames.begin(), record->uniformNames.end(), name);+ if (it != record->uniformNames.end()) {+ return static_cast<i32>(it - record->uniformNames.begin());+ }+ if (record->realized && backendUniformLocation(id, name) < 0) return -1;+ record->uniformNames.emplace_back(name);+ record->uniformValues.emplace_back();+ return static_cast<i32>(record->uniformNames.size() - 1);+}++i32 GfxDevice::getAttribLocation(ShaderHandle program, const char* name) {+ const u32 id = static_cast<u32>(program);+ const auto* record = registry_.programs.find(id);+ return record && record->realized ? backendAttribLocation(id, name) : -1;+}++void GfxDevice::setUniformValue(i32 location, const GfxUniformValue& value) {+ const u32 id = static_cast<u32>(current_program_);+ auto* record = registry_.programs.find(id);+ if (!record || location < 0 || static_cast<usize>(location) >= record->uniformValues.size()) return;+ record->uniformValues[static_cast<usize>(location)] = value;+ if (!record->realized) return;+ const i32 native = nativeUniformLocation(*record, id, location);+ if (native >= 0) backendSetUniform(native, value);+}++void GfxDevice::setUniform1i(i32 location, i32 value) {+ GfxUniformValue v;+ v.type = GfxUniformValue::Type::Int;+ v.i = value;+ setUniformValue(location, v);+}++void GfxDevice::setUniform1f(i32 location, f32 value) {+ GfxUniformValue v;+ v.type = GfxUniformValue::Type::Float;+ v.f[0] = value;+ setUniformValue(location, v);+}++void GfxDevice::setUniform2f(i32 location, f32 x, f32 y) {+ GfxUniformValue v;+ v.type = GfxUniformValue::Type::Vec2;+ v.f[0] = x;+ v.f[1] = y;+ setUniformValue(location, v);+}++void GfxDevice::setUniform3f(i32 location, f32 x, f32 y, f32 z) {+ GfxUniformValue v;+ v.type = GfxUniformValue::Type::Vec3;+ v.f[0] = x;+ v.f[1] = y;+ v.f[2] = z;+ setUniformValue(location, v);+}++void GfxDevice::setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) {+ GfxUniformValue v;+ v.type = GfxUniformValue::Type::Vec4;+ v.f[0] = x;+ v.f[1] = y;+ v.f[2] = z;+ v.f[3] = w;+ setUniformValue(location, v);+}++void GfxDevice::setUniformMat3(i32 location, const f32* data) {+ if (!data) return;+ GfxUniformValue v;+ v.type = GfxUniformValue::Type::Mat3;+ std::memcpy(v.f, data, 9 * sizeof(f32));+ setUniformValue(location, v);+}++void GfxDevice::setUniformMat4(i32 location, const f32* data) {+ if (!data) return;+ GfxUniformValue v;+ v.type = GfxUniformValue::Type::Mat4;+ std::memcpy(v.f, data, 16 * sizeof(f32));+ setUniformValue(location, v);+}++std::vector<GfxUniformInfo> GfxDevice::getActiveUniforms(ShaderHandle program) {+ const u32 id = static_cast<u32>(program);+ auto* record = registry_.programs.find(id);+ if (!record || !record->realized) return {};+ std::vector<GfxUniformInfo> infos = backendActiveUniforms(id);+ for (GfxUniformInfo& info : infos) {+ const i32 native = info.location;+ info.location = getUniformLocation(program, info.name.c_str());+ if (info.location >= 0) {+ auto& natives = native_locations_[id];+ if (natives.size() < record->uniformNames.size()) natives.resize(record->uniformNames.size(), -2);+ natives[static_cast<usize>(info.location)] = native;+ }+ }+ return infos;+}++u32 GfxDevice::getUniformBlockIndex(ShaderHandle program, const char* name) {+ const u32 id = static_cast<u32>(program);+ auto* record = registry_.programs.find(id);+ if (!record || !name) return GFX_INVALID_UNIFORM_BLOCK;+ auto it = std::find(record->blockNames.begin(), record->blockNames.end(), name);+ if (it != record->blockNames.end()) return static_cast<u32>(it - record->blockNames.begin());+ if (record->realized && backendUniformBlockIndex(id, name) == GFX_INVALID_UNIFORM_BLOCK) {+ return GFX_INVALID_UNIFORM_BLOCK;+ }+ record->blockNames.emplace_back(name);+ record->blockBindings.push_back(GFX_UNBOUND_BLOCK);+ return static_cast<u32>(record->blockNames.size() - 1);+}++void GfxDevice::uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) {+ const u32 id = static_cast<u32>(program);+ auto* record = registry_.programs.find(id);+ if (!record || blockIndex >= record->blockNames.size()) return;+ record->blockBindings[blockIndex] = bindingPoint;+ if (!record->realized) return;+ const u32 native = backendUniformBlockIndex(id, record->blockNames[blockIndex].c_str());+ if (native != GFX_INVALID_UNIFORM_BLOCK) backendUniformBlockBinding(id, native, bindingPoint);+}++// =============================================================================+// Framebuffers and queries+// =============================================================================++FramebufferHandle GfxDevice::createFramebuffer(const FramebufferDesc& desc) {+ if (device_status_ == GfxDeviceStatus::Dead) return FramebufferHandle::Default;+ const u32 id = registry_.framebuffers.insert(GfxFramebufferRecord{desc});+ if (!isDeviceUsable()) return FramebufferHandle{id};+ if (!backendCreateFramebuffer(id, desc)) {+ registry_.framebuffers.erase(id);+ return FramebufferHandle::Default;+ }+ registry_.framebuffers.find(id)->realized = true;+ return FramebufferHandle{id};+}++void GfxDevice::deleteFramebuffer(FramebufferHandle framebuffer) {+ const u32 id = static_cast<u32>(framebuffer);+ auto* record = registry_.framebuffers.find(id);+ if (!record) return;+ if (record->realized) backendDeleteFramebuffer(id);+ registry_.framebuffers.erase(id);+}++const FramebufferDesc* GfxDevice::framebufferDesc(FramebufferHandle framebuffer) const {+ const auto* record = registry_.framebuffers.find(static_cast<u32>(framebuffer));+ return record ? &record->desc : nullptr;+}++u32 GfxDevice::createTimerQuery() {+ if (!isDeviceUsable()) return 0;+ const u32 id = registry_.timerQueries.insert(GfxTimerQueryRecord{});+ if (!backendCreateTimerQuery(id)) {+ registry_.timerQueries.erase(id);+ return 0;+ }+ registry_.timerQueries.find(id)->realized = true;+ return id;+}++GfxLiveObjects GfxDevice::liveObjects() const {+ return GfxLiveObjects{+ registry_.buffers.size(),+ registry_.textures.size(),+ registry_.programs.size(),+ registry_.layouts.size(),+ registry_.pipelines.size(),+ registry_.framebuffers.size(),+ backendReadbackCount(),+ };+}++} // namespace esenginediff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hppindex b92f833ad..fed1b3a5b 100644--- a/src/esengine/renderer/rhi/GfxDevice.hpp+++ b/src/esengine/renderer/rhi/GfxDevice.hpp@@ -23,10 +23,13 @@#include "../../core/Types.hpp"#include "../draw/BlendMode.hpp"+#include "./GfxContent.hpp"#include "./GfxEnums.hpp"+#include "./GfxResourceRegistry.hpp"#include "./PipelineState.hpp"#include <functional>+#include <map>#include <string>#include <utility>#include <vector>@@ -149,36 +152,21 @@ public:}/**- * @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;- }- ++device_generation_;- return true;- }+ * @brief Rebuilds the device and every object it issued, behind the same handles.+ * @details Runs once per loss. Retained content is uploaded again and Sourced+ * content becomes owed; the device turns Live when nothing is owed.+ * @return True when the device is usable (Recovering or Live).+ */+ bool recoverDevice();++ /** @brief Sourced objects that have storage again and are waiting for their contents. */+ std::vector<GfxOwedContent> owedContent() const { return registry_.owed(); }/**- * @brief The content is back: the device is fully itself again.- * @details Called by the layer that re-uploaded what the backend could not.+ * @brief Gives up on one owed object's contents: it keeps its placeholder.+ * @details For a provider that no longer exists. Logged by the caller, never silent.*/- void markDeviceRestored() {- if (device_status_ != GfxDeviceStatus::Recovering) return;- device_status_ = GfxDeviceStatus::Live;- device_info_ = GfxDeviceLostInfo{};- captureDeviceIdentity();- }+ void forgoContent(const GfxOwedContent& owed);/*** @brief Gives up on the device: no further recovery will be attempted.@@ -283,22 +271,26 @@ public:/*** @brief Creates a buffer with fixed capacity and optional initial contents.+ * @param content Who restores the contents after a loss.* @param initialData When non-null, `desc.size` bytes uploaded at creation.*/- virtual BufferHandle createBuffer(const BufferDesc& desc, const void* initialData) = 0;+ BufferHandle createBuffer(const BufferDesc& desc, GfxContent content, const void* initialData);/** @brief Deletes a buffer */- virtual void deleteBuffer(BufferHandle buffer) = 0;+ void deleteBuffer(BufferHandle buffer);/** @brief Updates a sub-range of a buffer; must fit within its capacity. */- virtual void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) = 0;+ void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes);/*** @brief Re-specifies a buffer's store with a new capacity, discarding prior contents.* @details The handle stays valid (streaming growth without re-wiring vertex* layouts). `data` may be null to allocate uninitialized storage.*/- virtual void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) = 0;+ void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data);++ /** @brief A buffer's description as it stands, or null for a handle that names none. */+ const BufferDesc* bufferDesc(BufferHandle buffer) const;/** @brief Binds a buffer to a uniform binding slot (the block index shaders are linked to). */virtual void setUniformBuffer(u32 slot, BufferHandle buffer) = 0;@@ -308,10 +300,13 @@ public:// =========================================================================/** @brief Registers an immutable vertex layout; pipelines reference it by handle. */- virtual VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc) = 0;+ VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc);/** @brief Deletes a vertex layout (no pipeline may reference it afterwards) */- virtual void deleteVertexLayout(VertexLayoutHandle layout) = 0;+ void deleteVertexLayout(VertexLayoutHandle layout);++ /** @brief A layout's description, or null for a handle that names none. */+ const VertexLayoutDesc* vertexLayoutDesc(VertexLayoutHandle layout) const;/*** @brief Binds a vertex buffer to a layout slot for subsequent draws.@@ -332,7 +327,7 @@ public:* @details Storage is allocated either way. `desc.mipmaps` generates mipmaps* after the initial upload.*/- virtual TextureHandle createTexture(const TextureDesc& desc, const void* pixels) = 0;+ TextureHandle createTexture(const TextureDesc& desc, GfxContent content, const void* pixels);/*** @brief Creates a texture from pre-compressed GPU block data.@@ -344,32 +339,51 @@ public:* `max(1, width>>i) x max(1, height>>i)`.* @param mipLevels Number of mip levels present (1 = base only).*/- virtual TextureHandle createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,- const void* data, u32 byteLength, u32 mipLevels) = 0;+ TextureHandle createCompressedTexture(const TextureDesc& desc, GfxContent content,+ GfxCompressedFormat format, const void* data,+ u32 byteLength, u32 mipLevels);++ /** @brief Puts compressed contents back behind an owed texture's handle. */+ bool restoreCompressedTexture(TextureHandle texture, GfxCompressedFormat format,+ const void* data, u32 byteLength, u32 mipLevels);++ /**+ * @brief Adopts a texture a host created with the device's own API (a JS-side WebGL upload).+ * @details The device owns it from here and, after a loss, recreates storage of+ * `desc` behind the same handle for the provider in @p content to refill.+ */+ TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc, GfxContent content);++ /** @brief Replaces the native texture behind @p texture with one the host created again. */+ bool restoreTextureFromNative(TextureHandle texture, u32 nativeId);/**- * @brief Wraps a texture created outside the device (e.g. a JS-side WebGL upload).- * @details Registers the metadata updates/binds need; ownership stays external,- * so the wrapper must not delete it.+ * @brief Moves @p from's storage and description behind @p into, and ends @p from.+ * @details How a provider pays an owed texture: it loads the content the way it+ * always does, into a texture of its own, and hands that over. @p into+ * keeps its handle and content policy; @p from names nothing afterwards.*/- virtual TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc) = 0;+ bool adoptTextureContent(TextureHandle into, TextureHandle from);/** @brief Deletes a texture */- virtual void deleteTexture(TextureHandle texture) = 0;+ void deleteTexture(TextureHandle texture);/*** @brief Uploads pixels to a sub-rectangle of a texture (transfer format from its desc).* @param flipY Vertical flip on upload (WebGL upload state; no-op on native backends).*/- virtual void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,- const void* pixels, bool flipY) = 0;+ void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY);/** @brief Sets texture filtering and wrap parameters */- virtual void setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag,- TextureWrap wrapS, TextureWrap wrapT) = 0;+ void setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag,+ TextureWrap wrapS, TextureWrap wrapT);/** @brief Generates mipmaps for a texture */- virtual void generateMipmaps(TextureHandle texture) = 0;+ void generateMipmaps(TextureHandle texture);++ /** @brief A texture's description as it stands, or null for a handle that names none. */+ const TextureDesc* textureDesc(TextureHandle texture) const;/** @brief Activates a texture slot and binds a 2D texture */virtual void bindTexture(u32 slot, TextureHandle texture) = 0;@@ -414,9 +428,9 @@ public:* @param outFailedStage Optional; receives the stage that rejected the source.* @return The linked program handle, or Invalid on failure.*/- virtual ShaderHandle createProgram(const GfxShaderSource& source,- const GfxAttribBinding* bindings, u32 bindingCount,- std::string* outLog, GfxShaderStage* outFailedStage) = 0;+ ShaderHandle createProgram(const GfxShaderSource& source,+ const GfxAttribBinding* bindings, u32 bindingCount,+ std::string* outLog, GfxShaderStage* outFailedStage);/** @brief Whether this backend compiles @p language (GL: GLSL ES 300; WebGPU: WGSL). */virtual bool supportsShaderLanguage(GfxShaderLanguage language) const = 0;@@ -432,59 +446,66 @@ public:virtual bool textureOriginTopLeft() const = 0;/** @brief Deletes a shader program */- virtual void deleteProgram(ShaderHandle program) = 0;+ void deleteProgram(ShaderHandle program);/*** @brief Binds a program directly, for setup-time uniform seeding.* @details Per-frame rendering binds programs through setPipeline.*/- virtual void useProgram(ShaderHandle program) = 0;+ void useProgram(ShaderHandle program);- /** @brief Gets a uniform location by name */- virtual i32 getUniformLocation(ShaderHandle program, const char* name) = 0;+ /**+ * @brief Gets a uniform location by name, -1 when the linked program has none.+ * @details The location belongs to the device, not the backend: it stays valid+ * across a relink, and the value last set through it is set again.+ */+ i32 getUniformLocation(ShaderHandle program, const char* name);/** @brief Gets a vertex attribute location by name (-1 if not found) */- virtual i32 getAttribLocation(ShaderHandle program, const char* name) = 0;+ i32 getAttribLocation(ShaderHandle program, const char* name);- /** @brief Sets an integer uniform */- virtual void setUniform1i(i32 location, i32 value) = 0;+ /** @brief Sets an integer uniform of the bound program */+ void setUniform1i(i32 location, i32 value);/** @brief Sets a float uniform */- virtual void setUniform1f(i32 location, f32 value) = 0;+ void setUniform1f(i32 location, f32 value);/** @brief Sets a vec2 uniform */- virtual void setUniform2f(i32 location, f32 x, f32 y) = 0;+ void setUniform2f(i32 location, f32 x, f32 y);/** @brief Sets a vec3 uniform */- virtual void setUniform3f(i32 location, f32 x, f32 y, f32 z) = 0;+ void setUniform3f(i32 location, f32 x, f32 y, f32 z);/** @brief Sets a vec4 uniform */- virtual void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) = 0;+ void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w);/** @brief Sets a mat3 uniform */- virtual void setUniformMat3(i32 location, const f32* data) = 0;+ void setUniformMat3(i32 location, const f32* data);/** @brief Sets a mat4 uniform */- virtual void setUniformMat4(i32 location, const f32* data) = 0;+ void setUniformMat4(i32 location, const f32* data);/** @brief Enumerates all active uniforms of a linked shader program */- virtual std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle program) = 0;+ std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle program);/** @brief Returns a program's uniform-block index by name, or GFX_INVALID_UNIFORM_BLOCK if absent. */- virtual u32 getUniformBlockIndex(ShaderHandle program, const char* name) = 0;+ u32 getUniformBlockIndex(ShaderHandle program, const char* name);/** @brief Links a program's uniform block to an indexed binding slot. */- virtual void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) = 0;+ void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint);// =========================================================================// Pipeline State (immutable "how to draw"; see PipelineState.hpp)// =========================================================================/** @brief Resolves a pipeline description to a cached handle (creating it on first use). */- virtual PipelineHandle createPipeline(const PipelineDesc& desc) = 0;+ PipelineHandle createPipeline(const PipelineDesc& desc);++ /** @brief A pipeline's description, or null for a handle that names none. */+ const PipelineDesc* pipelineDesc(PipelineHandle handle) const;/** @brief Binds a pipeline: applies its program, blend, depth, stencil compare/op and culling. */- virtual void setPipeline(PipelineHandle handle) = 0;+ void setPipeline(PipelineHandle handle);/** @brief Sets the dynamic stencil reference for the bound pipeline's stencil mode (no-op if Off). */virtual void setStencilReference(i32 ref) = 0;@@ -495,7 +516,7 @@ public:* pipeline left bound by a prior phase — or by a direct-state path like custom* geometry — is not mistaken for the current one.*/- virtual void invalidatePipelineCache() = 0;+ void invalidatePipelineCache();// =========================================================================// Draw Calls@@ -519,10 +540,13 @@ public:* @return The framebuffer handle, or Default (0) when incomplete — the default* framebuffer can never be created, so 0 unambiguously means failure.*/- virtual FramebufferHandle createFramebuffer(const FramebufferDesc& desc) = 0;+ FramebufferHandle createFramebuffer(const FramebufferDesc& desc);/** @brief Deletes a framebuffer (its attachment textures are owned by the caller) */- virtual void deleteFramebuffer(FramebufferHandle framebuffer) = 0;+ void deleteFramebuffer(FramebufferHandle framebuffer);++ /** @brief A framebuffer's description, or null for Default and unknown handles. */+ const FramebufferDesc* framebufferDesc(FramebufferHandle framebuffer) const;// =========================================================================// Render Pass@@ -614,7 +638,7 @@ public:// =========================================================================/** @brief Creates a GPU elapsed-time query, or 0 when the backend cannot time GPU work. */- virtual u32 createTimerQuery() = 0;+ u32 createTimerQuery();/** @brief Starts timing GPU work into a query; one query may be active at a time. */virtual void beginTimerQuery(u32 query) = 0;@@ -647,16 +671,63 @@ public:/** @brief Queries a backend integer capability/limit */virtual i32 getInt(GfxIntParam name) = 0;- /**- * @brief GPU objects alive right now (see {@link GfxLiveObjects}).- * @details Not pure: a backend that cannot answer reports zeros rather than- * forcing every device to carry the bookkeeping. The census treats- * an all-zero result as "this backend does not report", which is a- * different claim than "nothing is allocated" — see censusProbes.ts.- */- virtual GfxLiveObjects liveObjects() const { return {}; }+ /** @brief GPU objects alive right now (see {@link GfxLiveObjects}), read off the registry. */+ GfxLiveObjects liveObjects() const;protected:+ // =========================================================================+ // Backend primitives. `id` is the handle's value; the backend maps it to its+ // own object for the current generation and nothing else.+ // =========================================================================++ virtual bool backendCreateBuffer(u32 id, const BufferDesc& desc, const void* data) = 0;+ virtual void backendDeleteBuffer(u32 id) = 0;+ virtual void backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) = 0;+ virtual void backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) = 0;++ virtual bool backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) = 0;+ virtual bool backendCreateCompressedTexture(u32 id, const TextureDesc& desc, GfxCompressedFormat format,+ const void* data, u32 byteLength, u32 mipLevels) = 0;+ /** @brief Takes over a native texture the host created; false when this backend cannot. */+ virtual bool backendAdoptTexture(u32 id, u32 nativeId, const TextureDesc& desc) = 0;+ virtual void backendDeleteTexture(u32 id) = 0;+ /** @brief Re-keys @p from's native texture under @p into; @p into holds none on entry. */+ virtual void backendMoveTexture(u32 into, u32 from) = 0;+ virtual void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY) = 0;+ virtual void backendSetTextureParams(u32 id, const TextureDesc& desc) = 0;+ virtual void backendGenerateMipmaps(u32 id) = 0;++ virtual bool backendCreateProgram(u32 id, const GfxShaderSource& source,+ const GfxAttribBinding* bindings, u32 bindingCount,+ std::string* outLog, GfxShaderStage* outFailedStage) = 0;+ virtual void backendDeleteProgram(u32 id) = 0;+ virtual void backendUseProgram(u32 id) = 0;+ /** @brief The backend's own location this generation, -1 when absent. */+ virtual i32 backendUniformLocation(u32 program, const char* name) = 0;+ virtual i32 backendAttribLocation(u32 program, const char* name) = 0;+ virtual void backendSetUniform(i32 nativeLocation, const GfxUniformValue& value) = 0;+ virtual std::vector<GfxUniformInfo> backendActiveUniforms(u32 program) = 0;+ virtual u32 backendUniformBlockIndex(u32 program, const char* name) = 0;+ virtual void backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint) = 0;++ /** @brief False for a layout this backend has no way to express. */+ virtual bool backendAcceptsVertexLayout(const VertexLayoutDesc& desc) { (void)desc; return true; }+ /** @brief Drops what the backend derived from a layout (a GL VAO); the desc stays here. */+ virtual void backendDeleteVertexLayout(u32 id) = 0;+ virtual void backendSetPipeline(u32 id, const PipelineDesc& desc) = 0;+ virtual void backendInvalidatePipelineCache() = 0;++ virtual bool backendCreateFramebuffer(u32 id, const FramebufferDesc& desc) = 0;+ virtual void backendDeleteFramebuffer(u32 id) = 0;++ virtual bool backendCreateTimerQuery(u32 id) = 0;++ /** @brief Readbacks in flight, the one live object the registry does not hold. */+ virtual u32 backendReadbackCount() const = 0;++ /** @brief The pipeline most recently bound, whose program uniforms are set on. */+ PipelineHandle currentPipeline() const { return current_pipeline_; }/// Backends record what they were last handed; see @ref viewport.Viewport viewport_;@@ -670,10 +741,10 @@ protected: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.+ * @brief Backend half of {@link recoverDevice}: a working device again, with+ * every id-to-native map and derived cache emptied.+ * @details The registry then rebuilds each object through the primitives above.+ * Default: this backend cannot rebuild itself, so a loss is final.*/virtual bool recreateDevice() { return false; }@@ -693,18 +764,7 @@ protected:* @return True when this call performed the transition.*/bool markDeviceLost(GfxDeviceLostReason reason, std::string message = {},- std::string context = {}) {- if (device_status_ != GfxDeviceStatus::Live) return false;- device_status_ = GfxDeviceStatus::Lost;- device_info_.reason = reason;- device_info_.identity = identity_;- 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;- }+ std::string context = {});/*** @brief Release what only this backend can name, while the dead device is@@ -716,12 +776,28 @@ protected:virtual void onDeviceLost() {}private:+ /** @brief Builds every recorded object on the current device, in dependency order. */+ void realizeRegistry();+ void realizeProgramState(u32 id, GfxProgramRecord& record);+ /** @brief Recovering becomes Live once nothing is owed. */+ void settleRecovery();+ void payTexture(u32 id, GfxTextureRecord& record);+ i32 nativeUniformLocation(GfxProgramRecord& record, u32 id, i32 location);+ void setUniformValue(i32 location, const GfxUniformValue& value);+GfxDeviceStatus device_status_ = GfxDeviceStatus::Live;GfxDeviceIdentity identity_;GfxDeviceLostInfo device_info_;u64 device_frame_ = 0;u64 device_generation_ = 0;std::function<void(const GfxDeviceLostInfo&)> device_lost_handler_;++ GfxResourceRegistry registry_;+ u32 owed_count_ = 0;+ ShaderHandle current_program_ = ShaderHandle::Invalid;+ PipelineHandle current_pipeline_ = PipelineHandle::Invalid;+ /// Native uniform locations per program for the current generation; -2 = not asked yet.+ std::map<u32, std::vector<i32>> native_locations_;};} // namespace esenginediff --git a/src/esengine/renderer/rhi/GfxResourceRegistry.hpp b/src/esengine/renderer/rhi/GfxResourceRegistry.hppnew file mode 100644index 000000000..5a9d185e1--- /dev/null+++ b/src/esengine/renderer/rhi/GfxResourceRegistry.hpp@@ -0,0 +1,170 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file GfxResourceRegistry.hpp+ * @brief Every GPU object a device has issued, described well enough to build again.+ *+ * @details The device's one record of what exists. A handle is an id in these+ * tables, never a backend object, so it outlives any number of device+ * losses; the backend keeps only a map from id to whatever its API calls+ * the object this generation. Ids are never reused: a stale handle has to+ * find nothing rather than someone else's object.+ */+#pragma once++#include "./GfxContent.hpp"+#include "./GfxEnums.hpp"+#include "./PipelineState.hpp"++#include <map>+#include <string>+#include <utility>+#include <vector>++namespace esengine {++/** @brief The last value a program was given for one uniform, replayed after a relink. */+struct GfxUniformValue {+ enum class Type : u8 { None, Int, Float, Vec2, Vec3, Vec4, Mat3, Mat4 };+ Type type = Type::None;+ i32 i = 0;+ f32 f[16] = {};+};++struct GfxBufferRecord {+ GfxBufferRecord(const BufferDesc& d, GfxContent c) : desc(d), content(c) {}++ BufferDesc desc;+ GfxContent content;+ /// Retained content, or the initial bytes of a buffer created while the device was lost.+ std::vector<u8> bytes;+ bool realized = false;+ bool owed = false;+};++struct GfxTextureRecord {+ GfxTextureRecord(const TextureDesc& d, GfxContent c) : desc(d), content(c) {}++ TextureDesc desc;+ GfxContent content;+ /// Retained level-0 pixels in upload order (rows as GL stores them), or the+ /// initial pixels of a texture created while the device was lost.+ std::vector<u8> bytes;+ bool compressed = false;+ GfxCompressedFormat compressedFormat = GfxCompressedFormat::ETC2_RGBA8;+ u32 mipLevels = 1;+ bool realized = false;+ bool owed = false;+};++struct GfxProgramRecord {+ GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300;+ std::string vertex;+ std::string fragment;+ std::vector<std::pair<u32, std::string>> attribBindings;+ /// A location handed out is an index here; the backend's own is resolved per generation.+ std::vector<std::string> uniformNames;+ std::vector<GfxUniformValue> uniformValues;+ std::vector<std::string> blockNames;+ /// Binding point per block name, or GFX_UNBOUND_BLOCK.+ std::vector<u32> blockBindings;+ bool realized = false;+};++inline constexpr u32 GFX_UNBOUND_BLOCK = 0xFFFFFFFFu;++struct GfxFramebufferRecord {+ FramebufferDesc desc;+ bool realized = false;+};++struct GfxLayoutRecord {+ VertexLayoutDesc desc;+};++struct GfxPipelineRecord {+ PipelineDesc desc;+};++struct GfxTimerQueryRecord {+ bool realized = false;+};++/** @brief One kind of object, by id, in creation order. */+template <typename Record>+class GfxRecordTable {+public:+ u32 insert(Record record) {+ const u32 id = next_++;+ records_.emplace(id, std::move(record));+ return id;+ }++ Record* find(u32 id) {+ auto it = records_.find(id);+ return it != records_.end() ? &it->second : nullptr;+ }++ const Record* find(u32 id) const {+ auto it = records_.find(id);+ return it != records_.end() ? &it->second : nullptr;+ }++ bool erase(u32 id) { return records_.erase(id) != 0; }++ u32 size() const { return static_cast<u32>(records_.size()); }++ std::map<u32, Record>& all() { return records_; }+ const std::map<u32, Record>& all() const { return records_; }++private:+ std::map<u32, Record> records_;+ u32 next_ = 1;+};++/** @brief A Sourced object that has storage again and is waiting for its contents. */+struct GfxOwedContent {+ enum class Kind : u8 { Buffer, Texture };+ Kind kind;+ u32 id;+ u32 provider;+ u32 key;+};++class GfxResourceRegistry {+public:+ GfxRecordTable<GfxBufferRecord> buffers;+ GfxRecordTable<GfxTextureRecord> textures;+ GfxRecordTable<GfxProgramRecord> programs;+ GfxRecordTable<GfxFramebufferRecord> framebuffers;+ GfxRecordTable<GfxLayoutRecord> layouts;+ GfxRecordTable<GfxPipelineRecord> pipelines;+ GfxRecordTable<GfxTimerQueryRecord> timerQueries;++ /** @brief An existing pipeline with this description, or 0. */+ u32 findPipeline(const PipelineDesc& desc) const {+ for (const auto& [id, record] : pipelines.all()) {+ if (record.desc == desc) return id;+ }+ return 0;+ }++ std::vector<GfxOwedContent> owed() const {+ std::vector<GfxOwedContent> out;+ for (const auto& [id, record] : buffers.all()) {+ if (record.owed) {+ out.push_back({GfxOwedContent::Kind::Buffer, id,+ record.content.provider(), record.content.key()});+ }+ }+ for (const auto& [id, record] : textures.all()) {+ if (record.owed) {+ out.push_back({GfxOwedContent::Kind::Texture, id,+ record.content.provider(), record.content.key()});+ }+ }+ return out;+ }+};++} // namespace esenginediff --git a/src/esengine/renderer/rhi/PerDrawBlocks.hpp b/src/esengine/renderer/rhi/PerDrawBlocks.hppindex 11a02ffe2..74f449e84 100644--- a/src/esengine/renderer/rhi/PerDrawBlocks.hpp+++ b/src/esengine/renderer/rhi/PerDrawBlocks.hpp@@ -20,9 +20,7 @@ namespace esengine {class PerDrawBlocks {public:- /** @brief Claims the pool for blocks of @p blockSize bytes, plus the zero one.- * Also what a device loss runs: old handles are DROPPED, not deleted,- * since freeing an id would read metadata the backend just wiped. */+ /** @brief Claims the pool for blocks of @p blockSize bytes, plus the zero one. */void init(GfxDevice& device, u32 blockSize) {device_ = &device;blockSize_ = blockSize;@@ -30,7 +28,7 @@ public:used_ = 0;const std::vector<u8> zeros(blockSize, 0);zero_ = device.createBuffer({GfxBufferUsage::Uniform, blockSize, /*dynamic=*/false},- zeros.data());+ GfxContent::retained(), zeros.data());}/** @brief Hands every buffer back. Called once per FRAME — see the file note. */@@ -43,7 +41,8 @@ public:if (used_ == pool_.size()) {const std::vector<u8> zeros(blockSize_, 0);pool_.push_back(device_->createBuffer(- {GfxBufferUsage::Uniform, blockSize_, /*dynamic=*/true}, zeros.data()));+ {GfxBufferUsage::Uniform, blockSize_, /*dynamic=*/true}, GfxContent::transient(),+ zeros.data()));}const BufferHandle handle = pool_[used_++];if (handle != BufferHandle::Invalid) device_->updateBuffer(handle, 0, bytes, size);diff --git a/src/esengine/renderer/rhi/RenderTarget.cpp b/src/esengine/renderer/rhi/RenderTarget.cppindex 293899d2a..1f12b592b 100644--- a/src/esengine/renderer/rhi/RenderTarget.cpp+++ b/src/esengine/renderer/rhi/RenderTarget.cpp@@ -4,13 +4,6 @@namespace esengine {-void RenderTarget::recreateGpuResources(GfxDevice& device) {- // The framebuffer and its attachment textures died with the device; the size- // and format it was created at are still here, which is all init needs.- framebuffer_.reset();- init(device, width_, height_, has_depth_, linear_filter_);-}-void RenderTarget::init(GfxDevice& device, u32 width, u32 height, bool depth, bool linearFilter) {width_ = width;height_ = height;diff --git a/src/esengine/renderer/rhi/RenderTarget.hpp b/src/esengine/renderer/rhi/RenderTarget.hppindex f6f706aa7..da5b8128a 100644--- a/src/esengine/renderer/rhi/RenderTarget.hpp+++ b/src/esengine/renderer/rhi/RenderTarget.hpp@@ -33,9 +33,6 @@ public:u32 getWidth() const { return width_; }u32 getHeight() const { return height_; }- /// Re-creates the framebuffer after a device loss, at the size it already has.- void recreateGpuResources(GfxDevice& device);-bool isValid() const { return framebuffer_ != nullptr; }FramebufferHandle getFramebuffer() const;@@ -62,14 +59,6 @@ public:RenderTarget* get(Handle handle);void release(Handle handle);- /// Re-creates every live target after a device loss. Handles are indices, so- /// everything holding one keeps pointing at the same target.- void recreateGpuResources() {- if (!device_) return;- for (auto& target : targets_) {- if (target) target->recreateGpuResources(*device_);- }- }bool isValid(Handle handle) const;private:diff --git a/src/esengine/renderer/rhi/Shader.cpp b/src/esengine/renderer/rhi/Shader.cppindex ae511dfbd..558218d5a 100644--- a/src/esengine/renderer/rhi/Shader.cpp+++ b/src/esengine/renderer/rhi/Shader.cpp@@ -151,39 +151,12 @@ 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- // passing them to it directly would be self-assignment.- const std::string vert = vertexSource_;- const std::string frag = fragmentSource_;- const std::vector<AttribBinding> bindings = attribBindings_;-- // The program, its resolved locations and the DrawParams UBO all died with- // the device. Cleared rather than deleted; compile() rebuilds them.- program_ = ShaderHandle::Invalid;- paramsUbo_ = BufferHandle::Invalid;- uniformCache_.clear();- attribCache_.clear();- activeUniforms_.clear();-- return compile(vert, frag, bindings, nullptr, nullptr, language_);-}-bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrc,const std::vector<AttribBinding>& bindings,std::string* outLog,ShaderStageFailure* outFailedStage,GfxShaderLanguage language) {language_ = language;- vertexSource_ = vertexSrc;- fragmentSource_ = fragmentSrc;- attribBindings_.assign(bindings.begin(), bindings.end());// Fail fast on a language the backend cannot compile, before any GPU call —// the caller gets a diagnostic instead of a backend-specific compile error.@@ -368,7 +341,8 @@ void Shader::commitParams() {if (drawParams_.empty() || !device_) return;if (paramsUbo_ == BufferHandle::Invalid) {paramsUbo_ = device_->createBuffer(- {GfxBufferUsage::Uniform, drawParams_.blockSize, /*dynamic=*/true}, paramsShadow_.data());+ {GfxBufferUsage::Uniform, drawParams_.blockSize, /*dynamic=*/true}, GfxContent::retained(),+ paramsShadow_.data());paramsDirty_ = false;} else if (paramsDirty_) {device_->updateBuffer(paramsUbo_, 0, paramsShadow_.data(), drawParams_.blockSize);diff --git a/src/esengine/renderer/rhi/Shader.hpp b/src/esengine/renderer/rhi/Shader.hppindex 136eccbd0..7643f362d 100644--- a/src/esengine/renderer/rhi/Shader.hpp+++ b/src/esengine/renderer/rhi/Shader.hpp@@ -246,15 +246,6 @@ public:/** @brief Gets the program handle's raw value, for command payloads and sort keys */u32 getProgramId() const { return static_cast<u32>(program_); }- /// Rebuilds the program from the sources it was compiled with, after the- /// 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@@ -277,13 +268,6 @@ private:* @return True when consumed (caller must not fall through to a loose upload). */bool writeParam(const std::string& name, DrawParamType type, const void* src) const;- /// What this program was built from, kept so it can be rebuilt behind the- /// SAME handle after a device loss — which is what keeps a material's- /// shaderRef valid. A few KB each; a texture's pixels are not.- std::string vertexSource_;- std::string fragmentSource_;- std::vector<AttribBinding> attribBindings_;-GfxDevice* device_ = nullptr; ///< Set by the create* factories; all GL goes through it.GfxShaderLanguage language_ = GfxShaderLanguage::GLSL_ES300;ShaderHandle program_ = ShaderHandle::Invalid;diff --git a/src/esengine/renderer/rhi/Texture.cpp b/src/esengine/renderer/rhi/Texture.cppindex fc017a7ed..086e9e7c7 100644--- a/src/esengine/renderer/rhi/Texture.cpp+++ b/src/esengine/renderer/rhi/Texture.cpp@@ -80,29 +80,29 @@ Texture& Texture::operator=(Texture&& other) noexcept {return *this;}-Unique<Texture> Texture::create(GfxDevice& device, const TextureSpecification& spec) {+Unique<Texture> Texture::create(GfxDevice& device, GfxContent content, const TextureSpecification& spec) {auto texture = makeUnique<Texture>();texture->device_ = &device;- if (!texture->initialize(spec, nullptr, false)) {+ if (!texture->initialize(spec, content, nullptr, false)) {return nullptr;}return texture;}-Unique<Texture> Texture::create(GfxDevice& device, u32 width, u32 height, std::span<const u8> pixels,- TextureFormat format, bool flipY) {+Unique<Texture> Texture::create(GfxDevice& device, GfxContent content, u32 width, u32 height,+ std::span<const u8> pixels, TextureFormat format, bool flipY) {[[maybe_unused]] u32 expectedSize = width * height * bytesPerPixel(format);ES_ASSERT(pixels.size() == expectedSize, "Pixel data size mismatch");- return createRaw(device, width, height, pixels.data(), format, flipY);+ return createRaw(device, content, width, height, pixels.data(), format, flipY);}-Unique<Texture> Texture::create(GfxDevice& device, u32 width, u32 height, const std::vector<u8>& pixels,- TextureFormat format, bool flipY) {- return create(device, width, height, std::span<const u8>(pixels), format, flipY);+Unique<Texture> Texture::create(GfxDevice& device, GfxContent content, u32 width, u32 height,+ const std::vector<u8>& pixels, TextureFormat format, bool flipY) {+ return create(device, content, width, height, std::span<const u8>(pixels), format, flipY);}-Unique<Texture> Texture::createRaw(GfxDevice& device, u32 width, u32 height, const void* data,- TextureFormat format, bool flipY) {+Unique<Texture> Texture::createRaw(GfxDevice& device, GfxContent content, u32 width, u32 height,+ const void* data, TextureFormat format, bool flipY) {TextureSpecification spec;spec.width = width;spec.height = height;@@ -113,13 +113,13 @@ Unique<Texture> Texture::createRaw(GfxDevice& device, u32 width, u32 height, conauto texture = makeUnique<Texture>();texture->device_ = &device;- if (!texture->initialize(spec, data, flipY)) {+ if (!texture->initialize(spec, content, data, flipY)) {return nullptr;}return texture;}-Unique<Texture> Texture::createCompressed(GfxDevice& device, u32 width, u32 height,+Unique<Texture> Texture::createCompressed(GfxDevice& device, GfxContent content, u32 width, u32 height,GfxCompressedFormat format, std::span<const u8> data,u32 mipLevels) {auto texture = makeUnique<Texture>();@@ -137,7 +137,7 @@ Unique<Texture> Texture::createCompressed(GfxDevice& device, u32 width, u32 heigdesc.wrapT = TextureWrap::ClampToEdge;desc.mipmaps = mipLevels > 1;- texture->handle_ = device.createCompressedTexture(desc, format, data.data(),+ texture->handle_ = device.createCompressedTexture(desc, content, format, data.data(),static_cast<u32>(data.size()), mipLevels);if (texture->handle_ == TextureHandle::Invalid) {ES_LOG_ERROR("Texture::createCompressed: failed for {}x{}", width, height);@@ -146,13 +146,8 @@ Unique<Texture> Texture::createCompressed(GfxDevice& device, u32 width, u32 heigreturn texture;}-void Texture::retarget(TextureHandle gpuHandle, bool owns) {- handle_ = gpuHandle;- owns_ = owns;-}--Unique<Texture> Texture::createFromExternalId(GfxDevice& device, u32 glTextureId, u32 width, u32 height,- TextureFormat format) {+Unique<Texture> Texture::createFromExternalId(GfxDevice& device, GfxContent content, u32 glTextureId,+ u32 width, u32 height, TextureFormat format) {TextureDesc desc;desc.width = width;desc.height = height;@@ -160,15 +155,37 @@ Unique<Texture> Texture::createFromExternalId(GfxDevice& device, u32 glTextureIdauto texture = makeUnique<Texture>();texture->device_ = &device;- texture->handle_ = device.importExternalTexture(glTextureId, desc);+ texture->handle_ = device.importExternalTexture(glTextureId, desc, content);texture->width_ = width;texture->height_ = height;texture->format_ = format;- texture->owns_ = false; // external owner frees the GL id; don't double-free itreturn texture;}-bool Texture::initialize(const TextureSpecification& spec, const void* pixels, bool flipY) {+Unique<Texture> Texture::borrow(GfxDevice& device, TextureHandle handle, u32 width, u32 height) {+ if (!device.textureDesc(handle)) return nullptr;+ auto texture = makeUnique<Texture>();+ texture->device_ = &device;+ texture->handle_ = handle;+ texture->width_ = width;+ texture->height_ = height;+ texture->format_ = TextureFormat::RGBA8;+ texture->owns_ = false;+ return texture;+}++bool Texture::adoptContent(Texture& from) {+ if (!device_ || !owns_ || !from.owns_ || !device_->adoptTextureContent(handle_, from.handle_)) {+ return false;+ }+ width_ = from.width_;+ height_ = from.height_;+ format_ = from.format_;+ from.handle_ = TextureHandle::Invalid;+ return true;+}++bool Texture::initialize(const TextureSpecification& spec, GfxContent content, const void* pixels, bool flipY) {width_ = spec.width;height_ = spec.height;format_ = spec.format;@@ -184,7 +201,7 @@ bool Texture::initialize(const TextureSpecification& spec, const void* pixels, bdesc.mipmaps = spec.generateMips;desc.flipY = flipY;- handle_ = device_->createTexture(desc, pixels);+ handle_ = device_->createTexture(desc, content, pixels);if (handle_ == TextureHandle::Invalid) {// Out of memory or a lost context: surface the failure instead of// returning a "valid" texture wrapping the null handle (renders as black).diff --git a/src/esengine/renderer/rhi/Texture.hpp b/src/esengine/renderer/rhi/Texture.hppindex cda6927c8..37a748445 100644--- a/src/esengine/renderer/rhi/Texture.hpp+++ b/src/esengine/renderer/rhi/Texture.hpp@@ -20,6 +20,7 @@// Project includes#include "../../core/Types.hpp"+#include "./GfxContent.hpp"#include "./GfxEnums.hpp"// Standard library@@ -131,7 +132,7 @@ public:* @details Creates a texture with uninitialized pixel data.* Use setData() to upload pixels later.*/- static Unique<Texture> create(GfxDevice& device, const TextureSpecification& spec);+ static Unique<Texture> create(GfxDevice& device, GfxContent content, const TextureSpecification& spec);/*** @brief Creates a texture from a span of pixel data@@ -141,7 +142,8 @@ public:* @param format Pixel format (default RGBA8)* @return Unique pointer to the texture*/- static Unique<Texture> create(GfxDevice& device, u32 width, u32 height, std::span<const u8> pixels,+ static Unique<Texture> create(GfxDevice& device, GfxContent content, u32 width, u32 height,+ std::span<const u8> pixels,TextureFormat format = TextureFormat::RGBA8,bool flipY = false);@@ -154,23 +156,23 @@ public:* @param flipY Flip vertically on upload (for web image data)* @return Unique pointer to the texture*/- static Unique<Texture> create(GfxDevice& device, u32 width, u32 height, const std::vector<u8>& pixels,+ static Unique<Texture> create(GfxDevice& device, GfxContent content, u32 width, u32 height,+ const std::vector<u8>& pixels,TextureFormat format = TextureFormat::RGBA8,bool flipY = false);- // =========================================================================- // Device Loss- // =========================================================================+ /**+ * @brief Names a texture the device already holds for another owner (a render+ * target's colour plane), without taking it over.+ */+ static Unique<Texture> borrow(GfxDevice& device, TextureHandle texture, u32 width, u32 height);/**- * @brief Points this texture at a different GPU object, keeping its identity.- * @details How a device loss stays invisible above: the resource::Handle- * naming this Texture never changes, so no component, material or- * font has to learn that the pixels were re-uploaded. The old GPU- * object is NOT deleted — it died with the device.- * @param owns Whether this Texture should free @p gpuHandle at destruction.+ * @brief Takes @p from's pixels behind this texture's handle; @p from is empty afterwards.+ * @details How owed content is paid: the provider loads it the ordinary way and+ * hands the result over, so nothing that names this texture changes.*/- void retarget(TextureHandle gpuHandle, bool owns);+ bool adoptContent(Texture& from);// =========================================================================// Operations@@ -251,7 +253,8 @@ public:* @param format Pixel format (default RGBA8)* @return Unique pointer to the texture*/- static Unique<Texture> createRaw(GfxDevice& device, u32 width, u32 height, const void* data,+ static Unique<Texture> createRaw(GfxDevice& device, GfxContent content, u32 width, u32 height,+ const void* data,TextureFormat format = TextureFormat::RGBA8,bool flipY = false);@@ -261,19 +264,16 @@ public:* compressed data is immutable here.* @param data Compressed block data for mip level 0.*/- static Unique<Texture> createCompressed(GfxDevice& device, u32 width, u32 height,+ static Unique<Texture> createCompressed(GfxDevice& device, GfxContent content, u32 width, u32 height,GfxCompressedFormat format, std::span<const u8> data,u32 mipLevels = 1);/**- * @brief Wraps an existing GL texture ID- * @param glTextureId The OpenGL texture ID created externally- * @param width Texture width in pixels- * @param height Texture height in pixels- * @param format Pixel format- * @return Unique pointer to the texture wrapper+ * @brief Hands the device a texture the host made with its own API; the device owns it from here.+ * @param glTextureId The host's id for it (a WebGL texture registered with the GL layer)*/- static Unique<Texture> createFromExternalId(GfxDevice& device, u32 glTextureId, u32 width, u32 height,+ static Unique<Texture> createFromExternalId(GfxDevice& device, GfxContent content, u32 glTextureId,+ u32 width, u32 height,TextureFormat format = TextureFormat::RGBA8);/**@@ -291,15 +291,14 @@ private:* @param flipY Vertical flip on the initial upload* @return True on success*/- bool initialize(const TextureSpecification& spec, const void* pixels, bool flipY);+ bool initialize(const TextureSpecification& spec, GfxContent content, const void* pixels, bool flipY);GfxDevice* device_ = nullptr; ///< Set by the create* factories; all GL goes through it.TextureHandle handle_ = TextureHandle::Invalid;u32 width_ = 0;u32 height_ = 0;TextureFormat format_ = TextureFormat::None;- // False for textures wrapping an externally-owned GL id (createFromExternalId):- // the external owner frees it, so this wrapper must NOT delete it (double-free).+ /// False for a borrowed texture, whose owner deletes it.bool owns_ = true;};diff --git a/src/esengine/renderer/rhi/TransientBufferPool.cpp b/src/esengine/renderer/rhi/TransientBufferPool.cppindex cacaee9fb..b08f05884 100644--- a/src/esengine/renderer/rhi/TransientBufferPool.cpp+++ b/src/esengine/renderer/rhi/TransientBufferPool.cpp@@ -27,26 +27,6 @@ void TransientBufferPool::init(u32 initialVertexBytes, u32 initialIndexCount) {initialized_ = true;}-void TransientBufferPool::recreateGpuResources() {- if (!initialized_) return;- // Dropped without deleting, then re-set up from the same initial sizes. The- // staging vectors are CPU-side and survive; only their write positions reset.- for (auto& s : streams_) {- s.vbo = BufferHandle::Invalid;- s.ebo = BufferHandle::Invalid;- s.quad_vbo = BufferHandle::Invalid;- s.layout = VertexLayoutHandle::Invalid;- s.vbo_capacity = 0;- s.ebo_capacity = 0;- s.vertex_write_pos = 0;- s.index_write_pos = 0;- s.texture = TextureHandle::Invalid;- s.texture_rows = 0;- }- initialized_ = false;- init(initial_vertex_bytes_, initial_index_count_);-}-void TransientBufferPool::shutdown() {if (!initialized_) return;@@ -117,7 +97,7 @@ void TransientBufferPool::uploadInstanceRows(Stream& s, u32& grows, u32& writes)desc.wrapS = TextureWrap::ClampToEdge;desc.wrapT = TextureWrap::ClampToEdge;desc.mipmaps = false;- s.texture = device_.createTexture(desc, s.vertex_staging.data());+ s.texture = device_.createTexture(desc, GfxContent::transient(), s.vertex_staging.data());s.texture_rows = s.texture == TextureHandle::Invalid ? 0 : want;++grows;return;@@ -285,7 +265,8 @@ void TransientBufferPool::setupStream(LayoutId layout) {// Per-instance (per-particle) stream: dynamic, streamed each frame.s.vertex_staging.resize(initial_vertex_bytes_);s.vbo_capacity = initial_vertex_bytes_;- s.vbo = device_.createBuffer({GfxBufferUsage::Vertex, s.vbo_capacity, /*dynamic=*/true}, nullptr);+ s.vbo = device_.createBuffer({GfxBufferUsage::Vertex, s.vbo_capacity, /*dynamic=*/true},+ GfxContent::transient(), nullptr);// Static unit quad (pos + uv) and its 6 indices, uploaded once. UVs are laid out// so the instance shader's a_texCoord*uvScale+uvOffset reproduces the prior@@ -299,9 +280,11 @@ void TransientBufferPool::setupStream(LayoutId layout) {};const u32 quadIdx[6] = { 0, 1, 2, 2, 3, 0 };s.quad_vbo = device_.createBuffer(- {GfxBufferUsage::Vertex, static_cast<u32>(sizeof(quad)), /*dynamic=*/false}, quad);+ {GfxBufferUsage::Vertex, static_cast<u32>(sizeof(quad)), /*dynamic=*/false},+ GfxContent::retained(), quad);s.ebo = device_.createBuffer(- {GfxBufferUsage::Index, static_cast<u32>(sizeof(quadIdx)), /*dynamic=*/false}, quadIdx);+ {GfxBufferUsage::Index, static_cast<u32>(sizeof(quadIdx)), /*dynamic=*/false},+ GfxContent::retained(), quadIdx);// Slot 0: the static quad (per vertex). Slot 1: the instance stream (per instance),// rebased per draw in bindInstanceLayout.@@ -330,9 +313,11 @@ void TransientBufferPool::setupStream(LayoutId layout) {s.vbo_capacity = initial_vertex_bytes_;s.ebo_capacity = initial_index_count_;- s.vbo = device_.createBuffer({GfxBufferUsage::Vertex, s.vbo_capacity, /*dynamic=*/true}, nullptr);+ s.vbo = device_.createBuffer({GfxBufferUsage::Vertex, s.vbo_capacity, /*dynamic=*/true},+ GfxContent::transient(), nullptr);s.ebo = device_.createBuffer(- {GfxBufferUsage::Index, static_cast<u32>(s.ebo_capacity * sizeof(u32)), /*dynamic=*/true}, nullptr);+ {GfxBufferUsage::Index, static_cast<u32>(s.ebo_capacity * sizeof(u32)), /*dynamic=*/true},+ GfxContent::transient(), nullptr);VertexLayoutDesc desc;switch (layout) {diff --git a/src/esengine/renderer/rhi/TransientBufferPool.hpp b/src/esengine/renderer/rhi/TransientBufferPool.hppindex ffdd8ea6f..b5c5decab 100644--- a/src/esengine/renderer/rhi/TransientBufferPool.hpp+++ b/src/esengine/renderer/rhi/TransientBufferPool.hpp@@ -32,9 +32,6 @@ public:u32 initialIndexCount = 256 * 1024);void shutdown();- /// Re-creates the streams' GPU buffers and layouts after a device loss.- void recreateGpuResources();-void beginFrame();u32 allocVertices(LayoutId layout, u32 byteSize);diff --git a/src/esengine/renderer/store/LightStore.cpp b/src/esengine/renderer/store/LightStore.cppindex 94a017b42..0a07cb5cb 100644--- a/src/esengine/renderer/store/LightStore.cpp+++ b/src/esengine/renderer/store/LightStore.cpp@@ -16,7 +16,8 @@ void LightStore::uploadAndBind() {if (ubo_ == BufferHandle::Invalid) {ubo_ = device_->createBuffer(- {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(LightConstants)), /*dynamic=*/true}, &data_);+ {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(LightConstants)), /*dynamic=*/true},+ GfxContent::retained(), &data_);dirty_ = false;} else if (dirty_) {device_->updateBuffer(ubo_, 0, &data_, sizeof(LightConstants));diff --git a/src/esengine/renderer/store/LightStore.hpp b/src/esengine/renderer/store/LightStore.hppindex 5f8dbcb00..dc3e86ab8 100644--- a/src/esengine/renderer/store/LightStore.hpp+++ b/src/esengine/renderer/store/LightStore.hpp@@ -35,13 +35,6 @@ public:/// The render path uses this device to create/upload/delete the lighting UBO.void setDevice(GfxDevice* device) { device_ = device; }- /// Forgets the UBO after a device loss WITHOUT deleting it — the buffer died- /// with the device, and the upload path creates a fresh one on demand.- void recreateGpuResources() {- ubo_ = BufferHandle::Invalid;- dirty_ = true;- }-/// Begins a frame's collection: zeroes ambient + all light slots (inactive slots contribute/// nothing because their intensity is 0) and marks the UBO for re-upload.void clear() {diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex bf02dec7d..fe0801ab4 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -34,16 +34,6 @@ void MaterialStore::clear() {layouts_.clear();}-void MaterialStore::recreateGpuResources() {- // Buffers are dropped, not deleted: they died with the device. The material- // RECORDS stay, so every materialId the scene refers to still resolves and- // bindForDraw re-creates the UBO from the parameters it already holds.- for (auto& [id, rec] : materials_) {- rec.ubo = BufferHandle::Invalid;- rec.uboDirty = true;- }-}-u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resources,bool withNormals, bool skinned, bool envMapped) const {// Keyed by shader AND vertex shape: a layout may not declare an attribute its@@ -149,24 +139,6 @@ void MaterialStore::seedSamplers(Shader& shader, const resource::ParsedShader& pshader.unbind();}-void MaterialStore::refreshShaderPrograms(resource::ResourceManager& resources) {- // The cached program id is the one thing a record holds that the device can- // invalidate; shaderRef is what makes recomputing it possible at all.- for (auto& [id, rec] : materials_) {- rec.shader = 0;- Shader* shader = resources.getShader(rec.shaderRef);- if (!shader) continue;- rec.shader = shader->getProgramId();- // And the sampler units, which the relink behind that id cleared. Reading- // the id back is half of restoring a program: the other half is the- // uniform state that says which unit each texture param reads.- auto src = sources_.find(rec.shaderRef.id());- if (src != sources_.end()) {- seedSamplers(*shader, resource::ShaderParser::parse(src->second.source));- }- }-}-void MaterialStore::bindForDraw(u32 materialId) {if (!device_) return;auto it = materials_.find(materialId);@@ -181,7 +153,7 @@ void MaterialStore::bindForDraw(u32 materialId) {const u32 byteSize = static_cast<u32>(rec.uboBytes.size());if (rec.ubo == BufferHandle::Invalid) {rec.ubo = device_->createBuffer({GfxBufferUsage::Uniform, byteSize, /*dynamic=*/true},- rec.uboBytes.data());+ GfxContent::retained(), rec.uboBytes.data());rec.uboDirty = false;} else if (rec.uboDirty) {// Full re-spec (not a sub-update): orphans the old store so a draw stilldiff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex a56b2a00d..ee22d1d9e 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -144,8 +144,7 @@ public:/// Resolves texture handles at bind time; without one, texture params bind nothing.void setResourceManager(resource::ResourceManager* resources) { resources_ = resources; }- /// The context's current built-in fallbacks. Pushed rather than cached from a- /// resolved id, so re-creating them after a device loss reaches the materials too.+ /// The context's built-in fallbacks.void setBuiltinDefaults(TextureHandle white, TextureHandle black, TextureHandle flatNormal) {defaultWhite_ = white;defaultBlack_ = black;@@ -156,21 +155,11 @@ public:/// so the post-process pipeline's params fall back to the same textures.TextureHandle builtinDefault(MaterialDefaultTexture which) const;- /// Drops every material UBO after a device loss, keeping the records so the- /// scene's materialIds stay meaningful. See the definition.- void recreateGpuResources();-- /// Re-resolves each material's cached program id from its shader handle, after- /// the device rebuilt the programs behind them.- void refreshShaderPrograms(resource::ResourceManager& resources);-/*** @brief Point each of @p shader's texture params at its unit.** @details GLSL ES 300 has no `layout(binding=)`, so a program carries this- * as uniform state — which a relink clears. Public and shared so- * registration and device recovery seed by one rule; they did not,- * and a recovered material sampled every texture from unit 0.+ * as uniform state.*/static void seedSamplers(Shader& shader, const resource::ParsedShader& parsed);diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cppindex a6b2a8fda..519d261a2 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp@@ -173,32 +173,45 @@ void WebGPUDevice::shutdown() {}void WebGPUDevice::releaseDeviceObjects() {+ if (pass_) { wgpuRenderPassEncoderRelease(pass_); pass_ = nullptr; }+ if (encoder_) { wgpuCommandEncoderRelease(encoder_); encoder_ = nullptr; }+ if (frame_view_) { wgpuTextureViewRelease(frame_view_); frame_view_ = nullptr; }+ if (frame_texture_) { wgpuTextureRelease(frame_texture_); frame_texture_ = nullptr; }+ capture_id_ = 0;+ capture_copied_ = false;+ pass_is_surface_ = false;+ pass_timed_ = false;++ // bind_group_/texture_group_ point INTO the cache — release the cache, not them.+ for (auto& e : bind_group_cache_) if (e.bg) wgpuBindGroupRelease(e.bg);+ bind_group_cache_.clear();+ bind_group_ = nullptr;+ texture_group_ = nullptr;+ bind_group_dirty_ = true;+ bound_pipeline_ = 0;+for (auto& [id, rec] : buffers_) {if (rec.buffer) wgpuBufferRelease(rec.buffer);}buffers_.clear();- for (auto& [id, rec] : textures_) {- if (rec.view) wgpuTextureViewRelease(rec.view);- if (rec.texture) wgpuTextureRelease(rec.texture);- }+ for (auto& [id, rec] : textures_) releaseTexture(rec);textures_.clear();for (auto& [id, rec] : programs_) {if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);}programs_.clear();- layouts_.clear();for (auto& [id, rec] : pipelines_) {for (WGPURenderPipeline variant : rec.variants) {if (variant) wgpuRenderPipelineRelease(variant);}}pipelines_.clear();- // bind_group_/texture_group_ point INTO the cache — release the cache, not them.- for (auto& e : bind_group_cache_) if (e.bg) wgpuBindGroupRelease(e.bg);- bind_group_cache_.clear();- bind_group_ = nullptr;- texture_group_ = nullptr;++ if (dummy_ubo_.buffer) wgpuBufferRelease(dummy_ubo_.buffer);+ dummy_ubo_ = BufferRec{};+ releaseTexture(dummy_texture_);+ releaseTexture(dummy_depth_texture_);// GPU timing resources.if (timestamp_qset_) { wgpuQuerySetRelease(timestamp_qset_); timestamp_qset_ = nullptr; }@@ -208,6 +221,7 @@ void WebGPUDevice::releaseDeviceObjects() {timestamp_supported_ = false;timestamp_init_done_ = false;if (clear_bind_group_) { wgpuBindGroupRelease(clear_bind_group_); clear_bind_group_ = nullptr; }+ if (clear_color_buffer_) { wgpuBufferRelease(clear_color_buffer_); clear_color_buffer_ = nullptr; }for (auto& [key, pipeline] : clear_pipelines_) {if (pipeline) wgpuRenderPipelineRelease(pipeline);}@@ -222,10 +236,6 @@ void WebGPUDevice::releaseDeviceObjects() {if (layout) wgpuBindGroupLayoutRelease(layout);}group_layouts_.clear();- dummy_ubo_ = BufferHandle{}; // the WGPUBuffer/WGPUTexture went with the maps above- dummy_texture_ = 0;- dummy_depth_texture_ = 0;- framebuffers_.clear();// Erase before release: aborting a pending map fires the callback, which must// miss the lookup rather than see a half-dead record.while (!readbacks_.empty()) releaseReadback(readbacks_.begin()->first);@@ -597,35 +607,29 @@ void WebGPUDevice::setScissor(i32 x, i32 y, i32 w, i32 h) {// Buffers// =============================================================================-// Unlike GL — where a lost context turns every call into a silent no-op — calling-// into a lost WebGPU device is not defined to be harmless. The guards below are-// the backend's half of the contract; the frame loop stops submitting above them.--BufferHandle WebGPUDevice::createBuffer(const BufferDesc& desc, const void* initialData) {- if (!isDeviceUsable()) return BufferHandle::Invalid;+WGPUBuffer WebGPUDevice::makeBuffer(GfxBufferUsage usage, u32 size, const void* data) {if (!device_) {- ES_LOG_ERROR("WebGPUDevice::createBuffer: no device");- return BufferHandle::Invalid;+ ES_LOG_ERROR("WebGPUDevice: no device to create a buffer on");+ return nullptr;}-WGPUBufferDescriptor bd{};- bd.usage = toWGPUBufferUsage(desc.usage);+ bd.usage = toWGPUBufferUsage(usage);// Round the allocation, never the caller's data — see alignedWriteSize.- bd.size = webgpu::alignedWriteSize(desc.size);-+ bd.size = webgpu::alignedWriteSize(size);WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);if (!buffer) {- ES_LOG_ERROR("WebGPUDevice::createBuffer: creation failed ({} bytes)", desc.size);- return BufferHandle::Invalid;+ ES_LOG_ERROR("WebGPUDevice: buffer creation failed ({} bytes)", size);+ return nullptr;}+ if (data && size > 0) writeBufferPadded(buffer, 0, data, size);+ return buffer;+}- const u32 id = next_id_++;+bool WebGPUDevice::backendCreateBuffer(u32 id, const BufferDesc& desc, const void* data) {+ WGPUBuffer buffer = makeBuffer(desc.usage, desc.size, data);+ if (!buffer) return false;buffers_[id] = BufferRec{buffer, desc.size, desc.usage};-- if (initialData && desc.size > 0) {- writeBufferPadded(buffer, 0, initialData, desc.size);- }- return BufferHandle{id};+ return true;}void WebGPUDevice::writeBufferPadded(WGPUBuffer buffer, u32 offset, const void* data, u32 size) {@@ -638,8 +642,8 @@ void WebGPUDevice::writeBufferPadded(WGPUBuffer buffer, u32 offset, const void*wgpuQueueWriteBuffer(queue_, buffer, offset, padded.data(), padded.size());}-void WebGPUDevice::deleteBuffer(BufferHandle buffer) {- auto it = buffers_.find(static_cast<u32>(buffer));+void WebGPUDevice::backendDeleteBuffer(u32 id) {+ auto it = buffers_.find(id);if (it == buffers_.end()) return;if (it->second.buffer) {evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(it->second.buffer)));@@ -664,8 +668,8 @@ void WebGPUDevice::evictBindGroups(u64 id) {}}-void WebGPUDevice::updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) {- auto it = buffers_.find(static_cast<u32>(buffer));+void WebGPUDevice::backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) {+ auto it = buffers_.find(id);if (it == buffers_.end() || !it->second.buffer || !data || sizeBytes == 0) return;if (!webgpu::writeFitsInBuffer(offsetBytes, sizeBytes, it->second.size)) {ES_LOG_ERROR("WebGPUDevice::updateBuffer: range {}+{} exceeds buffer size {}",@@ -687,32 +691,20 @@ void WebGPUDevice::updateBuffer(BufferHandle buffer, u32 offsetBytes, const voidwriteBufferPadded(it->second.buffer, offsetBytes, data, sizeBytes);}-void WebGPUDevice::resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) {- auto it = buffers_.find(static_cast<u32>(buffer));+void WebGPUDevice::backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) {+ auto it = buffers_.find(id);if (it == buffers_.end()) return;- // The RHI contract: the handle stays stable across growth. WebGPU buffers are- // fixed-size, so re-create the WGPUBuffer behind the same id. A cached bind- // group names the old WGPUBuffer, not the id, and would keep drawing its bytes.+ // WebGPU buffers are fixed-size, so the store is re-created behind the same id.+ // A cached bind group names the old WGPUBuffer, not the id, and would keep+ // drawing its bytes.if (it->second.buffer) {evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(it->second.buffer)));wgpuBufferRelease(it->second.buffer);}bind_group_dirty_ = true;-- WGPUBufferDescriptor bd{};- bd.usage = toWGPUBufferUsage(it->second.usage);- bd.size = webgpu::alignedWriteSize(sizeBytes);- it->second.buffer = wgpuDeviceCreateBuffer(device_, &bd);- it->second.size = sizeBytes;- if (!it->second.buffer) {- ES_LOG_ERROR("WebGPUDevice::resizeBuffer: creation failed ({} bytes)", sizeBytes);- return;- }-- if (data && sizeBytes > 0) {- writeBufferPadded(it->second.buffer, 0, data, sizeBytes);- }+ it->second.buffer = makeBuffer(desc.usage, desc.size, data);+ it->second.size = desc.size;}void WebGPUDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {@@ -728,25 +720,18 @@ void WebGPUDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {// Vertex layouts (descriptors retained; pipelines consume them at build time)// =============================================================================-VertexLayoutHandle WebGPUDevice::createVertexLayout(const VertexLayoutDesc& desc) {- if (!isDeviceUsable()) return VertexLayoutHandle::Invalid;- // Validate every attribute has a WebGPU spelling up front — a mismatch is an- // engine bug, not a runtime condition.+bool WebGPUDevice::backendAcceptsVertexLayout(const VertexLayoutDesc& desc) {+ // Every attribute needs a WebGPU spelling — a mismatch is an engine bug, not a+ // runtime condition, so it is refused where the layout is declared.for (u32 i = 0; i < desc.attributeCount; ++i) {const auto& a = desc.attributes[i];if (toWGPUVertexFormat(a.components, a.type, a.normalized) == kInvalidVertexFormat) {ES_LOG_ERROR("WebGPUDevice::createVertexLayout: attribute {} ({} x type {}) has no WGPU format",i, a.components, static_cast<u32>(a.type));- return VertexLayoutHandle::Invalid;+ return false;}}- const u32 id = next_id_++;- layouts_[id] = desc;- return VertexLayoutHandle{id};-}--void WebGPUDevice::deleteVertexLayout(VertexLayoutHandle layout) {- layouts_.erase(static_cast<u32>(layout));+ return true;}void WebGPUDevice::setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) {@@ -762,16 +747,6 @@ void WebGPUDevice::setIndexBuffer(BufferHandle buffer) {bound_index_buffer_ = static_cast<u32>(buffer);}-const VertexLayoutDesc* WebGPUDevice::layoutDesc(VertexLayoutHandle handle) const {- auto it = layouts_.find(static_cast<u32>(handle));- return it != layouts_.end() ? &it->second : nullptr;-}--const PipelineDesc* WebGPUDevice::pipelineDesc(PipelineHandle handle) const {- auto it = pipelines_.find(static_cast<u32>(handle));- return it != pipelines_.end() ? &it->second.desc : nullptr;-}-// =============================================================================// Textures// =============================================================================@@ -785,11 +760,10 @@ u32 WebGPUDevice::colorVariantOf(WGPUTextureFormat format) {}}-TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* pixels) {- if (!isDeviceUsable()) return TextureHandle::Invalid;+bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, TextureRec& out) {if (!device_) {- ES_LOG_ERROR("WebGPUDevice::createTexture: no device");- return TextureHandle::Invalid;+ ES_LOG_ERROR("WebGPUDevice: no device to create a texture on");+ return false;}WGPUTextureDescriptor td{};@@ -808,8 +782,8 @@ TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* pWGPUTexture texture = wgpuDeviceCreateTexture(device_, &td);if (!texture) {- ES_LOG_ERROR("WebGPUDevice::createTexture: creation failed ({}x{})", desc.width, desc.height);- return TextureHandle::Invalid;+ ES_LOG_ERROR("WebGPUDevice: texture creation failed ({}x{})", desc.width, desc.height);+ return false;}WGPUTextureView view = wgpuTextureCreateView(texture, nullptr);@@ -832,31 +806,35 @@ TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* psampleView = wgpuTextureCreateView(texture, &vd);}- const u32 id = next_id_++;- textures_[id] = TextureRec{texture, view, sampleView,- desc.width, desc.height, td.format, desc.format,- packSamplerKey(desc.minFilter, desc.magFilter,- desc.wrapS, desc.wrapT)};+ out = TextureRec{texture, view, sampleView,+ desc.width, desc.height, td.format, desc.format,+ packSamplerKey(desc.minFilter, desc.magFilter, desc.wrapS, desc.wrapT)};if (pixels && !isDepthFormat(td.format)) {// desc.flipY, not false: the caller's orientation request has to reach the- // upload, which is where the row reversal happens (see updateTexture).- updateTexture(TextureHandle{id}, 0, 0, desc.width, desc.height, pixels, desc.flipY);+ // upload, which is where the row reversal happens (see writeTexture).+ writeTexture(out, 0, 0, desc.width, desc.height, pixels, desc.flipY);}- return TextureHandle{id};+ return true;+}++bool WebGPUDevice::backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) {+ TextureRec rec;+ if (!makeTexture(desc, pixels, rec)) return false;+ textures_[id] = rec;+ return true;}-TextureHandle WebGPUDevice::createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,- const void* data, u32 byteLength, u32 mipLevels) {- if (!isDeviceUsable()) return TextureHandle::Invalid;+bool WebGPUDevice::backendCreateCompressedTexture(u32 id, const TextureDesc& desc, GfxCompressedFormat format,+ const void* data, u32 byteLength, u32 mipLevels) {if (!device_ || !queue_) {ES_LOG_ERROR("WebGPUDevice::createCompressedTexture: no device");- return TextureHandle::Invalid;+ return false;}const WGPUTextureFormat wgpuFmt = toWGPUCompressedFormat(format);if (wgpuFmt == WGPUTextureFormat_Undefined) {ES_LOG_ERROR("WebGPUDevice::createCompressedTexture: unmapped format");- return TextureHandle::Invalid;+ return false;}const u32 levels = mipLevels ? mipLevels : 1;@@ -871,7 +849,7 @@ TextureHandle WebGPUDevice::createCompressedTexture(const TextureDesc& desc, GfxWGPUTexture texture = wgpuDeviceCreateTexture(device_, &td);if (!texture) {ES_LOG_ERROR("WebGPUDevice::createCompressedTexture: creation failed ({}x{})", desc.width, desc.height);- return TextureHandle::Invalid;+ return false;}// Upload each mip level from the concatenated pyramid. writeTexture counts@@ -879,7 +857,7 @@ TextureHandle WebGPUDevice::createCompressedTexture(const TextureDesc& desc, Gfxconst GfxBlockInfo bi = gfxCompressedBlockInfo(format);const u8* ptr = static_cast<const u8*>(data);const u8* end = ptr + byteLength;- for (u32 level = 0; level < levels; ++level) {+ for (u32 level = 0; ptr && level < levels; ++level) {const u32 lw = (desc.width >> level) ? (desc.width >> level) : 1u;const u32 lh = (desc.height >> level) ? (desc.height >> level) : 1u;const u32 blocksX = (lw + bi.blockWidth - 1) / bi.blockWidth;@@ -898,7 +876,6 @@ TextureHandle WebGPUDevice::createCompressedTexture(const TextureDesc& desc, Gfxptr += levelBytes;}- const u32 id = next_id_++;// A compressed texture is never a depth one, so it samples through the view// it already has — the two members alias, as they do for any colour format.WGPUTextureView view = wgpuTextureCreateView(texture, nullptr);@@ -906,54 +883,64 @@ TextureHandle WebGPUDevice::createCompressedTexture(const TextureDesc& desc, Gfxdesc.width, desc.height, wgpuFmt, desc.format,packSamplerKey(desc.minFilter, desc.magFilter,desc.wrapS, desc.wrapT)};- return TextureHandle{id};-}--TextureHandle WebGPUDevice::importExternalTexture(u32 nativeId, const TextureDesc&) {- // A "native id" this backend already owns is one of ours — a render target's- // colour plane, adopted so a component can name it. On GL the two ids are the- // same number by construction; here the lookup is what makes them one.- if (textures_.count(nativeId) != 0) return TextureHandle{nativeId};- // A genuinely foreign surface (canvas, video frame) arrives as a WGPUTexture- // in a later slice, not as an integer.- stubOnce("importExternalTexture");- return TextureHandle::Invalid;+ return true;}-void WebGPUDevice::deleteTexture(TextureHandle texture) {- auto it = textures_.find(static_cast<u32>(texture));- if (it == textures_.end()) return;+void WebGPUDevice::releaseTexture(TextureRec& rec) {// The sample view first, and only when it is a view of its own: for a colour// texture it aliases `view`, and releasing that twice frees a live object.- if (it->second.sampleView && it->second.sampleView != it->second.view) {- evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(it->second.sampleView)));- wgpuTextureViewRelease(it->second.sampleView);+ if (rec.sampleView && rec.sampleView != rec.view) {+ evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(rec.sampleView)));+ wgpuTextureViewRelease(rec.sampleView);}- if (it->second.view) {- evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(it->second.view)));- wgpuTextureViewRelease(it->second.view);+ if (rec.view) {+ evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(rec.view)));+ wgpuTextureViewRelease(rec.view);}- if (it->second.texture) wgpuTextureRelease(it->second.texture);+ if (rec.texture) wgpuTextureRelease(rec.texture);+ rec = TextureRec{};+}++void WebGPUDevice::backendDeleteTexture(u32 id) {+ auto it = textures_.find(id);+ if (it == textures_.end()) return;+ releaseTexture(it->second);textures_.erase(it);}-void WebGPUDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,- const void* pixels, bool flipY) {- auto it = textures_.find(static_cast<u32>(texture));- if (it == textures_.end() || !pixels || !queue_) return;- if (isDepthFormat(it->second.format)) {+void WebGPUDevice::backendMoveTexture(u32 into, u32 from) {+ auto it = textures_.find(from);+ if (it == textures_.end()) return;+ textures_[into] = it->second;+ textures_.erase(from);+ for (u32 slot = 0; slot < kTextureSlots; ++slot) {+ if (texture_slots_[slot] == into || texture_slots_[slot] == from) bind_group_dirty_ = true;+ }+}++void WebGPUDevice::backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY) {+ auto it = textures_.find(id);+ if (it == textures_.end()) return;+ writeTexture(it->second, x, y, width, height, pixels, flipY);+}++void WebGPUDevice::writeTexture(const TextureRec& rec, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY) {+ if (!pixels || !queue_ || !rec.texture) return;+ if (isDepthFormat(rec.format)) {ES_LOG_ERROR("WebGPUDevice::updateTexture: depth-stencil textures are attachment-only");return;}WGPUTexelCopyTextureInfo dst{};- dst.texture = it->second.texture;+ dst.texture = rec.texture;dst.origin = WGPUOrigin3D{static_cast<u32>(x), static_cast<u32>(y), 0};// Source rows are what the caller allocated; destination rows are the texel// size WebGPU stores. They differ for RGB8, which has no WebGPU format and so// lands in an RGBA8 texture — reading dstRow from the source is the over-read.- const u32 srcBpp = gfxBytesPerPixel(it->second.srcFormat);- const u32 dstBpp = wgpuBytesPerPixel(it->second.srcFormat);+ const u32 srcBpp = gfxBytesPerPixel(rec.srcFormat);+ const u32 dstBpp = wgpuBytesPerPixel(rec.srcFormat);const usize dstRow = static_cast<usize>(width) * dstBpp;WGPUTexelCopyBufferLayout layout{};@@ -977,24 +964,23 @@ void WebGPUDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width,wgpuQueueWriteTexture(queue_, &dst, src, dstRow * height, &layout, &extent);}-void WebGPUDevice::setTextureParams(TextureHandle texture, TextureFilter minFilter,- TextureFilter magFilter, TextureWrap wrapS, TextureWrap wrapT) {+void WebGPUDevice::backendSetTextureParams(u32 id, const TextureDesc& desc) {// GL's texture-object sampler state, de-combined: the texture record carries// its params key and the bind group pairs it with a cached sampler object.- auto it = textures_.find(static_cast<u32>(texture));+ auto it = textures_.find(id);if (it == textures_.end()) return;- const u8 key = packSamplerKey(minFilter, magFilter, wrapS, wrapT);+ const u8 key = packSamplerKey(desc.minFilter, desc.magFilter, desc.wrapS, desc.wrapT);if (it->second.samplerKey == key) return;it->second.samplerKey = key;for (u32 slot = 0; slot < kTextureSlots; ++slot) {- if (texture_slots_[slot] == it->first) {+ if (texture_slots_[slot] == id) {bind_group_dirty_ = true;break;}}}-void WebGPUDevice::generateMipmaps(TextureHandle) { stubOnce("generateMipmaps"); }+void WebGPUDevice::backendGenerateMipmaps(u32) { stubOnce("generateMipmaps"); }void WebGPUDevice::bindTexture(u32 slot, TextureHandle texture) {if (slot >= kTextureSlots) return;@@ -1018,23 +1004,19 @@ bool WebGPUDevice::supportsCompressedFormat(GfxCompressedFormat format) {// Programs (WGSL shader modules)// =============================================================================-ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,- const GfxAttribBinding*, u32,- std::string* outLog, GfxShaderStage* outFailedStage) {- if (!isDeviceUsable()) {- if (outLog) *outLog = "device lost";- return ShaderHandle::Invalid;- }+bool WebGPUDevice::backendCreateProgram(u32 id, const GfxShaderSource& source,+ const GfxAttribBinding*, u32,+ std::string* outLog, GfxShaderStage* outFailedStage) {if (source.language != GfxShaderLanguage::WGSL) {if (outLog) *outLog = "WebGPUDevice compiles WGSL only";if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;ES_LOG_ERROR("WebGPUDevice::createProgram: unsupported shader language");- return ShaderHandle::Invalid;+ return false;}if (!device_) {if (outLog) *outLog = "no WGPUDevice";ES_LOG_ERROR("WebGPUDevice::createProgram: no device");- return ShaderHandle::Invalid;+ return false;}// A stage that names `tN`/`sN` without declaring it cannot compile, and WebGPU says@@ -1063,11 +1045,11 @@ ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,};if (undeclared(source.vertexSrc, "vertex")) {if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;- return ShaderHandle::Invalid;+ return false;}if (undeclared(source.fragmentSrc, "fragment")) {if (outFailedStage) *outFailedStage = GfxShaderStage::Fragment;- return ShaderHandle::Invalid;+ return false;}auto makeModule = [&](const char* code) -> WGPUShaderModule {@@ -1100,76 +1082,42 @@ ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);if (outLog) *outLog = "shader module creation failed";if (outFailedStage) *outFailedStage = rec.vertex ? GfxShaderStage::Fragment : GfxShaderStage::Vertex;- return ShaderHandle::Invalid;+ return false;}- const u32 id = next_id_++;programs_[id] = rec;- return ShaderHandle{id};+ return true;}-void WebGPUDevice::deleteProgram(ShaderHandle program) {- auto it = programs_.find(static_cast<u32>(program));+void WebGPUDevice::backendDeleteProgram(u32 id) {+ auto it = programs_.find(id);if (it == programs_.end()) return;if (it->second.vertex) wgpuShaderModuleRelease(it->second.vertex);if (it->second.fragment) wgpuShaderModuleRelease(it->second.fragment);programs_.erase(it);}-void WebGPUDevice::useProgram(ShaderHandle) { /* programs bind via pipelines */ }--// Loose uniforms do not exist on WebGPU: all uniform data rides the UBO bindings-// (0-4) and samplers ride bind groups. The engine reaches these only for sampler-// seeding on GLSL-shaped programs, which a WGSL pipeline never has.-i32 WebGPUDevice::getUniformLocation(ShaderHandle, const char*) { return -1; }-i32 WebGPUDevice::getAttribLocation(ShaderHandle, const char*) { return -1; }-void WebGPUDevice::setUniform1i(i32, i32) {}-void WebGPUDevice::setUniform1f(i32, f32) {}-void WebGPUDevice::setUniform2f(i32, f32, f32) {}-void WebGPUDevice::setUniform3f(i32, f32, f32, f32) {}-void WebGPUDevice::setUniform4f(i32, f32, f32, f32, f32) {}-void WebGPUDevice::setUniformMat3(i32, const f32*) {}-void WebGPUDevice::setUniformMat4(i32, const f32*) {}-std::vector<GfxUniformInfo> WebGPUDevice::getActiveUniforms(ShaderHandle) { return {}; }--u32 WebGPUDevice::getUniformBlockIndex(ShaderHandle, const char*) {- // Blocks bind by @group/@binding in WGSL; Shader::compile skips GL-style- // block wiring when this reports "absent".- return GFX_INVALID_UNIFORM_BLOCK;-}-void WebGPUDevice::uniformBlockBinding(ShaderHandle, u32, u32) {}-// =============================================================================// Pipelines (descriptors retained; WGPURenderPipeline built lazily per pass// depth-stencil shape — WebGPU validates that coupling, GL never had it)// =============================================================================-PipelineHandle WebGPUDevice::createPipeline(const PipelineDesc& desc) {- 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);- }- const u32 id = next_id_++;- pipelines_[id] = PipelineRec{desc, {}};- return static_cast<PipelineHandle>(id);-}-WGPURenderPipeline WebGPUDevice::ensurePipeline(u32 id) {- auto it = pipelines_.find(id);- if (it == pipelines_.end() || !device_) return nullptr;+ const PipelineDesc* described = pipelineDesc(PipelineHandle{id});+ if (!described || !device_) return nullptr;+ PipelineRec& built = pipelines_[id];const u32 dsVariant = dsVariantOf(pass_ds_format_);const u32 variant = dsVariant * kColorVariantCount + colorVariantOf(pass_color_format_);- if (it->second.variants[variant]) return it->second.variants[variant];+ if (built.variants[variant]) return built.variants[variant];- const PipelineDesc& desc = it->second.desc;+ const PipelineDesc& desc = *described;auto progIt = programs_.find(static_cast<u32>(desc.program));- auto layoutIt = layouts_.find(static_cast<u32>(desc.vertexLayout));- if (progIt == programs_.end() || layoutIt == layouts_.end()) {+ const VertexLayoutDesc* layout = vertexLayoutDesc(desc.vertexLayout);+ if (progIt == programs_.end() || !layout) {ES_LOG_ERROR("WebGPUDevice::ensurePipeline: missing program or layout");return nullptr;}- const VertexLayoutDesc& vl = layoutIt->second;+ const VertexLayoutDesc& vl = *layout;// RHI layout (attributes across up to 2 slots) -> per-slot WGPU buffer layouts.WGPUVertexAttribute attrs[MAX_VERTEX_ATTRIBUTES] = {};@@ -1239,16 +1187,15 @@ WGPURenderPipeline WebGPUDevice::ensurePipeline(u32 id) {"pass target has no depth-stencil attachment");}- it->second.variants[variant] = wgpuDeviceCreateRenderPipeline(device_, &pd);- if (!it->second.variants[variant]) {+ built.variants[variant] = wgpuDeviceCreateRenderPipeline(device_, &pd);+ if (!built.variants[variant]) {ES_LOG_ERROR("WebGPUDevice::ensurePipeline: creation failed");}- return it->second.variants[variant];+ return built.variants[variant];}-void WebGPUDevice::setPipeline(PipelineHandle pipeline) {- const u32 id = static_cast<u32>(pipeline);- current_pipeline_ = id;+void WebGPUDevice::backendSetPipeline(u32 id, const PipelineDesc&) {+ bound_pipeline_ = id;if (!pass_) return;if (WGPURenderPipeline p = ensurePipeline(id)) {wgpuRenderPassEncoderSetPipeline(pass_, p);@@ -1261,8 +1208,6 @@ void WebGPUDevice::setStencilReference(i32 reference) {if (pass_) wgpuRenderPassEncoderSetStencilReference(pass_, static_cast<u32>(reference));}-void WebGPUDevice::invalidatePipelineCache() {}-WGPUSampler WebGPUDevice::samplerFor(u8 key) {auto it = samplers_.find(key);if (it != samplers_.end()) return it->second;@@ -1339,11 +1284,10 @@ struct ClearColor { value : vec4f };pld.bindGroupLayouts = &clear_bgl_;clear_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);- clear_color_ubo_ = createBuffer({GfxBufferUsage::Uniform, 16, true}, nullptr);- auto uboIt = buffers_.find(static_cast<u32>(clear_color_ubo_));+ clear_color_buffer_ = makeBuffer(GfxBufferUsage::Uniform, 16, nullptr);WGPUBindGroupEntry entry{};entry.binding = 0;- entry.buffer = uboIt->second.buffer;+ entry.buffer = clear_color_buffer_;entry.offset = 0;entry.size = 16;WGPUBindGroupDescriptor bgd{};@@ -1409,7 +1353,7 @@ void WebGPUDevice::drawInternalClear(bool color, bool depth, bool stencil,if (!pipeline || !clear_bind_group_) return;const f32 black[4] = {0.0f, 0.0f, 0.0f, 0.0f};- updateBuffer(clear_color_ubo_, 0, rgba ? rgba : black, 16);+ writeBufferPadded(clear_color_buffer_, 0, rgba ? rgba : black, 16);// A region rides its own scissor and restores the full target; without one// (mid-pass stencil reset) the currently active scissor applies — the same@@ -1433,7 +1377,7 @@ void WebGPUDevice::drawInternalClear(bool color, bool depth, bool stencil,// The triangle clobbered pipeline/bind-group pass state; force the next// user draw to re-establish everything.- current_pipeline_ = 0;+ bound_pipeline_ = 0;bind_group_dirty_ = true;}@@ -1537,23 +1481,23 @@ WGPUPipelineLayout WebGPUDevice::pipelineLayoutFor(u32 group0Mask, u32 group1Mas}void WebGPUDevice::ensureDummies() {- if (dummy_ubo_ == BufferHandle::Invalid || buffers_.find(static_cast<u32>(dummy_ubo_)) == buffers_.end()) {+ if (!dummy_ubo_.buffer) {// Sized past the largest engine block (LightConstants, 1184 bytes) so a// declared-but-unbound block always satisfies draw-time size validation.const std::vector<u8> zeros(2048, 0);- dummy_ubo_ = createBuffer({GfxBufferUsage::Uniform, 2048, false}, zeros.data());+ dummy_ubo_ = BufferRec{makeBuffer(GfxBufferUsage::Uniform, 2048, zeros.data()), 2048,+ GfxBufferUsage::Uniform};}- if (dummy_texture_ == 0 || textures_.find(dummy_texture_) == textures_.end()) {+ if (!dummy_texture_.texture) {const u8 white[4] = {255, 255, 255, 255};- TextureDesc td{};- dummy_texture_ = static_cast<u32>(createTexture(td, white));+ makeTexture(TextureDesc{}, white, dummy_texture_);}- if (dummy_depth_texture_ == 0 || textures_.find(dummy_depth_texture_) == textures_.end()) {+ if (!dummy_depth_texture_.texture) {// Never written, only bound: a depth format takes no upload, and the// point is a texture of the right KIND under a declared depth binding.TextureDesc td{};td.format = GfxPixelFormat::Depth24Stencil8;- dummy_depth_texture_ = static_cast<u32>(createTexture(td, nullptr));+ makeTexture(td, nullptr, dummy_depth_texture_);}}@@ -1582,12 +1526,12 @@ WGPUBindGroup WebGPUDevice::cachedBindGroup(u32 group, u32 mask, const u64* ids,void WebGPUDevice::flushBindGroup() {if (!bind_group_dirty_ || !pass_ || !device_) return;- WGPURenderPipeline p = ensurePipeline(current_pipeline_);+ WGPURenderPipeline p = ensurePipeline(bound_pipeline_);if (!p) return;const ProgramRec* prog = nullptr;- if (auto pipeIt = pipelines_.find(current_pipeline_); pipeIt != pipelines_.end()) {- auto progIt = programs_.find(static_cast<u32>(pipeIt->second.desc.program));+ if (const PipelineDesc* desc = pipelineDesc(PipelineHandle{bound_pipeline_})) {+ auto progIt = programs_.find(static_cast<u32>(desc->program));if (progIt != programs_.end()) prog = &progIt->second;}if (!prog) return;@@ -1609,13 +1553,13 @@ void WebGPUDevice::flushBindGroup() {for (u32 slot = 0; slot < kUniformSlots; ++slot) {if ((prog->group0Mask & (1u << slot)) == 0) continue;auto it = buffers_.find(uniform_slots_[slot]);- if (it == buffers_.end()) it = buffers_.find(static_cast<u32>(dummy_ubo_));- if (it == buffers_.end()) continue;+ const BufferRec& bound = it != buffers_.end() && it->second.buffer ? it->second : dummy_ubo_;+ if (!bound.buffer) continue;WGPUBindGroupEntry e{};e.binding = slot;- e.buffer = it->second.buffer;+ e.buffer = bound.buffer;e.offset = 0;- e.size = it->second.size;+ e.size = bound.size;entries[count++] = e;}@@ -1637,11 +1581,8 @@ void WebGPUDevice::flushBindGroup() {// the bound unit's view/sampler or the 1x1 white dummy — so the group// always matches the explicit layout, textures bound or not.if (prog->group1Mask != 0) {- auto dummyIt = textures_.find(dummy_texture_);- const TextureRec* dummy = (dummyIt != textures_.end()) ? &dummyIt->second : nullptr;- auto depthDummyIt = textures_.find(dummy_depth_texture_);- const TextureRec* depthDummy =- (depthDummyIt != textures_.end()) ? &depthDummyIt->second : nullptr;+ const TextureRec* dummy = dummy_texture_.texture ? &dummy_texture_ : nullptr;+ const TextureRec* depthDummy = dummy_depth_texture_.texture ? &dummy_depth_texture_ : nullptr;WGPUBindGroupEntry texEntries[kTextureSlots * 2];u32 texCount = 0;@@ -1730,24 +1671,13 @@ void WebGPUDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType,indexByteOffset / indexSize, 0, 0);}-FramebufferHandle WebGPUDevice::createFramebuffer(const FramebufferDesc& desc) {- if (!isDeviceUsable()) return FramebufferHandle::Default;- FramebufferRec rec{};- rec.color0 = static_cast<u32>(desc.color0);- rec.depthStencil = static_cast<u32>(desc.depthStencil);- if (rec.depthStencil != 0 && !textures_.count(rec.depthStencil)) {+bool WebGPUDevice::backendCreateFramebuffer(u32, const FramebufferDesc& desc) {+ const u32 depthStencil = static_cast<u32>(desc.depthStencil);+ if (depthStencil != 0 && !textures_.count(depthStencil)) {ES_LOG_ERROR("WebGPUDevice::createFramebuffer: unknown depth-stencil texture");- return FramebufferHandle::Default;+ return false;}- // Framebuffer ids share the Default==0 namespace with the surface, so they- // come from their own counter offset well clear of it.- const u32 id = 0x40000000u + next_framebuffer_id_++;- framebuffers_[id] = rec;- return static_cast<FramebufferHandle>(id);-}--void WebGPUDevice::deleteFramebuffer(FramebufferHandle framebuffer) {- framebuffers_.erase(static_cast<u32>(framebuffer));+ return true;}void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {@@ -1763,27 +1693,29 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {pass_depth_texture_ = 0;pass_is_surface_ = desc.target == FramebufferHandle::Default;if (desc.target != FramebufferHandle::Default) {- auto fbIt = framebuffers_.find(static_cast<u32>(desc.target));- if (fbIt == framebuffers_.end()) {+ const FramebufferDesc* fb = framebufferDesc(desc.target);+ if (!fb) {ES_LOG_ERROR("WebGPUDevice::beginRenderPass: unknown framebuffer");return;}- auto texIt = textures_.find(fbIt->second.color0);+ const u32 color0 = static_cast<u32>(fb->color0);+ const u32 depthStencil = static_cast<u32>(fb->depthStencil);+ auto texIt = textures_.find(color0);if (texIt == textures_.end()) {ES_LOG_ERROR("WebGPUDevice::beginRenderPass: framebuffer color texture missing");return;}targetView = texIt->second.view;pass_color_format_ = texIt->second.format;- pass_color_texture_ = fbIt->second.color0;+ pass_color_texture_ = color0;pass_width_ = texIt->second.width;pass_height_ = texIt->second.height;- if (fbIt->second.depthStencil != 0) {- auto dsIt = textures_.find(fbIt->second.depthStencil);+ if (depthStencil != 0) {+ auto dsIt = textures_.find(depthStencil);if (dsIt != textures_.end()) {dsView = dsIt->second.view;pass_ds_format_ = dsIt->second.format;- pass_depth_texture_ = fbIt->second.depthStencil;+ pass_depth_texture_ = depthStencil;}}} else {@@ -2014,9 +1946,9 @@ ReadbackHandle WebGPUDevice::requestReadback(FramebufferHandle target, u32 w, u3stubOnce("requestReadback(default framebuffer) — use captureNextFrame");return ReadbackHandle::Invalid;}- auto fit = framebuffers_.find(static_cast<u32>(target));- if (fit == framebuffers_.end()) return ReadbackHandle::Invalid;- auto tit = textures_.find(fit->second.color0);+ const FramebufferDesc* fb = framebufferDesc(target);+ if (!fb) return ReadbackHandle::Invalid;+ auto tit = textures_.find(static_cast<u32>(fb->color0));if (tit == textures_.end() || !tit->second.texture) return ReadbackHandle::Invalid;const u32 id = allocReadback(w, h);@@ -2151,9 +2083,11 @@ void WebGPUDevice::ensureTimestamps() {timestamp_supported_ = timestamp_resolve_ && gpu_time_ring_[0].buf;}-u32 WebGPUDevice::createTimerQuery() {+// One query set serves every timer: timing rides the surface pass, so a query id+// only has to exist for the engine's GpuTimer to turn on.+bool WebGPUDevice::backendCreateTimerQuery(u32) {ensureTimestamps();- return timestamp_supported_ ? 1 : 0; // non-zero → the engine's GpuTimer enables; 0 → no GPU timing (as before)+ return timestamp_supported_;}void WebGPUDevice::beginTimerQuery(u32) {} // timing rides the pass: attached at beginRenderPass, resolved at endRenderPassdiff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hppindex 523485677..dcf8e8bdc 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp@@ -91,54 +91,22 @@ public:bool pollDeviceLost() override;- /**- * @brief Takes over a replacement device, rebuilding everything under it.- * @details Only whoever created a WebGPU device can replace it, so recovery- * arrives from outside rather than being something this class can- * perform. Every cached object belonged to the dead device and is- * released; the surface is re-created against the new one.- */- bool adoptDevice(WGPUDevice device);-/** @brief Hands a replacement in for the next recovery attempt to take up. */bool provideReplacementDevice(void* nativeDevice) override {pending_device_ = static_cast<WGPUDevice>(nativeDevice);return pending_device_ != nullptr;}-protected:- void captureDeviceIdentity() override;- bool recreateDevice() override;--public:-void setViewport(i32 x, i32 y, u32 w, u32 h) override;void clearStencil(i32 value) override;void setScissorTest(bool enabled) override;void setScissor(i32 x, i32 y, i32 w, i32 h) override;- BufferHandle createBuffer(const BufferDesc& desc, const void* initialData) override;- void deleteBuffer(BufferHandle buffer) override;- void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) override;- void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) override;void setUniformBuffer(u32 slot, BufferHandle buffer) override;-- VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc) override;- void deleteVertexLayout(VertexLayoutHandle layout) override;void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override;void setIndexBuffer(BufferHandle buffer) override;- TextureHandle createTexture(const TextureDesc& desc, const void* pixels) override;- TextureHandle createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,- const void* data, u32 byteLength, u32 mipLevels) override;- TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc) override;- void deleteTexture(TextureHandle texture) override;- void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,- const void* pixels, bool flipY) override;- void setTextureParams(TextureHandle texture, TextureFilter minFilter, TextureFilter magFilter,- TextureWrap wrapS, TextureWrap wrapT) override;- void generateMipmaps(TextureHandle texture) override;void bindTexture(u32 slot, TextureHandle texture) override;bool supportsCompressedFormat(GfxCompressedFormat format) override;// Float-target rendering is a WebGPU core capability.@@ -151,37 +119,14 @@ public:/// WebGPU stores a texture from the top down.bool textureOriginTopLeft() const override { return true; }- ShaderHandle createProgram(const GfxShaderSource& source,- const GfxAttribBinding* bindings, u32 bindingCount,- std::string* outLog, GfxShaderStage* outFailedStage) override;- void deleteProgram(ShaderHandle program) override;- void useProgram(ShaderHandle program) override;- i32 getUniformLocation(ShaderHandle program, const char* name) override;- i32 getAttribLocation(ShaderHandle program, const char* name) override;- void setUniform1i(i32 location, i32 value) override;- void setUniform1f(i32 location, f32 value) override;- void setUniform2f(i32 location, f32 x, f32 y) override;- void setUniform3f(i32 location, f32 x, f32 y, f32 z) override;- void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) override;- void setUniformMat3(i32 location, const f32* value) override;- void setUniformMat4(i32 location, const f32* value) override;- std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle program) override;-- u32 getUniformBlockIndex(ShaderHandle program, const char* blockName) override;- void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) override;-- PipelineHandle createPipeline(const PipelineDesc& desc) override;- void setPipeline(PipelineHandle pipeline) override;+void setStencilReference(i32 reference) override;- void invalidatePipelineCache() override;void drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) override;void drawArrays(u32 firstVertex, u32 vertexCount) override;void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 indexByteOffset,u32 instanceCount) override;- FramebufferHandle createFramebuffer(const FramebufferDesc& desc) override;- void deleteFramebuffer(FramebufferHandle framebuffer) override;void beginRenderPass(const RenderPassDesc& desc) override;void endRenderPass() override;void resizeBackbuffer(u32 width, u32 height) override;@@ -191,7 +136,6 @@ public:bool takeReadback(ReadbackHandle handle, void* dest, usize destSize) override;void discardReadback(ReadbackHandle handle) override;- u32 createTimerQuery() override;void beginTimerQuery(u32 query) override;void endTimerQuery() override;bool timerDisjoint() override;@@ -202,6 +146,53 @@ public:std::string getString(GfxStringName name) override;i32 getInt(GfxIntParam param) override;+protected:+ void captureDeviceIdentity() override;+ bool recreateDevice() override;++ bool backendCreateBuffer(u32 id, const BufferDesc& desc, const void* data) override;+ void backendDeleteBuffer(u32 id) override;+ void backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) override;+ void backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) override;++ bool backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) override;+ bool backendCreateCompressedTexture(u32 id, const TextureDesc& desc, GfxCompressedFormat format,+ const void* data, u32 byteLength, u32 mipLevels) override;+ /** A foreign surface (canvas, video frame) arrives as a WGPUTexture, never an integer. */+ bool backendAdoptTexture(u32, u32, const TextureDesc&) override { return false; }+ void backendDeleteTexture(u32 id) override;+ void backendMoveTexture(u32 into, u32 from) override;+ void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY) override;+ void backendSetTextureParams(u32 id, const TextureDesc& desc) override;+ void backendGenerateMipmaps(u32 id) override;++ bool backendCreateProgram(u32 id, const GfxShaderSource& source,+ const GfxAttribBinding* bindings, u32 bindingCount,+ std::string* outLog, GfxShaderStage* outFailedStage) override;+ void backendDeleteProgram(u32 id) override;+ // Programs bind through pipelines, uniforms through UBO bindings and blocks by+ // @group/@binding: the GL-shaped program state has nothing to reach here.+ void backendUseProgram(u32) override {}+ i32 backendUniformLocation(u32, const char*) override { return -1; }+ i32 backendAttribLocation(u32, const char*) override { return -1; }+ void backendSetUniform(i32, const GfxUniformValue&) override {}+ std::vector<GfxUniformInfo> backendActiveUniforms(u32) override { return {}; }+ u32 backendUniformBlockIndex(u32, const char*) override { return GFX_INVALID_UNIFORM_BLOCK; }+ void backendUniformBlockBinding(u32, u32, u32) override {}++ bool backendAcceptsVertexLayout(const VertexLayoutDesc& desc) override;+ void backendDeleteVertexLayout(u32) override {}+ void backendSetPipeline(u32 id, const PipelineDesc& desc) override;+ void backendInvalidatePipelineCache() override {}++ bool backendCreateFramebuffer(u32 id, const FramebufferDesc& desc) override;+ void backendDeleteFramebuffer(u32) override {}++ bool backendCreateTimerQuery(u32 id) override;+ u32 backendReadbackCount() const override { return static_cast<u32>(readbacks_.size()); }++public:// -------------------------------------------------------------------------// Bring-up introspection (tests / slice-2 plumbing)// -------------------------------------------------------------------------@@ -308,27 +299,12 @@ private:/** Match the backbuffer's depth-stencil companion to @p width x @p height. */bool ensureSurfaceDepth(u32 width, u32 height);-public:- usize bufferCount() const { return buffers_.size(); }- usize textureCount() const { return textures_.size(); }- usize layoutCount() const { return layouts_.size(); }- usize pipelineDescCount() const { return pipelines_.size(); }-- GfxLiveObjects liveObjects() const override {- return GfxLiveObjects{- static_cast<u32>(buffers_.size()),- static_cast<u32>(textures_.size()),- static_cast<u32>(programs_.size()),- static_cast<u32>(layouts_.size()),- static_cast<u32>(pipelines_.size()),- static_cast<u32>(framebuffers_.size()),- static_cast<u32>(readbacks_.size()),- };- }- const VertexLayoutDesc* layoutDesc(VertexLayoutHandle handle) const;- const PipelineDesc* pipelineDesc(PipelineHandle handle) const;+ /**+ * @brief Takes up a replacement device: every object of the old one is released+ * and the surface is re-made, leaving the registry to rebuild the rest.+ */+ bool adoptDevice(WGPUDevice device);-private:/** A GL-style rect's y (origin bottom-left) in this pass' coordinates* (origin top-left). See the definition. */i32 flipRectY(i32 y, i32 height) const;@@ -373,14 +349,9 @@ private:u32 group1DepthMask = 0;};struct PipelineRec {- PipelineDesc desc;/// Lazily built per pass shape: [ds * kColorVariantCount + color].WGPURenderPipeline variants[static_cast<u32>(kDsVariantCount) * static_cast<u32>(kColorVariantCount)] = {};};- struct FramebufferRec {- u32 color0 = 0; ///< TextureHandle id of the color attachment.- u32 depthStencil = 0; ///< TextureHandle id (0 = none).- };struct ReadbackRec {WGPUBuffer buffer = nullptr; ///< CopyDst|MapRead staging buffer.u32 width = 0;@@ -400,6 +371,14 @@ private:/** @brief Builds (once) and returns the WGPURenderPipeline for a handle,* in the variant matching the current pass's depth-stencil shape. */WGPURenderPipeline ensurePipeline(u32 id);++ WGPUBuffer makeBuffer(GfxBufferUsage usage, u32 size, const void* data);+ /** @brief A texture and its views; false with @p out untouched when creation fails. */+ bool makeTexture(const TextureDesc& desc, const void* pixels, TextureRec& out);+ void writeTexture(const TextureRec& rec, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY);+ /** @brief Releases a texture's views and storage, dropping bind groups that name them. */+ void releaseTexture(TextureRec& rec);/** @brief Returns the cached explicit bind-group layout for a binding mask.* Group 0 entries are uniform buffers at their slot; group 1 entries* are texture_2d/sampler pairs per the WebGPUMappings unit→binding@@ -471,10 +450,6 @@ private:WGPUTexture surface_depth_texture_ = nullptr;WGPUTextureView surface_depth_view_ = nullptr;- // Offscreen targets.- std::unordered_map<u32, FramebufferRec> framebuffers_;- u32 next_framebuffer_id_ = 1;-// In-flight readbacks: staging buffers whose mapAsync callback flips status.std::unordered_map<u32, ReadbackRec> readbacks_;u32 next_readback_id_ = 1;@@ -500,7 +475,7 @@ private:WGPUBindGroupLayout clear_bgl_ = nullptr;WGPUPipelineLayout clear_layout_ = nullptr;WGPUBindGroup clear_bind_group_ = nullptr;- BufferHandle clear_color_ubo_{};+ WGPUBuffer clear_color_buffer_ = nullptr;// Per-pass state.u32 pass_width_ = 0; ///< Current pass target size (scissor-off rectangle).@@ -518,7 +493,7 @@ private:u32 surface_depth_height_ = 0;WGPUTexture frame_texture_ = nullptr; ///< The frame's swapchain texture (released at endFrame).WGPUTextureView frame_view_ = nullptr;- u32 current_pipeline_ = 0;+ u32 bound_pipeline_ = 0;u32 bound_index_buffer_ = 0;i32 stencil_ref_ = 0; ///< Last user-set reference (re-applied after internal quads)./// Nine: the eight the engine had, plus where a draw's objects start in the@@ -594,18 +569,19 @@ private:// compatibility holds by identity.std::unordered_map<u64, WGPUBindGroupLayout> group_layouts_;std::unordered_map<u64, WGPUPipelineLayout> pipeline_layouts_;- BufferHandle dummy_ubo_{}; ///< Zeroed backfill for declared-but-unbound UBO slots.- u32 dummy_texture_ = 0; ///< 1x1 white backfill for declared-but-unbound units.+ // Backfill belongs to this backend, not to the registry: nothing above it can+ // name these, so they are made again lazily rather than recovered.+ BufferRec dummy_ubo_; ///< Zeroed backfill for declared-but-unbound UBO slots.+ TextureRec dummy_texture_; ///< 1x1 white backfill for declared-but-unbound units./// The same for a depth unit: an RGBA8 dummy under a `sampleType = Depth`/// entry is a validation error, so a declared-but-unbound depth binding/// needs a depth texture to stand in.- u32 dummy_depth_texture_ = 0;+ TextureRec dummy_depth_texture_;- u32 next_id_ = 1;+ /** This device's objects by registry id. */std::unordered_map<u32, BufferRec> buffers_;std::unordered_map<u32, TextureRec> textures_;std::unordered_map<u32, ProgramRec> programs_;- std::unordered_map<u32, VertexLayoutDesc> layouts_;std::unordered_map<u32, PipelineRec> pipelines_;std::vector<std::string> stub_logged_;};diff --git a/src/esengine/resource/Mesh.hpp b/src/esengine/resource/Mesh.hppindex e8b3e34a8..ca49b495a 100644--- a/src/esengine/resource/Mesh.hpp+++ b/src/esengine/resource/Mesh.hpp@@ -25,7 +25,7 @@ namespace esengine {*/enum class MeshRecovery : u8 {SourceReplayable, ///< Replayable from an asset the loader can load again.- HostOnly, ///< Built in this process from bytes kept nowhere else.+ HostOnly, ///< Built in this process; the device keeps its bytes.};/**@@ -45,13 +45,9 @@ struct MeshMorphSource {* @brief Buffers, the layout that describes them, and the bounds culling reads.** @details One record because the three are inseparable: a buffer without its- * layout cannot be drawn, and bounds kept elsewhere go stale. Material,- * layer and transform belong to the entity, so one mesh serves many.- *- * The handle is a LOGICAL identity: the buffers and the layout realize- * it on ONE device generation and a lost device takes all three, while- * the handle survives. Where the geometry comes back FROM is the- * minting producer's to declare — tools/meshProducers.mjs.+ * layout cannot be drawn, and bounds kept elsewhere go stale. Where the+ * geometry comes back from after a device loss is the minting producer's+ * to declare — tools/meshProducers.mjs.*/class Mesh {public:@@ -70,11 +66,6 @@ public:* without one is never mistaken for recoverable. */MeshRecovery recovery = MeshRecovery::HostOnly;- /** The device generation the three handles above belong to. A diagnostic:- * it answers whether a mesh was really rebuilt, where a non-zero handle- * only looks like it. */- u64 realizationGeneration = 0;-/** Whether the vertices carry normals — decides the per-object record's shape* and which shader variant draws it. */bool hasNormals = false;@@ -108,9 +99,7 @@ public:return morphTargetCount > 0 && morphTexture != TextureHandle::Invalid;}- /** Whether a live GPU realization stands behind this identity. False from a- * device loss until the rematerialization that replaces it, which is what- * stops the draw path consuming buffers that died with their device. */+ /** Whether GPU buffers stand behind this identity. */bool hasRealization() const {return vertexBuffer != BufferHandle::Invalid&& indexBuffer != BufferHandle::Invaliddiff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cppindex fa71abacf..d51bb71c9 100644--- a/src/esengine/resource/ResourceManager.cpp+++ b/src/esengine/resource/ResourceManager.cpp@@ -27,6 +27,23 @@namespace esengine::resource {+namespace {++bool meshOwed(const Mesh& mesh, const std::vector<GfxOwedContent>& owed) {+ for (const GfxOwedContent& entry : owed) {+ if (entry.kind == GfxOwedContent::Kind::Buffer+ && (entry.id == static_cast<u32>(mesh.vertexBuffer) || entry.id == static_cast<u32>(mesh.indexBuffer))) {+ return true;+ }+ if (entry.kind == GfxOwedContent::Kind::Texture && entry.id == static_cast<u32>(mesh.morphTexture)) {+ return true;+ }+ }+ return false;+}++} // namespace+void ResourceManager::init(GfxDevice& device) {if (initialized_) {ES_LOG_WARN("ResourceManager already initialized");@@ -176,9 +193,17 @@ u32 ResourceManager::getShaderRefCount(ShaderHandle handle) const {// Texture Resources// =============================================================================-TextureHandle ResourceManager::createTexture(const TextureSpecification& spec) {+GfxContent toGfxContent(ResourceContent content) {+ switch (content) {+ case ResourceContent::Transient: return GfxContent::transient();+ case ResourceContent::Retained: return GfxContent::retained();+ default: return GfxContent::sourced(static_cast<u32>(content), 0);+ }+}++TextureHandle ResourceManager::createTexture(ResourceContent content, const TextureSpecification& spec) {if (!device_) return {};- auto texture = Texture::create(*device_, spec);+ auto texture = Texture::create(*device_, toGfxContent(content), spec);if (!texture) {ES_LOG_ERROR("Failed to create texture from spec");return TextureHandle();@@ -187,11 +212,11 @@ TextureHandle ResourceManager::createTexture(const TextureSpecification& spec) {return textures_.add(std::move(texture), "", bytes);}-TextureHandle ResourceManager::createTexture(u32 width, u32 height, ConstSpan<u8> pixels,- TextureFormat format, bool flipY) {+TextureHandle ResourceManager::createTexture(ResourceContent content, u32 width, u32 height,+ ConstSpan<u8> pixels, TextureFormat format, bool flipY) {if (!device_) return {};- std::vector<u8> pixelVec(pixels.begin(), pixels.end());- auto texture = Texture::create(*device_, width, height, pixelVec, format, flipY);+ auto texture = Texture::create(*device_, toGfxContent(content), width, height,+ std::span<const u8>(pixels.data(), pixels.size()), format, flipY);if (!texture) {ES_LOG_ERROR("Failed to create texture from pixels");return TextureHandle();@@ -200,11 +225,11 @@ TextureHandle ResourceManager::createTexture(u32 width, u32 height, ConstSpan<u8return textures_.add(std::move(texture), "", bytes);}-TextureHandle ResourceManager::createCompressedTexture(u32 width, u32 height,+TextureHandle ResourceManager::createCompressedTexture(ResourceContent content, u32 width, u32 height,GfxCompressedFormat format, ConstSpan<u8> data,u32 mipLevels) {if (!device_) return {};- auto texture = Texture::createCompressed(*device_, width, height, format,+ auto texture = Texture::createCompressed(*device_, toGfxContent(content), width, height, format,std::span<const u8>(data.data(), data.size()), mipLevels);if (!texture) {ES_LOG_ERROR("Failed to create compressed texture");@@ -261,10 +286,12 @@ u32 ResourceManager::getTextureRefCount(TextureHandle handle) const {return textures_.getRefCount(handle);}-TextureHandle ResourceManager::registerExternalTexture(u32 glTextureId, u32 width, u32 height, usize bytes) {+TextureHandle ResourceManager::registerExternalTexture(ResourceContent content, u32 glTextureId,+ u32 width, u32 height, usize bytes) {if (!device_) return {};- auto texture = Texture::createFromExternalId(*device_, glTextureId, width, height, TextureFormat::RGBA8);- if (!texture) {+ auto texture = Texture::createFromExternalId(*device_, toGfxContent(content), glTextureId,+ width, height, TextureFormat::RGBA8);+ if (!texture || texture->handle() == ::esengine::TextureHandle::Invalid) {ES_LOG_ERROR("Failed to register external texture (GL ID: {})", glTextureId);return TextureHandle();}@@ -274,85 +301,45 @@ TextureHandle ResourceManager::registerExternalTexture(u32 glTextureId, u32 widtreturn textures_.add(std::move(texture), "", bytes);}-u32 ResourceManager::recreateGpuShaders() {- u32 rebuilt = 0;- u32 failed = 0;- shaders_.forEachAlive([&](ShaderHandle, Shader& shader) {- if (shader.recompile()) ++rebuilt;- else ++failed;- });- if (failed > 0) ES_LOG_ERROR("Device recovery: {} shader(s) failed to rebuild", failed);- ES_LOG_INFO("Device recovery: {} shader(s) rebuilt behind their handles", rebuilt);- 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) {- // Retargeted, never deleted: the GPU object is already gone, and asking- // a dead device to free its id is at best a no-op. owns=false so the- // shared placeholder is not freed when one of them is released.- texture.retarget(placeholder, /*owns=*/false);- awaitingReupload_.push_back(handle);- });- ES_LOG_INFO("Device loss: {} texture(s) now on the placeholder, awaiting re-upload",- awaitingReupload_.size());-}--bool ResourceManager::retargetExternalTexture(TextureHandle handle, u32 glTextureId,- u32 width, u32 height) {- if (!device_) return false;- Texture* texture = textures_.get(handle);- if (!texture) return false;-- TextureDesc desc;- desc.width = width;- desc.height = height;- desc.format = GfxPixelFormat::RGBA8;- texture->retarget(device_->importExternalTexture(glTextureId, desc), /*owns=*/false);-- for (usize i = 0; i < awaitingReupload_.size(); ++i) {- if (awaitingReupload_[i] == handle) {- awaitingReupload_[i] = awaitingReupload_.back();- awaitingReupload_.pop_back();- break;- }- }- return true;+TextureHandle ResourceManager::wrapDeviceTexture(::esengine::TextureHandle texture, u32 width, u32 height) {+ if (!device_) return {};+ auto wrapper = Texture::borrow(*device_, texture, width, height);+ if (!wrapper) return {};+ // The owner pays for the memory; a borrow costs the budget nothing.+ return textures_.add(std::move(wrapper), "", 0);}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 to && from && to->adoptContent(*from);+}++std::vector<ResourceManager::OwedTexture> ResourceManager::texturesAwaitingReupload() const {+ std::vector<OwedTexture> out;+ if (!device_) return out;+ const std::vector<GfxOwedContent> owed = device_->owedContent();+ if (owed.empty()) return out;+ textures_.forEachAlive([&](TextureHandle handle, const Texture& texture) {+ for (const GfxOwedContent& entry : owed) {+ if (entry.kind == GfxOwedContent::Kind::Texture && entry.id == texture.getId()) {+ out.push_back({handle, static_cast<ResourceContent>(entry.provider)});+ break;+ }}- }- return true;+ });+ return out;}-std::vector<TextureHandle> ResourceManager::texturesAwaitingReupload() const {- return awaitingReupload_;+void ResourceManager::forgoTextureContent(TextureHandle handle) {+ const Texture* texture = textures_.get(handle);+ if (!device_ || !texture) return;+ for (const GfxOwedContent& entry : device_->owedContent()) {+ if (entry.kind == GfxOwedContent::Kind::Texture && entry.id == texture->getId()) {+ device_->forgoContent(entry);+ return;+ }+ }}void ResourceManager::registerTextureWithPath(TextureHandle handle, const std::string& path) {@@ -375,11 +362,12 @@ TextureHandle ResourceManager::acquireTextureByPath(const std::string& path) {++stats_.cacheMisses;return handle;}- // A texture on the placeholder no longer holds this path's content, so a- // residency hit answers the re-upload with the very thing it replaces — a- // recovery that confirms itself and draws white. Linear: empty at rest.- for (TextureHandle awaiting : awaitingReupload_) {- if (awaiting == handle) {+ // A texture still owed its content does not hold this path's pixels, so a+ // residency hit would answer the re-upload with the very thing it replaces —+ // a recovery that confirms itself and draws blank. Empty at rest.+ const Texture* texture = textures_.get(handle);+ for (const GfxOwedContent& entry : device_ ? device_->owedContent() : std::vector<GfxOwedContent>{}) {+ if (texture && entry.kind == GfxOwedContent::Kind::Texture && entry.id == texture->getId()) {++stats_.cacheMisses;return TextureHandle{};}@@ -465,9 +453,9 @@ void ResourceManager::removeTextureMetadata(TextureHandle handle) {// Vertex Buffer Resources// =============================================================================-VertexBufferHandle ResourceManager::createVertexBuffer(u32 sizeBytes) {+VertexBufferHandle ResourceManager::createVertexBuffer(GfxContent content, u32 sizeBytes) {if (!device_) return {};- auto buffer = VertexBuffer::create(*device_, sizeBytes);+ auto buffer = VertexBuffer::create(*device_, content, sizeBytes);if (!buffer) {ES_LOG_ERROR("Failed to create dynamic vertex buffer");return VertexBufferHandle();@@ -574,8 +562,13 @@ bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpconst VertexBufferHandle previousVertices = mesh.vertices;const IndexBufferHandle previousIndices = mesh.indices;- const VertexBufferHandle vertices = createVertexBuffer(vertexBytes);- const IndexBufferHandle indices_handle = createIndexBuffer(indices);+ // A replayable mesh is refilled by its source; one built in this process has+ // no other copy, so the device keeps it.+ const GfxContent content = mesh.recovery == MeshRecovery::SourceReplayable+ ? toGfxContent(ResourceContent::Mesh)+ : GfxContent::retained();+ const VertexBufferHandle vertices = createVertexBuffer(content, vertexBytes);+ const IndexBufferHandle indices_handle = createIndexBuffer(content, indices);const VertexBuffer* vb = getVertexBuffer(vertices);const IndexBuffer* ib = getIndexBuffer(indices_handle);const VertexLayoutHandle layoutHandle = device_->createVertexLayout(layout);@@ -598,7 +591,6 @@ bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpmesh.indexBuffer = ib->handle();mesh.layout = layoutHandle;mesh.indexCount = static_cast<u32>(indices.size());- mesh.realizationGeneration = device_->deviceGeneration();mesh.hasNormals = hasNormals;mesh.hasLightmapUV = lightmapped;mesh.localMin = localMin;@@ -619,7 +611,7 @@ bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpmesh.morphTargetCount = 0;mesh.morphHasNormals = false;if (morph.targetCount > 0 && !morph.deltas.empty()) {- mesh.morphTexture = createMorphTexture(morph, mesh.vertexCount);+ mesh.morphTexture = createMorphTexture(content, morph, mesh.vertexCount);if (mesh.morphTexture != esengine::TextureHandle::Invalid) {mesh.morphTargetCount = morph.targetCount;mesh.morphHasNormals = morph.hasNormals;@@ -637,7 +629,7 @@ bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSp* device guarantees. Half precision because a delta is an offset off a* coordinate the vertex already carries at full precision.*/-esengine::TextureHandle ResourceManager::createMorphTexture(const MeshMorphSource& morph,+esengine::TextureHandle ResourceManager::createMorphTexture(GfxContent content, const MeshMorphSource& morph,u32 vertexCount) {if (!device_ || vertexCount == 0) return esengine::TextureHandle::Invalid;const u32 perVertex = morph.hasNormals ? 2u : 1u;@@ -679,7 +671,7 @@ esengine::TextureHandle ResourceManager::createMorphTexture(const MeshMorphSourcdesc.wrapS = TextureWrap::ClampToEdge;desc.wrapT = TextureWrap::ClampToEdge;desc.mipmaps = false;- return device_->createTexture(desc, pixels.data());+ return device_->createTexture(desc, content, pixels.data());}MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,@@ -688,11 +680,11 @@ MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32>MeshRecovery recovery, ConstSpan<f32> inverseBind,const MeshMorphSource& morph) {auto mesh = makeUnique<Mesh>();+ mesh->recovery = recovery;if (!realizeMesh(*mesh, vertexBytes, indices, channels, vertexStride,localMin, localMax, inverseBind, morph)) {return MeshHandle();}- mesh->recovery = recovery;return meshes_.add(std::move(mesh));}@@ -719,16 +711,6 @@ bool ResourceManager::rematerializeMesh(MeshHandle target, ConstSpan<u8> vertexBtarget.id());return false;}-- // Acknowledged only now. The debt is cleared by a rebuild that WORKED, never- // by the attempt — a handle dropped on failure is a hole nothing reports.- for (usize i = 0; i < awaitingRematerialization_.size(); ++i) {- if (awaitingRematerialization_[i] == target) {- awaitingRematerialization_[i] = awaitingRematerialization_.back();- awaitingRematerialization_.pop_back();- break;- }- }return true;}@@ -740,44 +722,24 @@ const Mesh* ResourceManager::getMesh(MeshHandle handle) const {return meshes_.get(handle);}-u32 ResourceManager::invalidateGpuMeshes() {- awaitingRematerialization_.clear();- meshes_lost_non_recoverable_ = 0;- meshes_.forEachAlive([&](MeshHandle handle, Mesh& mesh) {- // Abandoned, never deleted: the GPU objects went with the device, so the- // records are told to forget them rather than ask a dead device to free- // ids it no longer has.- if (auto* vb = vertexBuffers_.get(mesh.vertices)) vb->abandonGpuBuffer();- if (auto* ib = indexBuffers_.get(mesh.indices)) ib->abandonGpuBuffer();- mesh.vertexBuffer = BufferHandle::Invalid;- mesh.indexBuffer = BufferHandle::Invalid;- mesh.layout = VertexLayoutHandle::Invalid;- // Forgotten for the same reason, and the COUNT with it: a mesh that still- // claimed targets would be drawn morphed against a texture that is gone.- mesh.morphTexture = esengine::TextureHandle::Invalid;- mesh.morphTargetCount = 0;-- if (mesh.recovery == MeshRecovery::SourceReplayable) {- awaitingRematerialization_.push_back(handle);- } else {- ++meshes_lost_non_recoverable_;- }- });- ES_LOG_INFO("Device loss: {} mesh(es) awaiting rematerialization, {} host-only mesh(es) gone"- " for good", awaitingRematerialization_.size(), meshes_lost_non_recoverable_);- return static_cast<u32>(awaitingRematerialization_.size());-}-std::vector<ResourceManager::MeshRealization> ResourceManager::meshRealizations() {std::vector<MeshRealization> out;+ const std::vector<GfxOwedContent> owed = device_ ? device_->owedContent() : std::vector<GfxOwedContent>{};meshes_.forEachAlive([&](MeshHandle handle, Mesh& mesh) {- out.push_back({handle.id(), mesh.realizationGeneration, mesh.hasRealization()});+ out.push_back({handle.id(), mesh.hasRealization() && !meshOwed(mesh, owed)});});return out;}std::vector<MeshHandle> ResourceManager::meshesAwaitingRematerialization() const {- return awaitingRematerialization_;+ std::vector<MeshHandle> out;+ if (!device_) return out;+ const std::vector<GfxOwedContent> owed = device_->owedContent();+ if (owed.empty()) return out;+ meshes_.forEachAlive([&](MeshHandle handle, const Mesh& mesh) {+ if (meshOwed(mesh, owed)) out.push_back(handle);+ });+ return out;}void ResourceManager::releaseMesh(MeshHandle handle) {@@ -792,16 +754,6 @@ void ResourceManager::releaseMesh(MeshHandle handle) {device_->deleteTexture(mesh->morphTexture);}meshes_.release(handle.id());-- // A released mesh cannot be owed: the identity the debt named is gone, and a- // rematerialization aimed at it would land on whatever reuses the slot.- for (usize i = 0; i < awaitingRematerialization_.size(); ++i) {- if (awaitingRematerialization_[i] == handle) {- awaitingRematerialization_[i] = awaitingRematerialization_.back();- awaitingRematerialization_.pop_back();- break;- }- }}// =============================================================================@@ -873,9 +825,9 @@ void ResourceManager::releaseProbeVolume(ProbeVolumeHandle handle) {// Index Buffer Resources// =============================================================================-IndexBufferHandle ResourceManager::createIndexBuffer(ConstSpan<u32> indices) {+IndexBufferHandle ResourceManager::createIndexBuffer(GfxContent content, ConstSpan<u32> indices) {if (!device_) return {};- auto buffer = IndexBuffer::create(*device_, indices.data(), static_cast<u32>(indices.size()));+ auto buffer = IndexBuffer::create(*device_, content, indices.data(), static_cast<u32>(indices.size()));if (!buffer) {ES_LOG_ERROR("Failed to create index buffer (u32)");return IndexBufferHandle();@@ -883,9 +835,9 @@ IndexBufferHandle ResourceManager::createIndexBuffer(ConstSpan<u32> indices) {return indexBuffers_.add(std::move(buffer));}-IndexBufferHandle ResourceManager::createIndexBuffer(ConstSpan<u16> indices) {+IndexBufferHandle ResourceManager::createIndexBuffer(GfxContent content, ConstSpan<u16> indices) {if (!device_) return {};- auto buffer = IndexBuffer::create(*device_, indices.data(), static_cast<u32>(indices.size()));+ auto buffer = IndexBuffer::create(*device_, content, indices.data(), static_cast<u32>(indices.size()));if (!buffer) {ES_LOG_ERROR("Failed to create index buffer (u16)");return IndexBufferHandle();diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hppindex 03eee8e15..2f36af2f3 100644--- a/src/esengine/resource/ResourceManager.hpp+++ b/src/esengine/resource/ResourceManager.hpp@@ -42,6 +42,23 @@ namespace esengine::resource {enum class ShaderTargetLanguage : u8; // ShaderParser.hpp+/**+ * @brief Who refills a resource's GPU content after a device loss.+ * @details Numbered for the host boundary, where a texture's creator states it:+ * only the creator knows whether it can make the pixels again.+ */+enum class ResourceContent : u32 {+ Transient = 0, ///< Rewritten by its owner before every use (a video frame).+ Retained = 1, ///< The device keeps the bytes (a glyph page).+ Asset = 2, ///< The asset layer loads it again from its path.+ Canvas = 3, ///< Redrawn from the canvas it mirrors.+ Video = 4, ///< Refilled by the next decoded frame.+ Mesh = 5, ///< Geometry the asset layer replays (MeshRecovery::SourceReplayable).+};++/** @brief The device's policy for a content code; unknown codes are Asset, the one that asks. */+GfxContent toGfxContent(ResourceContent content);+// =============================================================================// Resource Manager Statistics// =============================================================================@@ -214,7 +231,7 @@ public:* @param spec Texture creation parameters* @return Handle to the texture, or invalid handle on failure*/- TextureHandle createTexture(const TextureSpecification& spec);+ TextureHandle createTexture(ResourceContent content, const TextureSpecification& spec);/*** @brief Creates a texture from pixel data@@ -224,7 +241,7 @@ public:* @param format Pixel format (default RGBA8)* @return Handle to the texture, or invalid handle on failure*/- TextureHandle createTexture(u32 width, u32 height, ConstSpan<u8> pixels,+ TextureHandle createTexture(ResourceContent content, u32 width, u32 height, ConstSpan<u8> pixels,TextureFormat format, bool flipY = false);/**@@ -235,8 +252,9 @@ public:* @param mipLevels Mip levels present (1 = base only).* @return Handle to the texture, or invalid handle on failure.*/- TextureHandle createCompressedTexture(u32 width, u32 height, GfxCompressedFormat format,- ConstSpan<u8> data, u32 mipLevels = 1);+ TextureHandle createCompressedTexture(ResourceContent content, u32 width, u32 height,+ GfxCompressedFormat format, ConstSpan<u8> data,+ u32 mipLevels = 1);/*** @brief Loads a texture from file (with caching)@@ -283,7 +301,14 @@ public:* billing them as RGBA8 would waste most of the budget.* @return Handle to the registered texture*/- TextureHandle registerExternalTexture(u32 glTextureId, u32 width, u32 height, usize bytes = 0);+ TextureHandle registerExternalTexture(ResourceContent content, u32 glTextureId, u32 width, u32 height,+ usize bytes = 0);++ /**+ * @brief Names a texture the device holds for another owner (a render target's+ * colour plane) by a resource handle, without taking it over.+ */+ TextureHandle wrapDeviceTexture(::esengine::TextureHandle texture, u32 width, u32 height);/*** @brief Registers a texture with a path for cache lookup@@ -297,50 +322,25 @@ public:// =========================================================================/**- * @brief Points every texture at @p placeholder, keeping all handles valid.- * @details The GPU objects died with the device; the handles did not. They- * are pool indices, and components, materials and fonts all name- * textures by them, so re-uploading behind one is invisible.- * Sampling the placeholder meanwhile renders pale, not garbage.- */- /**- * @brief Re-compiles every shader behind its existing handle.- * @details Shaders keep their sources precisely so this is possible: a- * material's shaderRef and a plugin's handle stay valid, where- * creating NEW shaders would invalidate every one of them.- * @return How many were rebuilt.- */- 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.+ * @brief Moves a freshly loaded texture's pixels behind an owed handle.+ * @details How the asset layer pays: it loads the texture the ordinary way and+ * hands the result over, which leaves @p source empty for its release.+ * @return False if either handle names no live texture.*/- u32 releaseLostGpuShaders();-- void invalidateGpuTextures(::esengine::TextureHandle placeholder);+ bool adoptTextureContent(TextureHandle target, TextureHandle source);- /**- * @brief Re-points an existing handle at a freshly uploaded GPU texture.- * @return False if the handle names no live texture.- */- bool retargetExternalTexture(TextureHandle handle, u32 glTextureId, u32 width, u32 height);+ /** @brief Textures the device is waiting for content for, with who refills them. */+ struct OwedTexture {+ TextureHandle handle;+ ResourceContent content = ResourceContent::Asset;+ };+ std::vector<OwedTexture> texturesAwaitingReupload() const;/**- * @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.+ * @brief Gives up on an owed texture's content: it keeps blank storage.+ * @details For content nothing can bring back; the caller says so in the log.*/- bool adoptTextureContent(TextureHandle target, TextureHandle source);-- /** @brief Texture handles that were invalidated and not yet re-uploaded. */- std::vector<TextureHandle> texturesAwaitingReupload() const;+ void forgoTextureContent(TextureHandle handle);/*** @brief Gets the cached path for a texture@@ -441,14 +441,14 @@ public:* @return Handle to the buffer, or invalid handle on failure*/template<typename T>- VertexBufferHandle createVertexBuffer(ConstSpan<T> data);+ VertexBufferHandle createVertexBuffer(GfxContent content, ConstSpan<T> data);/*** @brief Creates a dynamic vertex buffer* @param sizeBytes Buffer size in bytes* @return Handle to the buffer, or invalid handle on failure*/- VertexBufferHandle createVertexBuffer(u32 sizeBytes);+ VertexBufferHandle createVertexBuffer(GfxContent content, u32 sizeBytes);/*** @brief Uploads geometry that stays on the GPU, drawn from its own buffers.@@ -492,42 +492,19 @@ public:void releaseMesh(MeshHandle handle);/**- * @brief Ends every mesh's GPU realization, keeping every MeshHandle valid.- *- * @details The realization died with the device; the handles did not, so it- * is dropped and the identity stands. A SourceReplayable mesh is- * enqueued; a HostOnly one is COUNTED, since silence there reports- * success over content nothing can bring back.- *- * @return How many meshes are awaiting rematerialization.- */- u32 invalidateGpuMeshes();-- /**- * @brief Meshes whose realization is gone and whose source has not replaced it.- * @details A copy, and only ever emptied by a rematerialization that- * SUCCEEDED: a debt drained by the act of reading it is a debt the- * engine forgets the moment its holder fails to pay.+ * @brief Replayable meshes whose geometry the device is still waiting for.+ * @details Read off the device's ledger, so the list empties exactly when a+ * rematerialization has put the geometry back.*/std::vector<MeshHandle> meshesAwaitingRematerialization() const;- /** @brief Meshes the last loss ended for good, because no source can replay- * them. Never part of the awaiting list, never silently skipped. */- u32 meshesLostNonRecoverable() const { return meshes_lost_non_recoverable_; }-- /** @brief One live mesh's identity told apart from its realization. */+ /** @brief One live mesh and whether its geometry is on the device. */struct MeshRealization {u32 handle = 0;- u64 generation = 0; ///< The device generation the realization belongs to.bool realized = false;};- /**- * @brief Every live mesh, as identity and realization read separately.- * @details The seam a recovery criterion needs. From outside, a mesh that- * came back and a mesh that was replaced by a new one look the same- * — both draw — and only these two numbers tell them apart.- */+ /** @brief Every live mesh, for a recovery criterion to read. */std::vector<MeshRealization> meshRealizations();// =========================================================================@@ -596,14 +573,14 @@ public:* @param indices Span of index data* @return Handle to the buffer, or invalid handle on failure*/- IndexBufferHandle createIndexBuffer(ConstSpan<u32> indices);+ IndexBufferHandle createIndexBuffer(GfxContent content, ConstSpan<u32> indices);/*** @brief Creates an index buffer from 16-bit indices* @param indices Span of index data* @return Handle to the buffer, or invalid handle on failure*/- IndexBufferHandle createIndexBuffer(ConstSpan<u16> indices);+ IndexBufferHandle createIndexBuffer(GfxContent content, ConstSpan<u16> indices);/*** @brief Gets an index buffer by handle@@ -709,9 +686,6 @@ private:ResourcePool<Environment> environments_;ResourcePool<ProbeVolume> probeVolumes_;ResourcePool<text::BitmapFont> fonts_;- /// Handles whose GPU texture died with the device, still showing the- /// placeholder. Empty means the content is whole again.- std::vector<TextureHandle> awaitingReupload_;/** Builds the buffers and layout one mesh is drawn from, replacing whatever* it had. Shared by the mint and the rebuild so the two cannot describe the* same geometry differently. Leaves the mesh untouched when it fails. */@@ -721,10 +695,9 @@ private:ConstSpan<f32> inverseBind, const MeshMorphSource& morph);/** The deltas as a texture the vertex stage fetches from, or an invalid* handle where they do not fit one — see realizeMesh for what that means. */- esengine::TextureHandle createMorphTexture(const MeshMorphSource& morph, u32 vertexCount);+ esengine::TextureHandle createMorphTexture(GfxContent content, const MeshMorphSource& morph,+ u32 vertexCount);- std::vector<MeshHandle> awaitingRematerialization_;- u32 meshes_lost_non_recoverable_ = 0;std::unordered_map<std::string, TextureHandle> guidToTexture_;std::unordered_map<TextureHandle::IdType, TextureMetadata> textureMetadata_;LoaderRegistry loaderRegistry_;@@ -738,8 +711,8 @@ private:// =============================================================================template<typename T>-VertexBufferHandle ResourceManager::createVertexBuffer(ConstSpan<T> data) {- auto buffer = VertexBuffer::create(*device_, data);+VertexBufferHandle ResourceManager::createVertexBuffer(GfxContent content, ConstSpan<T> data) {+ auto buffer = VertexBuffer::create(*device_, content, data);if (!buffer) return VertexBufferHandle();return vertexBuffers_.add(std::move(buffer));}diff --git a/src/esengine/resource/ResourcePool.hpp b/src/esengine/resource/ResourcePool.hppindex a672b2ee0..74b3fb1a2 100644--- a/src/esengine/resource/ResourcePool.hpp+++ b/src/esengine/resource/ResourcePool.hpp@@ -141,8 +141,7 @@ public:/*** @brief Visits every live resource, with the handle naming it.* @details For sweeps that must reach resources by identity rather than by- * path — a device loss invalidates all of them, including the ones- * created from pixels and never given a path.+ * path, including the ones created from pixels and never given one.*/template<typename Fn>void forEachAlive(Fn&& fn) {@@ -153,6 +152,16 @@ public:}}+ template<typename Fn>+ void forEachAlive(Fn&& fn) const {+ for (usize i = 1; i < entries_.size(); ++i) {+ const Entry& entry = entries_[i];+ if (!entry.resource) continue;+ fn(Handle<T>::fromParts(static_cast<u32>(i), entry.generation),+ static_cast<const T&>(*entry.resource));+ }+ }+/*** @brief Gets a resource by handle* @param handle The resource handlediff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex 32fbd1de9..3e7d0ef55 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -160,6 +160,7 @@ add_test(NAME test_resource_pool COMMAND test_resource_pool)# create/uniform/reflect/delete through GfxDevice.add_executable(test_shader_devicerenderer/test_shader_device.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Shader.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/draw/DrawParams.cpp${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp@@ -175,6 +176,7 @@ add_test(NAME test_shader_device COMMAND test_shader_device)# loose uploads for lifted members).add_executable(test_draw_paramsrenderer/test_draw_params.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Shader.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/draw/DrawParams.cpp${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp@@ -284,6 +286,7 @@ add_test(NAME test_hdr_format COMMAND test_hdr_format)# an id, so acquireTextureByPath is the only place that decision is made.add_executable(test_texture_cacheresource/test_texture_cache.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/resource/ResourceManager.cpp${CMAKE_SOURCE_DIR}/src/esengine/resource/ShaderParser.cpp${CMAKE_SOURCE_DIR}/src/esengine/text/BitmapFont.cpp@@ -306,6 +309,7 @@ add_test(NAME test_texture_cache COMMAND test_texture_cache)# asserts is the engine's invalidation and not a model of it.add_executable(test_mesh_recoveryresource/test_mesh_recovery.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/resource/ResourceManager.cpp${CMAKE_SOURCE_DIR}/src/esengine/resource/ShaderParser.cpp${CMAKE_SOURCE_DIR}/src/esengine/text/BitmapFont.cpp@@ -337,6 +341,7 @@ add_test(NAME test_shader_variant COMMAND test_shader_variant)# MockGfxDevice. The harness stubs the (uncalled) stb file loader.add_executable(test_texture_fbrenderer/test_texture_fb.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Texture.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Framebuffer.cpp${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp@@ -352,6 +357,7 @@ add_test(NAME test_texture_fb COMMAND test_texture_fb)# how many physical targets a chain actually costs.add_executable(test_render_graphrenderer/test_render_graph.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/graph/RenderGraph.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/graph/TargetPool.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Texture.cpp@@ -369,6 +375,7 @@ add_test(NAME test_render_graph COMMAND test_render_graph)# upload/attribute-setup/bind/delete route through GfxDevice.add_executable(test_buffer_devicerenderer/test_buffer_device.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Buffer.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/draw/CustomGeometry.cpp${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp@@ -380,6 +387,7 @@ add_test(NAME test_buffer_device COMMAND test_buffer_device)# Header-only, so nothing but Log.cpp is needed to link.add_executable(test_device_lossrenderer/test_device_loss.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Texture.cpp${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp)@@ -394,6 +402,7 @@ if(EMSCRIPTEN)add_executable(test_webgpu_devicerenderer/test_webgpu_device.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/webgpu/WebGPUDevice.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp)target_include_directories(test_webgpu_device PRIVATE@@ -413,6 +422,7 @@ if(EMSCRIPTEN)add_executable(webgpu_bringuprenderer/webgpu_bringup.cpp${CMAKE_SOURCE_DIR}/src/esengine/renderer/webgpu/WebGPUDevice.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp# The twins assemble from the embedded .esshaders (WGSL target).${CMAKE_SOURCE_DIR}/src/esengine/resource/ShaderParser.cpp@@ -467,6 +477,7 @@ add_test(NAME test_boundary_span COMMAND test_boundary_span)# a link error, on every push, for as long as nobody read the C++ job's log.add_executable(test_batch_builderrenderer/test_batch_builder.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp)target_link_libraries(test_batch_builder PRIVATE esengine)target_include_directories(test_batch_builder PRIVATE@@ -479,6 +490,7 @@ target_include_directories(test_batch_builder PRIVATE# only as an empty WebGPU readback; this counts it on a mock device instead.add_executable(test_frame_lifecyclerenderer/test_frame_lifecycle.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp)target_link_libraries(test_frame_lifecycle PRIVATE esengine)target_include_directories(test_frame_lifecycle PRIVATE@@ -492,6 +504,8 @@ add_test(NAME test_batch_builder COMMAND test_batch_builder)# assert the compressed upload + capability-gated RGBA8 fallback. No GL, no emsdk.add_executable(test_compressed_formatrenderer/test_compressed_format.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/GfxDevice.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp)target_include_directories(test_compressed_format PRIVATE ${CMAKE_SOURCE_DIR}/src)add_test(NAME test_compressed_format COMMAND test_compressed_format)diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hppindex ba5a5245e..27c3b1360 100644--- a/tests/renderer/MockGfxDevice.hpp+++ b/tests/renderer/MockGfxDevice.hpp@@ -79,11 +79,6 @@ struct MockGfxDevice final : GfxDevice {int takeReadbackCalls = 0;int discardReadbackCalls = 0;- u32 nextTextureId = 100;- u32 nextBufferId = 200;- u32 nextFramebufferId = 500;- u32 nextVertexLayoutId = 800;- u32 nextPipelineId = 0;u32 nextReadbackId = 900;FramebufferHandle lastReadbackTarget = FramebufferHandle::Default;@@ -107,8 +102,13 @@ struct MockGfxDevice final : GfxDevice {std::vector<u8> lastUpdateData;BufferDesc lastBufferDesc{};bool lastCreateBufferHadData = false;+ std::vector<u8> lastCreateBufferBytes;TextureDesc lastTextureDesc{};bool lastCreateTextureHadPixels = false;+ std::vector<u8> lastCreateTextureBytes;+ /// What a program's block index lookup answers; GL-shaped by default "absent".+ u32 blockIndexAnswer = GFX_INVALID_UNIFORM_BLOCK;+ std::vector<std::pair<u32, u32>> blockBindingLog;TextureHandle lastDeletedTexture = TextureHandle::Invalid;GfxCompressedFormat lastCompressedFormat = GfxCompressedFormat::ETC2_RGBA8;u32 lastCompressedByteLength = 0;@@ -133,60 +133,14 @@ struct MockGfxDevice final : GfxDevice {* path a caller's "leaves it as it found it" promise is only true along. */bool createBufferSucceeds = true;- BufferHandle createBuffer(const BufferDesc& desc, const void* initialData) override {- ++createBufferCalls;- lastBufferDesc = desc;- lastCreateBufferHadData = initialData != nullptr;- if (!createBufferSucceeds) return BufferHandle::Invalid;- return BufferHandle{nextBufferId++};- }- void deleteBuffer(BufferHandle) override { ++deleteBufferCalls; }- void updateBuffer(BufferHandle, u32, const void* data, u32 sizeBytes) override {- ++updateBufferCalls;- lastUpdateData.assign(static_cast<const u8*>(data), static_cast<const u8*>(data) + sizeBytes);- }- void resizeBuffer(BufferHandle, u32, const void*) override { ++resizeBufferCalls; }void setUniformBuffer(u32 slot, BufferHandle buffer) override {++setUniformBufferCalls;lastUniformBufferSlot = slot;lastUniformBuffer = buffer;}-- VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc) override {- ++createVertexLayoutCalls;- lastVertexLayoutDesc = desc;- return VertexLayoutHandle{nextVertexLayoutId++};- }- void deleteVertexLayout(VertexLayoutHandle) override { ++deleteVertexLayoutCalls; }void setVertexBuffer(u32, BufferHandle buffer, u32) override { ++setVertexBufferCalls; lastVbo = buffer; }void setIndexBuffer(BufferHandle buffer) override { ++setIndexBufferCalls; lastIbo = buffer; }- TextureHandle createTexture(const TextureDesc& desc, const void* pixels) override {- ++createTextureCalls;- lastTextureDesc = desc;- lastCreateTextureHadPixels = pixels != nullptr;- return createTextureFails ? TextureHandle::Invalid : TextureHandle{nextTextureId++};- }- TextureHandle createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,- const void*, u32 byteLength, u32 mipLevels) override {- ++createCompressedTextureCalls;- lastTextureDesc = desc;- lastCompressedFormat = format;- lastCompressedByteLength = byteLength;- lastCompressedMipLevels = mipLevels;- return TextureHandle{nextTextureId++};- }- TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc) override {- ++importExternalTextureCalls;- lastTextureDesc = desc;- return TextureHandle{nativeId};- }- void deleteTexture(TextureHandle texture) override { ++deleteTextureCalls; lastDeletedTexture = texture; }- void updateTexture(TextureHandle, i32, i32, u32, u32, const void*, bool) override { ++updateTextureCalls; }- void setTextureParams(TextureHandle, TextureFilter, TextureFilter, TextureWrap, TextureWrap) override {- ++setTextureParamsCalls;- }- void generateMipmaps(TextureHandle) override { ++generateMipmapsCalls; }void bindTexture(u32 unit, TextureHandle texture) override {++bindTextureCalls;bindLog.push_back({unit, texture});@@ -203,36 +157,7 @@ struct MockGfxDevice final : GfxDevice {/// Answers as GL does; a test that cares sets it.bool originTopLeft = false;bool textureOriginTopLeft() const override { return originTopLeft; }- ShaderHandle createProgram(const GfxShaderSource& source, const GfxAttribBinding*, u32,- std::string*, GfxShaderStage* stage) override {- ++createProgramCalls;- lastShaderLanguage = source.language;- if (stage) *stage = GfxShaderStage::None;- return ShaderHandle{1}; // pretend link succeeds, program 1- }- void deleteProgram(ShaderHandle) override { ++deleteProgramCalls; }- void useProgram(ShaderHandle program) override { ++useProgramCalls; lastProgram = program; }- i32 getUniformLocation(ShaderHandle, const char*) override { return 0; }- i32 getAttribLocation(ShaderHandle, const char*) override { return 0; }- void setUniform1i(i32 loc, i32 v) override { ++setUniform1iCalls; lastUniform1iLoc = loc; lastUniform1iVal = v; }- void setUniform1f(i32, f32) override { ++setUniform1fCalls; }- void setUniform2f(i32, f32, f32) override {}- void setUniform3f(i32, f32, f32, f32) override {}- void setUniform4f(i32, f32, f32, f32, f32) override { ++setUniform4fCalls; }- void setUniformMat3(i32, const f32*) override {}- void setUniformMat4(i32, const f32*) override {}- std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle) override { ++getActiveUniformsCalls; return {}; }-- u32 getUniformBlockIndex(ShaderHandle, const char*) override { return GFX_INVALID_UNIFORM_BLOCK; }- void uniformBlockBinding(ShaderHandle, u32, u32) override {}-- PipelineHandle createPipeline(const PipelineDesc& desc) override {- lastPipelineDesc = desc;- return static_cast<PipelineHandle>(++nextPipelineId);- }- void setPipeline(PipelineHandle) override { ++setPipelineCalls; }void setStencilReference(i32) override {}- void invalidatePipelineCache() override {}void drawElements(u32 indexCount, GfxDataType, u32 byteOffset) override {++drawElementsCalls;@@ -246,12 +171,6 @@ struct MockGfxDevice final : GfxDevice {lastDrawInstanceCount = instanceCount;}- FramebufferHandle createFramebuffer(const FramebufferDesc& desc) override {- ++createFramebufferCalls;- lastFramebufferDesc = desc;- return FramebufferHandle{nextFramebufferId++};- }- void deleteFramebuffer(FramebufferHandle) override { ++deleteFramebufferCalls; }void beginRenderPass(const RenderPassDesc& desc) override {++beginRenderPassCalls;lastPassDesc = desc;@@ -276,7 +195,6 @@ struct MockGfxDevice final : GfxDevice {}void discardReadback(ReadbackHandle) override { ++discardReadbackCalls; }- u32 createTimerQuery() override { return 0; } // report "no GPU timing" like a bare backendvoid beginTimerQuery(u32) override {}void endTimerQuery() override {}bool timerDisjoint() override { return false; }@@ -286,6 +204,109 @@ struct MockGfxDevice final : GfxDevice {u32 getError() override { return 0; }std::string getString(GfxStringName) override { return {}; }i32 getInt(GfxIntParam) override { return 16; }++protected:+ bool backendCreateBuffer(u32, const BufferDesc& desc, const void* data) override {+ ++createBufferCalls;+ lastBufferDesc = desc;+ lastCreateBufferHadData = data != nullptr;+ if (data) {+ lastCreateBufferBytes.assign(static_cast<const u8*>(data), static_cast<const u8*>(data) + desc.size);+ } else {+ lastCreateBufferBytes.clear();+ }+ return createBufferSucceeds;+ }+ void backendDeleteBuffer(u32) override { ++deleteBufferCalls; }+ void backendUpdateBuffer(u32, u32, const void* data, u32 sizeBytes) override {+ ++updateBufferCalls;+ lastUpdateData.assign(static_cast<const u8*>(data), static_cast<const u8*>(data) + sizeBytes);+ }+ void backendResizeBuffer(u32, const BufferDesc&, const void*) override { ++resizeBufferCalls; }++ bool backendCreateTexture(u32, const TextureDesc& desc, const void* pixels) override {+ ++createTextureCalls;+ lastTextureDesc = desc;+ lastCreateTextureHadPixels = pixels != nullptr;+ if (pixels) {+ const usize bytes = static_cast<usize>(desc.width) * desc.height * gfxBytesPerPixel(desc.format);+ lastCreateTextureBytes.assign(static_cast<const u8*>(pixels), static_cast<const u8*>(pixels) + bytes);+ } else {+ lastCreateTextureBytes.clear();+ }+ return !createTextureFails;+ }+ bool backendCreateCompressedTexture(u32, const TextureDesc& desc, GfxCompressedFormat format,+ const void*, u32 byteLength, u32 mipLevels) override {+ ++createCompressedTextureCalls;+ lastTextureDesc = desc;+ lastCompressedFormat = format;+ lastCompressedByteLength = byteLength;+ lastCompressedMipLevels = mipLevels;+ return true;+ }+ bool backendAdoptTexture(u32, u32 nativeId, const TextureDesc& desc) override {+ ++importExternalTextureCalls;+ lastTextureDesc = desc;+ return nativeId != 0;+ }+ void backendDeleteTexture(u32 id) override { ++deleteTextureCalls; lastDeletedTexture = TextureHandle{id}; }+ void backendMoveTexture(u32, u32) override {}+ void backendUpdateTexture(u32, i32, i32, u32, u32, const void*, bool) override { ++updateTextureCalls; }+ void backendSetTextureParams(u32, const TextureDesc&) override { ++setTextureParamsCalls; }+ void backendGenerateMipmaps(u32) override { ++generateMipmapsCalls; }++ bool backendCreateProgram(u32, const GfxShaderSource& source, const GfxAttribBinding*, u32,+ std::string*, GfxShaderStage* stage) override {+ ++createProgramCalls;+ lastShaderLanguage = source.language;+ if (stage) *stage = GfxShaderStage::None;+ return true;+ }+ void backendDeleteProgram(u32) override { ++deleteProgramCalls; }+ void backendUseProgram(u32 id) override { ++useProgramCalls; lastProgram = ShaderHandle{id}; }+ i32 backendUniformLocation(u32, const char*) override { return 0; }+ i32 backendAttribLocation(u32, const char*) override { return 0; }+ void backendSetUniform(i32 location, const GfxUniformValue& value) override {+ switch (value.type) {+ case GfxUniformValue::Type::Int:+ ++setUniform1iCalls;+ lastUniform1iLoc = location;+ lastUniform1iVal = value.i;+ break;+ case GfxUniformValue::Type::Float: ++setUniform1fCalls; break;+ case GfxUniformValue::Type::Vec4: ++setUniform4fCalls; break;+ default: break;+ }+ }+ std::vector<GfxUniformInfo> backendActiveUniforms(u32) override { ++getActiveUniformsCalls; return {}; }+ u32 backendUniformBlockIndex(u32, const char*) override { return blockIndexAnswer; }+ void backendUniformBlockBinding(u32, u32 block, u32 binding) override {+ blockBindingLog.push_back({block, binding});+ }++ bool backendAcceptsVertexLayout(const VertexLayoutDesc& desc) override {+ ++createVertexLayoutCalls;+ lastVertexLayoutDesc = desc;+ return true;+ }+ void backendDeleteVertexLayout(u32) override { ++deleteVertexLayoutCalls; }+ void backendSetPipeline(u32, const PipelineDesc& desc) override {+ ++setPipelineCalls;+ lastPipelineDesc = desc;+ }+ void backendInvalidatePipelineCache() override {}++ bool backendCreateFramebuffer(u32, const FramebufferDesc& desc) override {+ ++createFramebufferCalls;+ lastFramebufferDesc = desc;+ return true;+ }+ void backendDeleteFramebuffer(u32) override { ++deleteFramebufferCalls; }++ // No GPU timing, like a bare backend.+ bool backendCreateTimerQuery(u32) override { return false; }+ u32 backendReadbackCount() const override { return 0; }};} // namespace esenginediff --git a/tests/renderer/test_buffer_device.cpp b/tests/renderer/test_buffer_device.cppindex d58c07ce1..e7f171136 100644--- a/tests/renderer/test_buffer_device.cpp+++ b/tests/renderer/test_buffer_device.cpp@@ -26,13 +26,13 @@ int main() {MockGfxDevice d;float verts[] = { 0, 0, 1, 1, 2, 2, 3, 3 };{- auto vbo = VertexBuffer::createRaw(d, verts, sizeof(verts));+ auto vbo = VertexBuffer::createRaw(d, GfxContent::retained(), verts, sizeof(verts));CHECK(vbo != nullptr, "VertexBuffer::createRaw returns a buffer");CHECK(d.createBufferCalls == 1, "createRaw -> device.createBuffer");CHECK(d.lastCreateBufferHadData, "createRaw uploads its initial data at creation");CHECK(d.lastBufferDesc.usage == GfxBufferUsage::Vertex, "createRaw declares Vertex usage");CHECK(d.lastBufferDesc.size == sizeof(verts), "createRaw sizes the buffer to the data");- CHECK(vbo->handle() == BufferHandle{200}, "buffer handle is device-assigned");+ CHECK(vbo->handle() == BufferHandle{1}, "buffer handle is device-assigned");vbo->setDataRaw(verts, sizeof(verts));CHECK(d.updateBufferCalls == 1, "setDataRaw -> device.updateBuffer");}@@ -43,7 +43,7 @@ int main() {{MockGfxDevice d;u32 idx[] = { 0, 1, 2, 2, 3, 0 };- auto ibo = IndexBuffer::create(d, idx, 6);+ auto ibo = IndexBuffer::create(d, GfxContent::retained(), idx, 6);CHECK(ibo != nullptr, "IndexBuffer::create returns a buffer");CHECK(d.createBufferCalls == 1 && d.lastCreateBufferHadData, "create -> device.createBuffer with data");CHECK(d.lastBufferDesc.usage == GfxBufferUsage::Index, "create declares Index usage");diff --git a/tests/renderer/test_compressed_format.cpp b/tests/renderer/test_compressed_format.cppindex 02d6792e0..650b43116 100644--- a/tests/renderer/test_compressed_format.cpp+++ b/tests/renderer/test_compressed_format.cpp@@ -29,9 +29,9 @@ static TextureHandle uploadTexture(GfxDevice& d, u32 w, u32 h,desc.width = w;desc.height = h;if (d.supportsCompressedFormat(fmt)) {- return d.createCompressedTexture(desc, fmt, compressed, compressedLen, 1);+ return d.createCompressedTexture(desc, GfxContent::sourced(2, 0), fmt, compressed, compressedLen, 1);}- return d.createTexture(desc, rgba);+ return d.createTexture(desc, GfxContent::sourced(2, 0), rgba);}int main() {@@ -69,7 +69,7 @@ int main() {TextureDesc desc;desc.width = 32;desc.height = 32;- d.createCompressedTexture(desc, GfxCompressedFormat::ETC2_RGBA8, blocks.data(), 512, 1);+ d.createCompressedTexture(desc, GfxContent::sourced(2, 0), GfxCompressedFormat::ETC2_RGBA8, blocks.data(), 512, 1);CHECK(d.createCompressedTextureCalls == 1, "ETC2_RGBA8 routes through device");CHECK(d.lastCompressedFormat == GfxCompressedFormat::ETC2_RGBA8, "ETC2 format forwarded");CHECK(d.lastCompressedByteLength == 512, "ETC2 byte length forwarded");diff --git a/tests/renderer/test_device_loss.cpp b/tests/renderer/test_device_loss.cppindex eabeab917..7ff2b3681 100644--- a/tests/renderer/test_device_loss.cpp+++ b/tests/renderer/test_device_loss.cpp@@ -1,12 +1,10 @@-// Device loss: the state machine every backend shares.-//-// Under test is that a lost device cannot be half-alive: the frame stops opening-// and the report names the GPU. Per-backend guards: test_webgpu_device.cpp.+// Device loss: a lost device cannot be half-alive, every handle survives the loss,+// each content policy comes back as promised, and the device turns Live exactly+// when nothing is owed. Per-backend guards: test_webgpu_device.cpp.#include "MockGfxDevice.hpp"#include "esengine/renderer/rhi/GfxEnums.hpp"#include "esengine/renderer/rhi/Texture.hpp"-#include "esengine/resource/ResourcePool.hpp"#include <cstdio>#include <string>@@ -95,26 +93,194 @@ int main() {"giving up does not overwrite why it was lost");}- // --- Recovery: usable before it is whole ---+ // --- A recovery with nothing owed is whole at once ---{MockGfxDevice d;+ const std::vector<u8> bytes(16, 7);+ const BufferHandle kept = d.createBuffer({GfxBufferUsage::Uniform, 16, true},+ GfxContent::retained(), bytes.data());+ const u64 generation = d.deviceGeneration();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");+ CHECK(d.deviceGeneration() == generation + 1, "a rebuild is a new generation");+ CHECK(d.deviceStatus() == GfxDeviceStatus::Live, "nothing owed: Live straight away");+ CHECK(d.deviceLostInfo() == nullptr, "a whole device reports no loss");+ CHECK(d.identityCaptures == 1, "a rebuilt device can be another GPU, so it is asked again");+ CHECK(d.bufferDesc(kept) != nullptr, "the handle names the same buffer");+ CHECK(d.lastCreateBufferBytes == bytes, "retained bytes are uploaded again");++ CHECK(d.recoverDevice(), "asking again is a no-op that reports usable");+ CHECK(d.recreateCalls == 1, "and does not rebuild twice");+ }++ // --- Sourced content is owed until a whole upload pays it ---+ {+ MockGfxDevice d;+ TextureDesc desc;+ desc.width = 4;+ desc.height = 4;+ const TextureHandle sourced = d.createTexture(desc, GfxContent::sourced(2, 17), nullptr);+ const TextureHandle transient = d.createTexture(desc, GfxContent::transient(), nullptr);+ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");+ d.recoverDevice();++ CHECK(d.deviceStatus() == GfxDeviceStatus::Recovering, "owed content keeps it Recovering");+ CHECK(d.isDeviceUsable() && d.beginDeviceFrame(), "a Recovering device draws meanwhile");+ const auto owed = d.owedContent();+ CHECK(owed.size() == 1 && owed[0].id == static_cast<u32>(sourced),+ "the ledger holds the sourced texture and not the transient one");+ CHECK(owed.size() == 1 && owed[0].provider == 2 && owed[0].key == 17,+ "the entry names its provider and key");+ CHECK(d.textureDesc(transient) != nullptr, "the transient texture came back as storage");++ const std::vector<u8> half(2 * 4 * 4, 1);+ d.updateTexture(sourced, 0, 0, 2, 4, half.data(), false);+ CHECK(d.deviceStatus() == GfxDeviceStatus::Recovering, "a partial upload pays nothing");++ const std::vector<u8> whole(4 * 4 * 4, 1);+ d.updateTexture(sourced, 0, 0, 4, 4, whole.data(), false);+ CHECK(d.owedContent().empty(), "a whole upload pays the debt");+ CHECK(d.deviceStatus() == GfxDeviceStatus::Live, "and the device turns Live by itself");+ }++ // --- Forgoing and deleting settle a debt nobody will pay ---+ {+ MockGfxDevice d;+ TextureDesc desc;+ desc.width = 2;+ desc.height = 2;+ d.createTexture(desc, GfxContent::sourced(3, 0), nullptr);+ const TextureHandle deleted = d.createTexture(desc, GfxContent::sourced(4, 0), nullptr);+ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");+ d.recoverDevice();++ CHECK(d.owedContent().size() == 2, "both are owed");+ d.deleteTexture(deleted);+ CHECK(d.owedContent().size() == 1, "a deleted texture owes nothing");+ d.forgoContent(d.owedContent()[0]);+ CHECK(d.deviceStatus() == GfxDeviceStatus::Live, "a forgone debt settles recovery");+ }++ // --- Every kind of object comes back behind the handle it had ---+ {+ MockGfxDevice d;+ const BufferHandle vertices = d.createBuffer({GfxBufferUsage::Vertex, 8, true},+ GfxContent::transient(), nullptr);+ TextureDesc desc;+ desc.width = 8;+ desc.height = 8;+ const TextureHandle color = d.createTexture(desc, GfxContent::transient(), nullptr);+ const FramebufferHandle target = d.createFramebuffer({color, TextureHandle::Invalid});+ const ShaderHandle program = d.createProgram({GfxShaderLanguage::GLSL_ES300, "vs", "fs"},+ nullptr, 0, nullptr, nullptr);+ const GfxLiveObjects before = d.liveObjects();+ const int buffersMade = d.createBufferCalls;+ const int texturesMade = d.createTextureCalls;+ const int framebuffersMade = d.createFramebufferCalls;+ const int programsMade = d.createProgramCalls;++ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");+ d.recoverDevice();++ CHECK(d.bufferDesc(vertices) && d.textureDesc(color) && d.framebufferDesc(target),+ "buffer, texture and framebuffer handles still resolve");+ CHECK(d.createBufferCalls == buffersMade + 1 && d.createTextureCalls == texturesMade + 1+ && d.createFramebufferCalls == framebuffersMade + 1+ && d.createProgramCalls == programsMade + 1,+ "each was built once more on the new device");+ CHECK(!d.lastCreateBufferHadData, "transient storage comes back without contents");+ const GfxLiveObjects after = d.liveObjects();+ CHECK(after.buffers == before.buffers && after.textures == before.textures+ && after.programs == before.programs && after.renderTargets == before.renderTargets,+ "a recovery adds no objects");+ (void)program;+ }++ // --- A program's state is replayed after the relink ---+ {+ MockGfxDevice d;+ d.blockIndexAnswer = 3;+ const ShaderHandle program = d.createProgram({GfxShaderLanguage::GLSL_ES300, "vs", "fs"},+ nullptr, 0, nullptr, nullptr);+ d.useProgram(program);+ const i32 sampler = d.getUniformLocation(program, "u_texture");+ d.setUniform1i(sampler, 5);+ d.uniformBlockBinding(program, d.getUniformBlockIndex(program, "FrameConstants"), 2);+ const int intsSet = d.setUniform1iCalls;+ d.blockBindingLog.clear();++ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");+ d.recoverDevice();++ CHECK(d.setUniform1iCalls == intsSet + 1 && d.lastUniform1iVal == 5,+ "the sampler unit is set again on the new program");+ CHECK(d.blockBindingLog.size() == 1 && d.blockBindingLog[0].second == 2,+ "the block binding is replayed");+ CHECK(d.getUniformLocation(program, "u_texture") == sampler,+ "a location handed out stays the location");+ }++ // --- Objects created while lost are realized by the recovery ---+ {+ MockGfxDevice d;+ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");+ const std::vector<u8> bytes(8, 9);+ const int made = d.createBufferCalls;+ const BufferHandle late = d.createBuffer({GfxBufferUsage::Vertex, 8, false},+ GfxContent::transient(), bytes.data());+ CHECK(late != BufferHandle::Invalid, "a lost device still issues a handle");+ CHECK(d.createBufferCalls == made, "and touches no backend");+ d.recoverDevice();+ CHECK(d.createBufferCalls == made + 1 && d.lastCreateBufferBytes == bytes,+ "the recovery builds it with the bytes it was created with");+ }++ // --- Losing the device again mid-recovery starts the transaction over ---+ {+ MockGfxDevice d;+ TextureDesc desc;+ desc.width = 2;+ desc.height = 2;+ const std::vector<u8> pixels(16, 200);+ d.createTexture(desc, GfxContent::sourced(2, 0), nullptr);+ const TextureHandle kept = d.createTexture(desc, GfxContent::retained(), pixels.data());+ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "first");+ d.recoverDevice();+ CHECK(d.deviceStatus() == GfxDeviceStatus::Recovering, "recovering from the first loss");++ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "second");+ CHECK(d.deviceStatus() == GfxDeviceStatus::Lost, "a loss while Recovering is a loss");+ CHECK(d.owedContent().empty(), "nothing is owed by a device that has no storage");+ d.recoverDevice();+ CHECK(d.recreateCalls == 2, "the second loss is rebuilt too");+ CHECK(d.owedContent().size() == 1, "the ledger is counted afresh");+ CHECK(d.textureDesc(kept) != nullptr && d.lastCreateTextureBytes.size() == pixels.size(),+ "retained pixels come back through both losses");+ }++ // --- A provider pays by handing over a texture it loaded ---+ {+ MockGfxDevice d;+ TextureSpecification spec;+ spec.width = 4;+ spec.height = 4;+ spec.format = TextureFormat::RGBA8;+ auto owedTexture = Texture::create(d, GfxContent::sourced(2, 0), spec);+ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");+ d.recoverDevice();+ const TextureHandle handle = owedTexture->handle();++ spec.width = 8;+ auto fresh = Texture::create(d, GfxContent::sourced(2, 0), spec);+ CHECK(owedTexture->adoptContent(*fresh), "the fresh texture's pixels move behind the owed handle");+ CHECK(owedTexture->handle() == handle, "the owed texture keeps its handle");+ CHECK(owedTexture->getWidth() == 8 && d.textureDesc(handle)->width == 8,+ "and takes the size it was loaded at");+ CHECK(fresh->handle() == TextureHandle::Invalid, "the provider's texture is empty afterwards");+ CHECK(d.deviceStatus() == GfxDeviceStatus::Live, "the debt is paid");+ CHECK(d.liveObjects().textures == 1, "one texture, not two");}// --- A recovery that fails leaves it retryable, not half-open ---@@ -132,7 +298,7 @@ int main() {// 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");+ CHECK(d.isDeviceLive(), "and with nothing owed it is whole");}// --- The transitions that must do nothing ---@@ -140,8 +306,6 @@ int main() {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;@@ -151,42 +315,6 @@ int main() {CHECK(dead.deviceStatus() == GfxDeviceStatus::Dead, "it stays Dead");}- // --- The identity that survives the loss ---- //- // The recovery design rests on this: a pool handle names the Texture, not the- // GPU object, so re-uploading behind it is invisible to every holder.- {- MockGfxDevice d;- resource::ResourcePool<Texture> pool;-- auto first = Texture::createFromExternalId(d, 41, 64, 64, TextureFormat::RGBA8);- auto second = Texture::createFromExternalId(d, 42, 32, 32, TextureFormat::RGBA8);- const resource::Handle<Texture> hA = pool.add(std::move(first));- const resource::Handle<Texture> hB = pool.add(std::move(second));- CHECK(pool.get(hA)->handle() == static_cast<TextureHandle>(41u),- "a texture starts on the GPU object it was registered with");-- // A loss: every live texture is swept onto a placeholder.- const auto placeholder = static_cast<TextureHandle>(999u);- int swept = 0;- pool.forEachAlive([&](resource::Handle<Texture>, Texture& texture) {- texture.retarget(placeholder, /*owns=*/false);- ++swept;- });- CHECK(swept == 2, "forEachAlive reaches every live texture, path or no path");- CHECK(pool.get(hA)->handle() == placeholder, "sampling falls back to the placeholder");- CHECK(pool.get(hB)->handle() == placeholder, "for all of them");-- // The re-upload: a NEW GPU object behind the SAME handle.- pool.get(hA)->retarget(static_cast<TextureHandle>(77u), /*owns=*/false);- CHECK(pool.get(hA)->handle() == static_cast<TextureHandle>(77u),- "a re-uploaded texture points at its new GPU object");- CHECK(pool.get(hA) != nullptr && pool.get(hB) != nullptr,- "and both handles still resolve — nothing above had to be told");- CHECK(pool.get(hB)->handle() == placeholder,- "a texture not yet re-uploaded keeps showing the placeholder");- }-std::printf(g_failures ? "\n%d FAILURE(S)\n" : "\nall passed\n", g_failures);return g_failures ? 1 : 0;}diff --git a/tests/renderer/test_draw_params.cpp b/tests/renderer/test_draw_params.cppindex 61baa1897..bf761a96a 100644--- a/tests/renderer/test_draw_params.cpp+++ b/tests/renderer/test_draw_params.cpp@@ -151,6 +151,7 @@ int main() {// compile() already seeded the engine-injected shadow sampler, so this is the// second loose int write rather than the first.const int seeded = d.setUniform1iCalls;+ shader->bind();shader->setUniform("u_texture", 3);CHECK(d.setUniform1iCalls == seeded + 1, "sampler still goes through the loose path");diff --git a/tests/renderer/test_shader_device.cpp b/tests/renderer/test_shader_device.cppindex ffb63f9c2..f84cc8915 100644--- a/tests/renderer/test_shader_device.cpp+++ b/tests/renderer/test_shader_device.cpp@@ -40,6 +40,9 @@ int main() {"compile pins the injected samplers to their texture units");CHECK(d.useProgramCalls == 2, "seeding them binds and unbinds the program once");+ shader->bind();+ CHECK(d.useProgramCalls == 3 && d.lastProgram == ShaderHandle{1}, "bind routes through device.useProgram");+shader->setUniform("u_tex", 3);CHECK(d.setUniform1iCalls == 8, "setUniform(name,int) routes through device.setUniform1i");CHECK(d.lastUniform1iVal == 3, "uniform value forwarded");@@ -47,8 +50,6 @@ int main() {shader->setUniform("u_color", glm::vec4(1, 0, 0, 1));CHECK(d.setUniform4fCalls == 1, "setUniform(name,vec4) routes through device.setUniform4f");- shader->bind();- CHECK(d.useProgramCalls == 3 && d.lastProgram == ShaderHandle{1}, "bind routes through device.useProgram");shader->unbind();CHECK(d.useProgramCalls == 4 && d.lastProgram == ShaderHandle::Invalid,"unbind routes through device.useProgram(Invalid)");diff --git a/tests/renderer/test_texture_fb.cpp b/tests/renderer/test_texture_fb.cppindex 3d08a8811..c696a6727 100644--- a/tests/renderer/test_texture_fb.cpp+++ b/tests/renderer/test_texture_fb.cpp@@ -28,7 +28,7 @@ int main() {TextureSpecification spec;spec.width = 8; spec.height = 8; spec.format = TextureFormat::RGBA8; spec.generateMips = true;{- auto tex = Texture::create(d, spec);+ auto tex = Texture::create(d, GfxContent::transient(), spec);CHECK(tex != nullptr, "Texture::create returns a texture");CHECK(d.createTextureCalls == 1, "create routes through device.createTexture");CHECK(d.lastTextureDesc.width == 8 && d.lastTextureDesc.height == 8,@@ -37,11 +37,11 @@ int main() {"creation descriptor carries the pixel format");CHECK(d.lastTextureDesc.mipmaps, "generateMips is declared in the descriptor");CHECK(!d.lastCreateTextureHadPixels, "empty spec allocates without pixel data");- CHECK(tex->handle() == TextureHandle{100}, "texture handle is device-assigned");+ CHECK(tex->handle() == TextureHandle{1}, "texture handle is device-assigned");tex->bind(2);CHECK(d.bindTextureCalls == 1, "bind routes through device.bindTexture");}- CHECK(d.deleteTextureCalls == 1 && d.lastDeletedTexture == TextureHandle{100},+ CHECK(d.deleteTextureCalls == 1 && d.lastDeletedTexture == TextureHandle{1},"destructor routes through device.deleteTexture");}@@ -49,7 +49,7 @@ int main() {{MockGfxDevice d;std::vector<u8> pixels(2 * 2 * 4, 0xFF);- auto tex = Texture::create(d, 2, 2, pixels, TextureFormat::RGBA8, /*flipY*/ true);+ auto tex = Texture::create(d, GfxContent::retained(), 2, 2, pixels, TextureFormat::RGBA8, /*flipY*/ true);CHECK(tex != nullptr, "Texture::create(pixels) returns a texture");CHECK(d.createTextureCalls == 1 && d.lastCreateTextureHadPixels,"pixels are uploaded with the creation call");@@ -63,7 +63,7 @@ int main() {MockGfxDevice d;TextureSpecification spec;spec.width = 4; spec.height = 4; spec.format = TextureFormat::RGBA8; // needs 4*4*4 = 64 bytes- auto tex = Texture::create(d, spec);+ auto tex = Texture::create(d, GfxContent::transient(), spec);const int before = d.updateTextureCalls;std::vector<u8> tooSmall(16, 0xAB); // 16 < 64tex->setDataRaw(tooSmall.data(), static_cast<u32>(tooSmall.size()));@@ -81,20 +81,28 @@ int main() {d.createTextureFails = true;TextureSpecification spec;spec.width = 8; spec.height = 8; spec.format = TextureFormat::RGBA8;- auto tex = Texture::create(d, spec);+ auto tex = Texture::create(d, GfxContent::transient(), spec);CHECK(tex == nullptr, "create returns null when device.createTexture fails");}- // --- createFromExternalId must NOT delete the externally-owned texture ---- // The external owner frees that id; deleting it here too is a double-free.+ // --- a host-made texture is the device's once imported; a borrowed one is not ---{MockGfxDevice d;{- auto tex = Texture::createFromExternalId(d, 42, 8, 8);- CHECK(tex != nullptr && tex->handle() == TextureHandle{42}, "wrapper holds the external id");+ auto tex = Texture::createFromExternalId(d, GfxContent::sourced(2, 0), 42, 8, 8);+ CHECK(tex != nullptr && tex->handle() != TextureHandle::Invalid, "the import has a device handle");CHECK(d.importExternalTextureCalls == 1, "external id is registered with the device");}- CHECK(d.deleteTextureCalls == 0, "destructor does NOT delete an externally-owned texture");+ CHECK(d.deleteTextureCalls == 1, "destructor deletes an imported texture: the device owns it");++ TextureSpecification spec;+ spec.width = 4; spec.height = 4; spec.format = TextureFormat::RGBA8;+ auto owner = Texture::create(d, GfxContent::transient(), spec);+ {+ auto borrowed = Texture::borrow(d, owner->handle(), 4, 4);+ CHECK(borrowed != nullptr && borrowed->handle() == owner->handle(), "a borrow names the owner's texture");+ }+ CHECK(d.deleteTextureCalls == 1, "destructor does NOT delete a borrowed texture");}// --- an engine-owned texture IS still deleted on destruction ---@@ -102,7 +110,7 @@ int main() {MockGfxDevice d;TextureSpecification spec;spec.width = 4; spec.height = 4; spec.format = TextureFormat::RGBA8;- { auto tex = Texture::create(d, spec); }+ { auto tex = Texture::create(d, GfxContent::transient(), spec); }CHECK(d.deleteTextureCalls == 1, "destructor deletes an engine-owned texture");}diff --git a/tests/renderer/test_webgpu_device.cpp b/tests/renderer/test_webgpu_device.cppindex 61d0b99dc..2f0ff7d28 100644--- a/tests/renderer/test_webgpu_device.cpp+++ b/tests/renderer/test_webgpu_device.cpp@@ -186,7 +186,7 @@ TEST_CASE("pass load-ops: full-target clear is a real load-op, a scoped clear isCHECK(color.a == doctest::Approx(0.5));}-TEST_CASE("a lost device issues no more handles") {+TEST_CASE("a lost device still issues handles, for the recovery to realize") {WebGPUDevice device;device.init();@@ -199,10 +199,11 @@ TEST_CASE("a lost device issues no more handles") {device.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "the host took the context");CHECK(device.deviceStatus() == GfxDeviceStatus::Lost);- // Registering a layout is descriptor-only bookkeeping — it succeeds with no- // GPU device at all, as the case below asserts. So this refusal is the loss- // guard and nothing else.- CHECK(device.createVertexLayout(layout) == VertexLayoutHandle::Invalid);+ // A handle names a record, not a GPU object: what a lost device is asked for+ // is built by the recovery, so nothing above has to hold its creation back.+ const VertexLayoutHandle late = device.createVertexLayout(layout);+ CHECK(late != VertexLayoutHandle::Invalid);+ CHECK(device.vertexLayoutDesc(late) != nullptr);REQUIRE(device.deviceLostInfo() != nullptr);const std::string report = gfxFormatDeviceLost(*device.deviceLostInfo());@@ -219,8 +220,9 @@ TEST_CASE("null-device skeleton: language gate + graceful degradation + bookkeepCHECK(!device.supportsShaderLanguage(GfxShaderLanguage::GLSL_ES300));// GPU-touching creation degrades to Invalid with a log, never UB.- CHECK(device.createBuffer({GfxBufferUsage::Vertex, 256, true}, nullptr) == BufferHandle::Invalid);- CHECK(device.createTexture({}, nullptr) == TextureHandle::Invalid);+ CHECK(device.createBuffer({GfxBufferUsage::Vertex, 256, true}, GfxContent::transient(), nullptr)+ == BufferHandle::Invalid);+ CHECK(device.createTexture({}, GfxContent::transient(), nullptr) == TextureHandle::Invalid);// Descriptor-only bookkeeping works without a device: layouts validate their// attributes against the WGPU format table and round-trip.@@ -233,8 +235,8 @@ TEST_CASE("null-device skeleton: language gate + graceful degradation + bookkeepbatch.attributes[3] = {3, 1, GfxDataType::Float, false, 20, 0};auto layout = device.createVertexLayout(batch);REQUIRE(layout != VertexLayoutHandle::Invalid);- REQUIRE(device.layoutDesc(layout) != nullptr);- CHECK(device.layoutDesc(layout)->strides[0] == 24);+ REQUIRE(device.vertexLayoutDesc(layout) != nullptr);+ CHECK(device.vertexLayoutDesc(layout)->strides[0] == 24);VertexLayoutDesc bad{};bad.attributeCount = 1;diff --git a/tests/renderer/webgpu_bringup.cpp b/tests/renderer/webgpu_bringup.cppindex 9a309864e..8f7bbccf7 100644--- a/tests/renderer/webgpu_bringup.cpp+++ b/tests/renderer/webgpu_bringup.cpp@@ -161,7 +161,7 @@ TextureHandle makeCheckerTexture() {td.format = GfxPixelFormat::RGBA8;td.minFilter = TextureFilter::Nearest;td.magFilter = TextureFilter::Nearest;- return g_device->createTexture(td, pixels);+ return g_device->createTexture(td, GfxContent::retained(), pixels);}} // namespace@@ -183,7 +183,7 @@ int main() {// FrameConstants: identity projection (positions are authored in clip space).const f32 identity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};- g_ubo = device.createBuffer({GfxBufferUsage::Uniform, sizeof(identity), false}, identity);+ g_ubo = device.createBuffer({GfxBufferUsage::Uniform, sizeof(identity), false}, GfxContent::retained(), identity);// --- Shape scene: small circle, top-center (clip y 0.55..0.95).const ShapeVertex shapeVerts[4] = {@@ -193,8 +193,8 @@ int main() {{-0.25f, 0.95f, -1, 1, 1, 0, 1, 1, 0, 100, 100, 0},};const u16 quadIdx[6] = {0, 1, 2, 2, 3, 0};- g_shapeVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(shapeVerts), false}, shapeVerts);- g_ibo6 = device.createBuffer({GfxBufferUsage::Index, sizeof(quadIdx), false}, quadIdx);+ g_shapeVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(shapeVerts), false}, GfxContent::retained(), shapeVerts);+ g_ibo6 = device.createBuffer({GfxBufferUsage::Index, sizeof(quadIdx), false}, GfxContent::retained(), quadIdx);// --- Batch scene: left quad samples slot 0 (checker), right quad slot 1 (green).const u32 white = 0xFFFFFFFFu;@@ -205,8 +205,8 @@ int main() {{ 0.9f, 0.3f, white, 1, 1, 1}, { 0.1f, 0.3f, white, 0, 1, 1},};const u16 batchIdx[12] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4};- g_batchVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(batchVerts), false}, batchVerts);- g_ibo12 = device.createBuffer({GfxBufferUsage::Index, sizeof(batchIdx), false}, batchIdx);+ g_batchVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(batchVerts), false}, GfxContent::retained(), batchVerts);+ g_ibo12 = device.createBuffer({GfxBufferUsage::Index, sizeof(batchIdx), false}, GfxContent::retained(), batchIdx);// --- Stencil scene (SDF rects, shapeType 2 with radius 0): quad 0 = the// mask (top-left), quad 1 = an oversized cyan rect testing INTO the mask,@@ -230,8 +230,8 @@ int main() {stencilVerts[8 + i] = orange[i];}const u16 stencilIdx[18] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8};- g_stencilVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(stencilVerts), false}, stencilVerts);- g_ibo18 = device.createBuffer({GfxBufferUsage::Index, sizeof(stencilIdx), false}, stencilIdx);+ g_stencilVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(stencilVerts), false}, GfxContent::retained(), stencilVerts);+ g_ibo18 = device.createBuffer({GfxBufferUsage::Index, sizeof(stencilIdx), false}, GfxContent::retained(), stencilIdx);g_texChecker = makeCheckerTexture();// The right quad's texture is RENDERED, not uploaded: an offscreen target@@ -240,12 +240,12 @@ int main() {offDesc.width = 4;offDesc.height = 4;offDesc.format = GfxPixelFormat::RGBA8;- g_texOffscreen = device.createTexture(offDesc, nullptr);+ g_texOffscreen = device.createTexture(offDesc, GfxContent::transient(), nullptr);TextureDesc offDepthDesc{};offDepthDesc.width = 4;offDepthDesc.height = 4;offDepthDesc.format = GfxPixelFormat::Depth24Stencil8;- g_texOffscreenDepth = device.createTexture(offDepthDesc, nullptr);+ g_texOffscreenDepth = device.createTexture(offDepthDesc, GfxContent::transient(), nullptr);if (g_texChecker == TextureHandle::Invalid || g_texOffscreen == TextureHandle::Invalid ||g_texOffscreenDepth == TextureHandle::Invalid) {std::printf("BRINGUP_FAIL textures\n");diff --git a/tests/renderer/webgpu_engine_bringup.cpp b/tests/renderer/webgpu_engine_bringup.cppindex 7a433f923..352ef08db 100644--- a/tests/renderer/webgpu_engine_bringup.cpp+++ b/tests/renderer/webgpu_engine_bringup.cpp@@ -224,10 +224,10 @@ bool buildScene(EstellaContext& ctx, ecs::Registry& registry) {255, 0, 0, 255, 0, 0, 255, 255, // row 0: red, blue0, 0, 255, 255, 255, 0, 0, 255, // row 1: blue, red};- auto checkerTex = rm.createTexture(2, 2, ConstSpan<u8>(checker, sizeof(checker)),+ auto checkerTex = rm.createTexture(resource::ResourceContent::Retained, 2, 2, ConstSpan<u8>(checker, sizeof(checker)),TextureFormat::RGBA8);const u8 green[4] = {0, 255, 0, 255};- auto greenTex = rm.createTexture(1, 1, ConstSpan<u8>(green, sizeof(green)),+ auto greenTex = rm.createTexture(resource::ResourceContent::Retained, 1, 1, ConstSpan<u8>(green, sizeof(green)),TextureFormat::RGBA8);if (!checkerTex.isValid() || !greenTex.isValid()) return false;@@ -267,7 +267,7 @@ bool buildScene(EstellaContext& ctx, ecs::Registry& registry) {// the two explicit lights below: white * (0.2 ambient + red point) ≈// (255, 51, 51) at the sprite center on BOTH backends.const u8 white[4] = {255, 255, 255, 255};- auto whiteTex = rm.createTexture(1, 1, ConstSpan<u8>(white, sizeof(white)),+ auto whiteTex = rm.createTexture(resource::ResourceContent::Retained, 1, 1, ConstSpan<u8>(white, sizeof(white)),TextureFormat::RGBA8);if (!whiteTex.isValid()) return false;{diff --git a/tests/resource/test_mesh_recovery.cpp b/tests/resource/test_mesh_recovery.cppindex 1f92176f2..e8940581d 100644--- a/tests/resource/test_mesh_recovery.cpp+++ b/tests/resource/test_mesh_recovery.cpp@@ -1,7 +1,6 @@-// Persistent mesh identity across a device generation.-//-// The REAL ResourceManager.cpp against MockGfxDevice: at the loss the handle-// survives, the realization does not, and every mesh is owed or gone for good.+// The REAL ResourceManager.cpp against MockGfxDevice: a mesh and its buffers survive+// a device loss, replayable geometry is owed until its source puts it back, and+// host-only geometry comes back from the bytes the device kept.#include "../renderer/MockGfxDevice.hpp"#include "esengine/resource/ResourceManager.hpp"@@ -42,10 +41,24 @@ bool owes(const std::vector<resource::MeshHandle>& awaiting, resource::MeshHandlreturn std::find(awaiting.begin(), awaiting.end(), h) != awaiting.end();}+void loseAndRecover(MockGfxDevice& d) {+ d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");+ d.recoverDevice();+}++bool rematerialize(resource::ResourceManager& rm, resource::MeshHandle h, f32 extent) {+ const Vertex verts[3] = {{0, 0, 0, 0, 0}, {extent, 0, 0, 1, 0}, {0, extent, 0, 0, 1}};+ const u32 indices[3] = {0, 1, 2};+ return rm.rematerializeMesh(+ h, ConstSpan<u8>(reinterpret_cast<const u8*>(verts), sizeof(verts)),+ ConstSpan<u32>(indices, 3), ConstSpan<GfxVertexAttribute>(kChannels, 2),+ sizeof(Vertex), glm::vec3(0.0f), glm::vec3(extent));+}+} // namespaceint main() {- // --- The identity survives; the realization does not ---+ // --- The identity and its buffers survive; replayable geometry is owed ---{MockGfxDevice d;resource::ResourceManager rm;@@ -54,51 +67,22 @@ int main() {const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);CHECK(h.isValid(), "a mesh mints a handle");const Mesh* before = rm.getMesh(h);- CHECK(before != nullptr, "and the handle resolves");- CHECK(before->hasRealization(), "a fresh mesh has a GPU realization");- CHECK(before->isDrawable(), "and is drawable");- CHECK(before->indexCount == 3, "with its index count");+ CHECK(before != nullptr && before->isDrawable(), "a fresh mesh is drawable");+ const BufferHandle vbo = before->vertexBuffer;+ CHECK(rm.meshesAwaitingRematerialization().empty(), "a live device owes nothing");- rm.invalidateGpuMeshes();+ loseAndRecover(d);const Mesh* after = rm.getMesh(h);- CHECK(after != nullptr, "the SAME handle still resolves after the loss");- CHECK(after == before, "naming the same record — identity was never re-minted");- CHECK(!after->hasRealization(), "whose realization is gone");- CHECK(!after->isDrawable(), "so the draw path skips it instead of binding a dead buffer");- CHECK(after->vertexBuffer == BufferHandle::Invalid, "the VBO is unavailable");- CHECK(after->indexBuffer == BufferHandle::Invalid, "the EBO is unavailable");- CHECK(after->layout == VertexLayoutHandle::Invalid, "the vertex layout is unavailable");- // Bounds and index count are the identity's, not the realization's: they- // are what culling reads while the geometry is on its way back.- CHECK(after->indexCount == 3, "the index count survives the loss");- CHECK(after->localMax == glm::vec3(1.0f), "and so do the bounds");- }-- // --- The debt is declared, and declared once ---- {- MockGfxDevice d;- resource::ResourceManager rm;- rm.init(d);-- const auto a = makeMesh(rm, MeshRecovery::SourceReplayable);- const auto b = makeMesh(rm, MeshRecovery::SourceReplayable);- CHECK(rm.meshesAwaitingRematerialization().empty(), "a live device owes nothing");-- const u32 owed = rm.invalidateGpuMeshes();- const auto awaiting = rm.meshesAwaitingRematerialization();- CHECK(owed == 2, "the loss reports what it enqueued");- CHECK(awaiting.size() == 2, "both meshes are owed");- CHECK(owes(awaiting, a) && owes(awaiting, b), "by handle, and by the right ones");-- // One loss, one debt: a second sweep of the same event must not double it.- rm.invalidateGpuMeshes();- const auto again = rm.meshesAwaitingRematerialization();- CHECK(again.size() == 2, "a second invalidate does not double the debt");- CHECK(std::count(again.begin(), again.end(), a) == 1, "each handle is owed exactly once");+ CHECK(after == before, "the SAME record — identity was never re-minted");+ CHECK(after->vertexBuffer == vbo, "behind the SAME buffer handle");+ CHECK(owes(rm.meshesAwaitingRematerialization(), h), "whose geometry is owed");+ CHECK(d.deviceStatus() == GfxDeviceStatus::Recovering, "which keeps the device Recovering");+ const auto rows = rm.meshRealizations();+ CHECK(rows.size() == 1 && !rows[0].realized, "and reads as not realized from outside");}- // --- Host-only geometry is counted, never quietly skipped ---+ // --- Host-only geometry comes back from the bytes the device kept ---{MockGfxDevice d;resource::ResourceManager rm;@@ -106,47 +90,12 @@ int main() {const auto asset = makeMesh(rm, MeshRecovery::SourceReplayable);const auto hostOnly = makeMesh(rm, MeshRecovery::HostOnly);+ loseAndRecover(d);- rm.invalidateGpuMeshes();const auto awaiting = rm.meshesAwaitingRematerialization();- CHECK(awaiting.size() == 1, "only the replayable mesh is owed");- CHECK(owes(awaiting, asset), "and it is the asset-backed one");- CHECK(!owes(awaiting, hostOnly), "host-only geometry is not queued for a source it has not got");- CHECK(rm.meshesLostNonRecoverable() == 1, "it is REPORTED as permanently gone");- CHECK(rm.getMesh(hostOnly) != nullptr, "its handle still resolves");- CHECK(!rm.getMesh(hostOnly)->isDrawable(), "and it is undrawable rather than drawing garbage");- }-- // --- A dead device is not asked to free what it already lost ---- {- MockGfxDevice d;- resource::ResourceManager rm;- rm.init(d);- makeMesh(rm, MeshRecovery::SourceReplayable);-- const int deletesBefore = d.deleteBufferCalls;- rm.invalidateGpuMeshes();- CHECK(d.deleteBufferCalls == deletesBefore,- "invalidation deletes no buffer — the objects went with the device");- }-- // --- The generation a realization belongs to is on the record ---- {- MockGfxDevice d;- resource::ResourceManager rm;- rm.init(d);-- const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);- CHECK(rm.getMesh(h)->realizationGeneration == d.deviceGeneration(),- "a mesh records the device generation it was realized on");-- d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");- d.recoverDevice();- CHECK(d.deviceGeneration() == 1, "a rebuilt device is a new generation");- rm.invalidateGpuMeshes();- CHECK(rm.getMesh(h)->realizationGeneration == 0,- "and a mesh not yet rebuilt still carries the OLD one, so nothing can"- " mistake a stale realization for a current one");+ CHECK(awaiting.size() == 1 && owes(awaiting, asset), "only the replayable mesh is owed");+ CHECK(!owes(awaiting, hostOnly), "host-only geometry is not waiting for a source it has not got");+ CHECK(rm.getMesh(hostOnly)->isDrawable(), "and draws: the device put its bytes back");}// --- A released mesh is not owed ---@@ -157,14 +106,14 @@ int main() {const auto keep = makeMesh(rm, MeshRecovery::SourceReplayable);const auto drop = makeMesh(rm, MeshRecovery::SourceReplayable);- rm.invalidateGpuMeshes();+ loseAndRecover(d);CHECK(rm.meshesAwaitingRematerialization().size() == 2, "both are owed to begin with");rm.releaseMesh(drop);const auto awaiting = rm.meshesAwaitingRematerialization();- CHECK(awaiting.size() == 1, "releasing a mesh cancels its debt");- CHECK(owes(awaiting, keep), "leaving the one that is still there");- CHECK(!owes(awaiting, drop), "and not an identity nothing holds any more");+ CHECK(awaiting.size() == 1 && owes(awaiting, keep), "releasing a mesh cancels its debt");+ rm.releaseMesh(keep);+ CHECK(d.deviceStatus() == GfxDeviceStatus::Live, "and with nothing left owed the device is whole");}// --- A mint the GPU refuses hands back nothing, not a mesh that draws nothing ---@@ -188,26 +137,16 @@ int main() {const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);const Mesh* record = rm.getMesh(h);- rm.invalidateGpuMeshes();- CHECK(!record->hasRealization(), "the mesh starts owed and unrealized");-- const Vertex verts[3] = {{0, 0, 0, 0, 0}, {2, 0, 0, 1, 0}, {0, 2, 0, 0, 1}};- const u32 indices[3] = {0, 1, 2};- const bool ok = rm.rematerializeMesh(- h, ConstSpan<u8>(reinterpret_cast<const u8*>(verts), sizeof(verts)),- ConstSpan<u32>(indices, 3), ConstSpan<GfxVertexAttribute>(kChannels, 2),- sizeof(Vertex), glm::vec3(0.0f), glm::vec3(2.0f));+ loseAndRecover(d);- CHECK(ok, "a replayed source rematerializes");+ CHECK(rematerialize(rm, h, 2.0f), "a replayed source rematerializes");CHECK(rm.getMesh(h) == record, "into the SAME record — no second handle was minted");- CHECK(record->hasRealization(), "which has a realization again");- CHECK(record->isDrawable(), "and is drawable again");- CHECK(record->vertexBuffer != BufferHandle::Invalid, "on a new VBO");- CHECK(record->indexBuffer != BufferHandle::Invalid, "a new EBO");- CHECK(record->layout != VertexLayoutHandle::Invalid, "and a new vertex layout");+ CHECK(record->isDrawable(), "which is drawable");CHECK(record->localMax == glm::vec3(2.0f), "carrying the geometry that was replayed");- CHECK(rm.meshesAwaitingRematerialization().empty(),- "and the debt is acknowledged, because the rebuild worked");+ CHECK(rm.meshesAwaitingRematerialization().empty(), "and the debt is paid");+ CHECK(d.deviceStatus() == GfxDeviceStatus::Live, "so the device is whole again");+ const auto rows = rm.meshRealizations();+ CHECK(rows.size() == 1 && rows[0].realized, "and the mesh reads as realized");}// --- A rebuild that fails leaves the debt standing ---@@ -217,9 +156,8 @@ int main() {rm.init(d);const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);- rm.invalidateGpuMeshes();+ loseAndRecover(d);- // Empty geometry: the decode produced nothing usable.const bool ok = rm.rematerializeMesh(h, ConstSpan<u8>(), ConstSpan<u32>(), ConstSpan<GfxVertexAttribute>(kChannels, 2),sizeof(Vertex), glm::vec3(0.0f), glm::vec3(1.0f));@@ -227,7 +165,6 @@ int main() {CHECK(!ok, "a rebuild that cannot happen reports failure");CHECK(owes(rm.meshesAwaitingRematerialization(), h),"and the handle is STILL owed — a debt dropped on failure is a hole nothing reports");- CHECK(!rm.getMesh(h)->hasRealization(), "the mesh stays unrealized rather than half-built");}// --- A failed rebuild leaves a LIVE mesh exactly as it found it ---@@ -240,7 +177,6 @@ int main() {const Mesh* record = rm.getMesh(h);const BufferHandle vbo = record->vertexBuffer;const BufferHandle ebo = record->indexBuffer;- CHECK(record->hasRealization(), "the mesh is realized to begin with");const bool empty = rm.rematerializeMesh(h, ConstSpan<u8>(), ConstSpan<u32>(),ConstSpan<GfxVertexAttribute>(kChannels, 2),@@ -251,18 +187,11 @@ int main() {// The other way it fails, and the one the promise is actually about: the// geometry is fine and the GPU cannot allocate for it.d.createBufferSucceeds = false;- const Vertex verts[3] = {{0, 0, 0, 0, 0}, {1, 0, 0, 1, 0}, {0, 1, 0, 0, 1}};- const u32 indices[3] = {0, 1, 2};- const bool oom = rm.rematerializeMesh(- h, ConstSpan<u8>(reinterpret_cast<const u8*>(verts), sizeof(verts)),- ConstSpan<u32>(indices, 3), ConstSpan<GfxVertexAttribute>(kChannels, 2),- sizeof(Vertex), glm::vec3(0.0f), glm::vec3(1.0f));- CHECK(!oom, "a rebuild the GPU cannot allocate for fails");+ CHECK(!rematerialize(rm, h, 1.0f), "a rebuild the GPU cannot allocate for fails");CHECK(record->hasRealization(),"and the mesh KEEPS the realization it had — a rebuild that cannot finish must"" not take away the geometry that was already drawing");- CHECK(record->vertexBuffer == vbo, "the same VBO");- CHECK(record->indexBuffer == ebo, "and the same EBO");+ CHECK(record->vertexBuffer == vbo && record->indexBuffer == ebo, "the same buffers");}// --- Host-only geometry cannot be rematerialized into ---@@ -272,40 +201,9 @@ int main() {rm.init(d);const auto h = makeMesh(rm, MeshRecovery::HostOnly);- rm.invalidateGpuMeshes();-- const Vertex verts[3] = {{0, 0, 0, 0, 0}, {1, 0, 0, 1, 0}, {0, 1, 0, 0, 1}};- const u32 indices[3] = {0, 1, 2};- const bool ok = rm.rematerializeMesh(- h, ConstSpan<u8>(reinterpret_cast<const u8*>(verts), sizeof(verts)),- ConstSpan<u32>(indices, 3), ConstSpan<GfxVertexAttribute>(kChannels, 2),- sizeof(Vertex), glm::vec3(0.0f), glm::vec3(1.0f));- CHECK(!ok, "a host-only mesh refuses geometry it never had a source for");- CHECK(!rm.getMesh(h)->hasRealization(), "and stays gone, as its producer declared");- }-- // --- A rematerialized mesh belongs to the CURRENT generation ---- {- MockGfxDevice d;- resource::ResourceManager rm;- rm.init(d);-- const auto h = makeMesh(rm, MeshRecovery::SourceReplayable);- CHECK(rm.getMesh(h)->realizationGeneration == 0, "minted on generation 0");-- d.notifyDeviceLost(GfxDeviceLostReason::ContextLost, "gone");- d.recoverDevice();- rm.invalidateGpuMeshes();-- const Vertex verts[3] = {{0, 0, 0, 0, 0}, {1, 0, 0, 1, 0}, {0, 1, 0, 0, 1}};- const u32 indices[3] = {0, 1, 2};- rm.rematerializeMesh(- h, ConstSpan<u8>(reinterpret_cast<const u8*>(verts), sizeof(verts)),- ConstSpan<u32>(indices, 3), ConstSpan<GfxVertexAttribute>(kChannels, 2),- sizeof(Vertex), glm::vec3(0.0f), glm::vec3(1.0f));- CHECK(rm.getMesh(h)->realizationGeneration == 1,- "a rebuilt mesh records the generation it was rebuilt ON, so a stale realization"- " cannot pass for a current one");+ loseAndRecover(d);+ CHECK(!rematerialize(rm, h, 1.0f), "a host-only mesh refuses geometry it never had a source for");+ CHECK(rm.getMesh(h)->isDrawable(), "and keeps the geometry the device restored");}std::printf(g_failures ? "\n%d FAILURE(S)\n" : "\nall passed\n", g_failures);diff --git a/tests/resource/test_texture_cache.cpp b/tests/resource/test_texture_cache.cppindex 97d398398..2093116d7 100644--- a/tests/resource/test_texture_cache.cpp+++ b/tests/resource/test_texture_cache.cpp@@ -24,7 +24,7 @@ int main() {resource::ResourceManager rm;rm.init(d);- const auto handle = rm.registerExternalTexture(7, 4, 4);+ const auto handle = rm.registerExternalTexture(resource::ResourceContent::Asset, 7, 4, 4);CHECK(handle.isValid(), "an external texture registers");rm.registerTextureWithPath(handle, "a.png");@@ -47,7 +47,7 @@ int main() {resource::ResourceManager rm;rm.init(d);- const auto handle = rm.registerExternalTexture(9, 2, 2);+ const auto handle = rm.registerExternalTexture(resource::ResourceContent::Asset, 9, 2, 2);rm.registerTextureWithPath(handle, "b.png");rm.acquireTextureByPath("b.png");rm.acquireTextureByPath("b.png");diff --git a/tools/check-render-scenes.mjs b/tools/check-render-scenes.mjsindex 3b2d03e8a..5a4263a34 100644--- a/tools/check-render-scenes.mjs+++ b/tools/check-render-scenes.mjs@@ -48,7 +48,9 @@ for (const s of SCENES) {// column that behaves unlike its neighbours on a grid is not a pixel colour.// A COUNT is an expectation too, and the one a point probe cannot make: how// much of a colour the frame holds does not depend on where a font put it.+ // A ROUNDTRIP compares every pixel against the frame from before the loss.const asserts = s.env.ESTELLA_VERIFY_EXPECT || s.env.ESTELLA_VERIFY_COUNT+ || s.env.ESTELLA_VERIFY_DEVICE_LOSS === 'roundtrip'|| s.env.ESTELLA_VERIFY_SEAM|| s.env.ESTELLA_VERIFY_GRID || s.env.ESTELLA_VERIFY_PREVIEW|| s.env.ESTELLA_VERIFY_MESH_PREVIEW || s.env.ESTELLA_VERIFY_DEPTH_LAYERSdiff --git a/tools/meshProducers.mjs b/tools/meshProducers.mjsindex 9a019481c..636f59eb1 100644--- a/tools/meshProducers.mjs+++ b/tools/meshProducers.mjs@@ -4,21 +4,14 @@* @file meshProducers.mjs — every path that can mint a persistent MeshHandle,* and what each one promises about surviving a device generation.*- * A MeshHandle is a LOGICAL resource identity. The VBO, the EBO and the vertex- * layout it points at are that identity's realization on one device generation,- * and a lost device takes all three; recovery replaces them underneath the same- * handle, so nothing that stored one ever hears about it.+ * A MeshHandle and the buffers behind it survive a device loss; the device+ * rebuilds the buffers. What it cannot answer for itself is where the geometry+ * comes back FROM, and only whoever minted the handle knows — so a producer says,+ * in advance, here: a source to replay, or bytes the device keeps.*- * Which leaves the only question recovery cannot answer for itself: where does- * the geometry come back FROM? Only whoever minted the handle knows, so only a- * producer can say — in advance, here.- *- * The distinction this table exists to keep: the ABSENCE of a recorded source is- * a fact about a handle, never a recovery policy. A production mesh whose- * provenance went missing is a broken contract and has to be reported as one; it- * is not, and must never be quietly downgraded into, a mesh that was never- * recoverable. Only a producer declared `host-only-non-recoverable` below is- * allowed to have no way back.+ * The ABSENCE of a recorded source is a fact about a handle, never a recovery+ * policy: a production mesh whose provenance went missing is a broken contract,+ * and must never be quietly downgraded into a mesh the device keeps.*//**@@ -49,11 +42,11 @@ export const CLASSES = {means: 'the geometry is replayable from an asset the loader can load again;'+ ' a handle of this class with no recorded source is a contract violation',},- 'host-only-non-recoverable': {+ 'host-only-retained': {owes: 'why',policy: 'HostOnly',means: 'the geometry exists only in the process that built it, by design;'- + ' a device generation ends it, and no source can bring it back',+ + ' the device keeps its bytes and puts them back after a loss itself',},};@@ -68,7 +61,7 @@ export const MESH_PRODUCERS = [{id: 'freezeMeshGeometry',file: 'src/esengine/bindings/RendererBindings.cpp',- class: 'host-only-non-recoverable',+ class: 'host-only-retained',why: 'it uploads a MeshRenderer\'s INLINE payload — vertices that live in a component,'+ ' authored by whoever built the entity, with no asset under them — and clears the'+ ' payload afterwards, so the geometry survives nowhere else. Its only callers are'diff --git a/tools/render-host/host.ts b/tools/render-host/host.tsindex 4843e7185..9c90486b2 100644--- a/tools/render-host/host.ts+++ b/tools/render-host/host.ts@@ -20,7 +20,7 @@ import {createWebApp, setEditorMode, setPlayMode, Assets, acquireWebGPUDevice,loadSceneData, Renderer, instantiatePrefab, writeFieldPath, Transform, Name,getComponent, DeviceStatus, getDeviceStatus, getDeviceLostReport, recoverDevice,- finishDeviceRecovery, getContextLossGuardInfo, decodeImagePixels, captureFramePixels,+ getContextLossGuardInfo, decodeImagePixels, captureFramePixels,RenderTexture, Camera, Sprite,EditorView, EditorGrid, installEditorGrid, editorViewHalfHeight, setEditorViewHalfHeight,ProfileRecorder, AnimatorController, Timeline,@@ -689,12 +689,11 @@ window.__estellaHeadless = {status: () => getDeviceStatus(),report: () => getDeviceLostReport(),recover: () => recoverDevice(),- finishRecovery: () => finishDeviceRecovery(),recoverFull: async () => (await app?.getResource(Assets)?.recoverFromDeviceLoss()) ?? false,// Which textures did not come back, not how many: a failing recovery// needs the list, and a number cannot give it.awaiting: () => (app?.getResource(Assets)?.texturesAwaitingReupload() ?? [])- .map((t: { handle: number; path: string }) => `${t.handle}|${t.path}`),+ .map((t: { handle: number; content: number; path: string }) => `${t.handle}|${t.content}|${t.path}`),// Identity and realization apart, which a frame cannot show: a recovery// that minted fresh handles draws exactly like one that put the geometry// back behind the handles the world already points at.diff --git a/tools/render-host/run.mjs b/tools/render-host/run.mjsindex f828c8907..bf93eed27 100644--- a/tools/render-host/run.mjs+++ b/tools/render-host/run.mjs@@ -20,6 +20,8 @@* ESTELLA_VERIFY_GRID editor-grid on/off pixel-diff assertion (value = spacing)* ESTELLA_VERIFY_GRID_EXPECT what that diff must be: "frame" (default) or "nothing"* ESTELLA_VERIFY_GRID_RESPACE respace the drawn grid; the frame must change with it+ * ESTELLA_VERIFY_DEVICE_LOSS 1 | auto | roundtrip (lose the device; roundtrip compares the frame)+ * ESTELLA_VERIFY_LOSS_GRID draw the editor grid through a roundtrip (value = spacing)* ESTELLA_VERIFY_DEPTH_LAYERS bitmask of layers resolved by depth (2.5D)* ESTELLA_VERIFY_RENDER_RESOLUTION render at the scene's own resolution and* scale the finished image (1 = design, 2 = integer)@@ -139,8 +141,12 @@ function finish(result, server) {// 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));+ // Recovering exactly while something is owed: a device with nothing left to+ // refill is whole the moment it is rebuilt, and one that still owes is not.+ const owedAfterRecover = (dl?.awaitingAfterRecover?.length ?? 0) + (dl?.meshesOwedAfterRecover?.length ?? 0);const drivenSteps = !dl || dl.mode === 'auto' || (dl.glLostAfterRestore === false- && dl.recovered === true && dl.statusAfterRecover === 2 && dl.fullRecovered === true);+ && dl.recovered === true && dl.statusAfterRecover === (owedAfterRecover > 0 ? 2 : 0)+ && dl.fullRecovered === true);// 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. What the ENGINE owns comes back to the same size, full stop: a@@ -155,35 +161,30 @@ function finish(result, server) {return owned && (last.tables.buffers - first.tables.buffers) <= spans;})(rounds[1], rounds[rounds.length - 1], rounds.length - 2);// Geometry, which the pixels cannot speak for: a recovery that minted fresh- // handles draws the same frame as one that re-realized the old ones. Same- // identity set, each realized again, each on a LATER device generation.+ // handles draws the same frame as one that put the geometry back behind the+ // old ones. Same identity set, every one realized, nothing still owed.const meshIdentityOk = !dl || !dl.meshesBefore?.length || (() => {const before = dl.meshesBefore;const after = dl.meshesAfterFull ?? [];const by = (rows) => new Map(rows.map((m) => [m.handle, m]));const [b, a] = [by(before), by(after)];if (b.size !== a.size) return false;- for (const [handle, was] of b) {- const now = a.get(handle);- // Same handle, realized again, on a generation the dead one never saw.- if (!now || !now.realized || now.generation <= was.generation) return false;+ for (const handle of b.keys()) {+ if (!a.get(handle)?.realized) return false;}- // Nothing may still be owed: a debt outliving recovery is geometry that- // never came back, and the device had no business reporting Live.if ((dl.meshesOwedAfterFull?.length ?? 0) !== 0) return false;- // The middle state has to have happened. Without it, a scene that never lost- // its geometry passes this whole check by never having been broken.+ // Between the rebuild and the replay, what is not realized is exactly what+ // the engine says it is owed: a mesh missing from the ledger never comes back.if (dl.mode !== 'auto') {- if (!dl.meshesAfterRecover?.length) return false;- if (!dl.meshesAfterRecover.every((m) => !m.realized)) return false;- if ((dl.meshesOwedAfterRecover?.length ?? 0) !== before.length) return false;+ const unrealized = (dl.meshesAfterRecover ?? []).filter((m) => !m.realized).length;+ if ((dl.meshesAfterRecover?.length ?? 0) !== before.length) return false;+ if ((dl.meshesOwedAfterRecover?.length ?? 0) !== unrealized) return false;}return true;})();- // A rebuild empties the stock program cache, so readiness taken before it is- // stale. Without this, a stamp from the dead generation keeps vouching for- // programs nothing holds, and the first frame that needs one pays for it.- const epochOk = !dl || dl.epochBefore < 0 || dl.epochAfterFull > dl.epochBefore;+ // Programs come back behind their handles, so readiness taken before a rebuild+ // is still true. An epoch that moves would re-derive readiness nothing lost.+ const epochOk = !dl || dl.epochBefore < 0 || dl.epochAfterFull === dl.epochBefore;// The two are independent on purpose. A rebuilt device that left readiness// untouched, or readiness invalidated on a device that never moved, are both// states nothing downstream could reason about.@@ -209,7 +210,7 @@ function finish(result, server) {(result.resize?.ok ?? true) && (result.preview?.ok ?? true) &&(result.meshPreview?.ok ?? true) && (result.grid?.ok ?? true) &&(result.draws?.ok ?? true) && (result.counters?.ok ?? true) &&- deviceLossOk && meshOk && pickOk;+ (result.roundtrip?.ok ?? true) && deviceLossOk && meshOk && pickOk;const why = assetsOk ? '' : `: could not load ${result.missingAssets.join(', ')}`;console.log(`\n[verify:render] ${ok ? 'PASS' : 'FAIL'} — ${SCENE} (${BACKEND})${why}`);console.log('DRIVE_RESULT ' + JSON.stringify(result));@@ -618,6 +619,60 @@ app.whenReady().then(async () => {const spread = (max[0] - min[0]) + (max[1] - min[1]) + (max[2] - min[2]);return { w, h, totalPixels: px.length / 4, nonZeroPixels: nonZero, min, max, spread, rendered: spread > 16 };`);++ // ESTELLA_VERIFY_DEVICE_LOSS=roundtrip: frames pass until the device says Live,+ // and the frame must be the one from before the loss. A second capture before+ // any loss proves the scene holds still, or the comparison proves nothing.+ let roundtrip = null;+ if (process.env.ESTELLA_VERIFY_DEVICE_LOSS === 'roundtrip') {+ const gridSpacing = Number(process.env.ESTELLA_VERIFY_LOSS_GRID) || 0;+ if (gridSpacing > 0) {+ await exec(`window.__estellaHeadless.api.setGrid(true, ${gridSpacing})`);+ await exec('window.__estellaHeadless.api.step(2, 1 / 60)');+ }+ const tolerance = Number(process.env.ESTELLA_VERIFY_LOSS_TOLERANCE) || 0;+ const diffAgainstReference = `+ const ref = window.__estellaRoundtripRef;+ let differing = 0;+ for (let i = 0; i < px.length; i += 4) {+ if (Math.abs(ref[i] - px[i]) + Math.abs(ref[i + 1] - px[i + 1]) + Math.abs(ref[i + 2] - px[i + 2]) > 24) differing++;+ }+ return differing;+ `;+ await readFrame('window.__estellaRoundtripRef = px.slice(); return true;');+ await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);+ const still = await readFrame(diffAgainstReference);+ const rounds = [];+ for (let r = 0; r < ROUNDS; r++) {+ const round = await exec(`(async () => {+ const d = window.__estellaHeadless.device;+ const api = window.__estellaHeadless.api;+ if (!d.lose()) return { supported: false };+ for (let i = 0; i < 30 && d.status() === 0; i++) {+ await api.step(1, 1 / 60);+ await new Promise((r2) => setTimeout(r2, 50));+ }+ const lost = d.status() !== 0;+ d.restore();+ await new Promise((r2) => setTimeout(r2, 200));+ let frames = 0;+ for (; frames < 300 && d.status() !== 0; frames++) {+ await api.step(1, 1 / 60);+ await new Promise((r2) => setTimeout(r2, 16));+ }+ return { supported: true, lost, status: d.status(), frames };+ })()`);+ await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);+ round.differing = await readFrame(diffAgainstReference);+ rounds.push(round);+ }+ roundtrip = {+ still, tolerance, rounds,+ ok: still === 0 && rounds.length > 0 && rounds.every((x) => x.supported && x.lost+ && x.status === 0 && x.differing <= tolerance),+ };+ }+const drawCalls = await exec('window.__estellaHeadless.api.getStats().drawCalls');// What the frame COST, which no pixel shows: the same geometry drawn N times// is one instanced call, and the picture is identical either way. Asserted as@@ -865,7 +920,7 @@ app.whenReady().then(async () => {`);if (respaced != null) grid = { ...grid, respacedPixels: respaced, ok: grid.ok && respaced > 300 };}- finish({ ok: true, entityCount, missingAssets, drawCalls, draws, counters, profile, capture, expect, count, seam, resize, preview, meshPreview, grid, deviceLoss, meshResident, meshAsset, meshMaterial, meshPrefab, setField, animator, pick, cameraTarget }, server);+ finish({ ok: true, entityCount, missingAssets, drawCalls, draws, counters, profile, capture, expect, count, seam, resize, preview, meshPreview, grid, deviceLoss, roundtrip, meshResident, meshAsset, meshMaterial, meshPrefab, setField, animator, pick, cameraTarget }, server);} catch (e) {finish({ ok: false, error: String((e && e.stack) || e) }, server);}diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex fa34a5b85..148e55e6b 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -731,6 +731,19 @@ export const SCENES = [// only come from the page: the rounds check that the engine adopts a NEW one// each time. Object tables are a GL notion there and read zero.{ id: "device-loss-auto", tier: "pr", webgpu: { ESTELLA_VERIFY_LOSS_ROUNDS: "3" }, 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]}]" } },+ // The player's loss, judged by the picture: after the device comes back on its own, the frame+ // is the frame from before the loss, twice. One scene per kind of GPU object a recovery must+ // bring back, because each kind has had its own owner and its own way of being forgotten.+ { id: "device-roundtrip-grid", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_SCENE: "/scenes/sprite-rendering.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/sprite-rendering.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3", ESTELLA_VERIFY_LOSS_GRID: "64" } },+ { id: "device-roundtrip-instanced", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_SCENE: "/scenes/mesh-instanced.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3" } },+ { id: "device-roundtrip-skin-material", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_SCENE: "/scenes/mesh-skin-mat.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3" } },+ { id: "device-roundtrip-morph-material", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_SCENE: "/scenes/mesh-morph-mat.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3" } },+ { id: "device-roundtrip-shadow-material", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow-material.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3" } },+ { id: "device-roundtrip-sky", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_SCENE: "/scenes/mesh-sky.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3" } },+ { id: "device-roundtrip-env", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_SCENE: "/scenes/mat-env.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3" } },+ { id: "device-roundtrip-light-cookie", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_SCENE: "/scenes/light-cookie.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/light-cookie.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3" } },+ { id: "device-roundtrip-text", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/ui-screen-text.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ui-screen-text.textures.json", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "360", ESTELLA_VERIFY_STEPS: "6" } },+ { id: "device-roundtrip-post", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_DEVICE_LOSS: "roundtrip", ESTELLA_VERIFY_LOSS_ROUNDS: "2", ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/ui-screen-post.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ui-screen-post.textures.json", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "360", ESTELLA_VERIFY_STEPS: "4" } },];const rank = (tier) => TIERS.indexOf(tier);diff --git a/tools/verify-world-residency.mjs b/tools/verify-world-residency.mjsindex 6874b305a..8e47263e7 100644--- a/tools/verify-world-residency.mjs+++ b/tools/verify-world-residency.mjs@@ -397,8 +397,8 @@ function main() {// ---- 5. A readiness claim across a device generation ----------------//- // The epoch says readiness taken before a rebuild is worth nothing, and- // publication is where that debt comes due. All four facts are read.+ // A rebuild puts every program back behind its handle, so readiness taken+ // before it is still true: the claim survives and publication pays nothing.const CELL_COMPILES = 'render.mesh.programCompiles';const revalidate = drive(dir, 'readiness-across-loss', [{ do: 'step', frames: 30 },@@ -424,17 +424,17 @@ function main() {claim(afterLoss.device.generation > preLoss.device.generation,'losing the device and recovering advances the device generation',`generation ${preLoss.device.generation} → ${afterLoss.device.generation}`);- claim(afterLoss.device.programEpoch > preLoss.device.programEpoch,- 'and the program epoch too, independently — the stock cache went cold',+ claim(afterLoss.device.programEpoch === preLoss.device.programEpoch,+ 'but not the program epoch — the programs came back behind their handles',`epoch ${preLoss.device.programEpoch} → ${afterLoss.device.programEpoch}`);claim(afterLoss.claim !== null&& afterLoss.claim.programEpoch === preLoss.claim?.programEpoch,- 'the claim the cell is holding is now from a dead epoch, and it still holds it',+ 'the claim the cell is holding is still from the live epoch',`still ${JSON.stringify(afterLoss.claim)}`);claim(afterPublish.claim !== null&& afterPublish.claim.programEpoch === afterLoss.device.programEpoch- && afterPublish.claim.restamps === 1,- 'publishing it replaced the stale claim with one from the live epoch',+ && afterPublish.claim.restamps === 0,+ 'publishing it kept the claim it was prepared with',`claim ${JSON.stringify(afterPublish.claim)}`);claim(resident(revalidate.revealed, C),'the cell published', `resident ${JSON.stringify(revalidate.revealed.streaming.residentCells)}`);