A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(assets): texture residency loop — released textures revive instead of re-decoding
yhh87c2160131a2
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex a585c42ab..df89bbb45 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -163,8 +163,14 @@ Key facts:- **ResourceManager / ResourcePool** — reference-counted GPU resources with athree-state lifecycle (Held → Evictable → Evicted). An intrusive LRU list plusa byte budget (`setTextureBudget`) evicts the oldest unreferenced entries when- resident bytes exceed the budget. (The budget/stats are not yet surfaced to the- SDK — see `REARCH_2D_PARITY.md` T1.)+ resident bytes exceed the budget. Textures loaded through the SDK carry a+ path identity (residency key), so a released texture is retained evictable and+ the next load revives it via `acquireTextureByPath` instead of re-decoding;+ hot reload severs the identity (`invalidateTexturePath`) so stale bytes are+ never revived. The SDK owns the asset-level refcount (one pool reference per+ cached texture); the pool owns residency. Surfaced to TS as+ `setTextureBudget(bytes)` / `getResourceStats()`, with a default budget from+ `RuntimeConfig.textureCacheBudget` applied at engine init.### Other C++ subsystemsdiff --git a/docs/astro/src/content/docs/guides/assets.mdx b/docs/astro/src/content/docs/guides/assets.mdxindex 8b0dd9ce2..14ddb2bf5 100644--- a/docs/astro/src/content/docs/guides/assets.mdx+++ b/docs/astro/src/content/docs/guides/assets.mdx@@ -99,19 +99,32 @@ manifest. Along the way it can:## Lifetime & reference countingLoaded GPU resources are **reference-counted**. When an entity that uses an asset-is despawned, its references are released; a byte-budgeted LRU then evicts the-oldest unreferenced textures when resident VRAM exceeds the budget. You generally-don't manage this by hand — reference and despawn entities normally.--Cap resident texture memory with `setTextureBudget` — the LRU evicts oldest-unreferenced textures once resident VRAM crosses it:+is despawned, its references are released — but a released texture isn't+destroyed immediately. It stays resident as an **evictable cache entry**, and if+the same texture is loaded again (re-entering a scene, streaming an area back+in) it is **revived in place** instead of re-fetched and re-decoded. A+byte-budgeted LRU evicts the oldest unreferenced textures once resident VRAM+exceeds the budget. You generally don't manage this by hand — reference and+despawn entities normally.++The budget defaults to **64 MB** (`RuntimeConfig.textureCacheBudget`, also+settable as `textureCacheBudget` in the build config). Size it for your game+with `setTextureBudget`, and watch residency with `getResourceStats`:```typescript-import { setTextureBudget } from 'esengine';+import { setTextureBudget, getResourceStats } from 'esengine';setTextureBudget(256 * 1024 * 1024); // 256 MB texture budget++const stats = getResourceStats();+// stats.textureBytes — resident texture bytes (held + evictable)+// stats.textureBudget — the current budget+// stats.textureEvictableCount — warm-cache entries awaiting revive/evict```+Setting the budget to `0` disables the warm cache — every texture frees the+moment its last reference is released.+## Best practices- **Reference by path in code, let the editor write `@uuid:`** — never hand-authordiff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 9d9ba951b..d2c6f57de 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -12,9 +12,9 @@ import type {import { AsyncCache } from './AsyncCache';import type { ESEngineModule } from '../wasm';import type { CppResourceManager } from '../wasm';-import { requireResourceManager, evictTextureDimensions } from '../resourceManager';+import { requireResourceManager, getResourceManager, evictTextureDimensions } from '../resourceManager';import type { TextureImportSettings, TextureImportSettingsResolver } from './loaders/TextureLoader';-import { TextureLoader } from './loaders/TextureLoader';+import { TextureLoader, textureResidencyKey } from './loaders/TextureLoader';import { SpineAssetLoader } from './loaders/SpineAssetLoader';import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';import { FontAssetLoader } from './loaders/FontAssetLoader';@@ -206,29 +206,53 @@ export class Assets {// =========================================================================async loadTexture(ref: string): Promise<TextureResult> {- const path = this.resolveLoadPath_(ref);- const cacheKey = this.textureCacheKey_(path, true);- const settings = this.textureImportResolver_?.(ref);- const result = await this.textureCache_.getOrLoad(cacheKey, () => {- this.textureLoader_.setPendingSettings(settings);- return this.textureLoader_.load(path, this.getLoadContext_());- });- this.textureRefCounts_.set(cacheKey, (this.textureRefCounts_.get(cacheKey) ?? 0) + 1);- return result;+ return this.loadTextureVariant_(ref, true);}async loadTextureRaw(ref: string): Promise<TextureResult> {+ return this.loadTextureVariant_(ref, false);+ }++ private async loadTextureVariant_(ref: string, flip: boolean): Promise<TextureResult> {const path = this.resolveLoadPath_(ref);- const cacheKey = this.textureCacheKey_(path, false);+ const cacheKey = this.textureCacheKey_(path, flip);const settings = this.textureImportResolver_?.(ref);const result = await this.textureCache_.getOrLoad(cacheKey, () => {+ // Warm-cache hit: a texture whose last reference was released stays+ // resident in the C++ pool (up to the texture budget) under this+ // exact key — reviving it skips the whole fetch + decode + upload.+ const revived = this.reviveResidentTexture_(cacheKey);+ if (revived) return Promise.resolve(revived);this.textureLoader_.setPendingSettings(settings);- return this.textureLoader_.loadRaw(path, this.getLoadContext_());+ return flip+ ? this.textureLoader_.load(path, this.getLoadContext_())+ : this.textureLoader_.loadRaw(path, this.getLoadContext_());});this.textureRefCounts_.set(cacheKey, (this.textureRefCounts_.get(cacheKey) ?? 0) + 1);return result;}+ /**+ * Try to revive an evictable texture from the C++ pool's residency cache.+ * Returns null on a miss — or when the resource-manager surface doesn't+ * support residency (minimal test mocks). Gated on invalidateTexturePath+ * too: reviving without the ability to sever a path on hot reload could+ * hand out stale bytes, so both must be present or neither is used.+ */+ private reviveResidentTexture_(cacheKey: string): TextureResult | null {+ const rm = requireResourceManager();+ if (typeof rm.acquireTextureByPath !== 'function'+ || typeof rm.invalidateTexturePath !== 'function') return null;+ const handle = rm.acquireTextureByPath(cacheKey);+ if (!handle) return null;+ const dims = rm.getTextureDimensions(handle);+ if (!dims) {+ rm.releaseTexture(handle);+ return null;+ }+ return { handle, width: dims.width, height: dims.height };+ }+/*** Provide per-asset texture import settings at load time (filter, wrap,* mipmaps). The resolver is called with the original ref — keyed off@@ -673,6 +697,9 @@ export class Assets {const newCount = count - 1;if (newCount <= 0) {+ // Last SDK reference: drop our one C++ ref. The pool decides+ // what that means — free immediately (no budget), or retain as+ // an evictable cache entry that the next load revives by key.const rm = requireResourceManager();rm.releaseTexture(info.handle);evictTextureDimensions(info.handle);@@ -742,11 +769,17 @@ export class Assets {const path = this.resolveRef(ref) ?? ref;let hit = false;- // Textures: cache_key has a flip flag suffix, so check both.+ // Textures: cache_key has a flip flag suffix, so check both. The C+++ // pool's residency identity is severed too — an evictable entry under+ // this key is freed and can never be revived with stale bytes.+ const rm = getResourceManager();for (const flip of [true, false]) {const key = this.textureCacheKey_(path, flip);if (this.textureCache_.invalidate(key)) hit = true;if (this.textureRefCounts_.delete(key)) hit = true;+ if (typeof rm?.invalidateTexturePath === 'function') {+ if (rm.invalidateTexturePath(key)) hit = true;+ }}// Generic caches: material / font / anim-clip / tilemap / timeline / audio / prefab.@@ -909,7 +942,7 @@ export class Assets {}private textureCacheKey_(path: string, flip: boolean): string {- return `${path}:${flip ? 'f' : 'n'}`;+ return textureResidencyKey(path, flip);}private async loadTyped<T>(type: string, ref: string): Promise<T> {diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.tsindex fa792f9d3..e6eaa3948 100644--- a/sdk/src/asset/loaders/TextureLoader.ts+++ b/sdk/src/asset/loaders/TextureLoader.ts@@ -36,6 +36,18 @@ export interface TextureImportSettings {export type TextureImportSettingsResolver = (ref: string) => TextureImportSettings | undefined;+/**+ * Canonical residency key for a texture: the resolved load path plus the+ * flip-orientation flag (flipped and raw uploads are genuinely different GPU+ * objects). One string serves as both the SDK's AsyncCache key and the C+++ * ResourcePool path identity, so a texture whose last reference was released+ * can be revived by `acquireTextureByPath` under the exact same key the next+ * `loadTexture` looks up.+ */+export function textureResidencyKey(path: string, flip: boolean): string {+ return `${path}:${flip ? 'f' : 'n'}`;+}+export class TextureLoader implements AssetLoader<TextureResult> {readonly type = 'texture';readonly extensions = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.ktx2'];@@ -130,6 +142,19 @@ export class TextureLoader implements AssetLoader<TextureResult> {private async loadWithFlip(path: string, ctx: LoadContext, flip: boolean, settings?: TextureImportSettings,+ ): Promise<TextureResult> {+ const result = await this.decodeAndUpload_(path, ctx, flip, settings);+ // Path identity in the C++ pool: after the last release the texture can+ // survive as an evictable cache entry (budget permitting) and the next+ // load revives it by this key instead of re-fetching + re-decoding.+ // Optional-chained: minimal test mocks may not model the pool surface.+ requireResourceManager().registerTextureWithPath?.(+ result.handle, textureResidencyKey(path, flip));+ return result;+ }++ private async decodeAndUpload_(+ path: string, ctx: LoadContext, flip: boolean, settings?: TextureImportSettings,): Promise<TextureResult> {if (path.toLowerCase().endsWith('.ktx2')) {return this.loadCompressed(path, ctx, settings);diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex e23a75488..8c46fc64b 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -70,7 +70,7 @@ export {// Resource budget (VRAM)// =============================================================================-export { setTextureBudget } from './resourceManager';+export { setTextureBudget, getResourceStats, type ResourceStats } from './resourceManager';// =============================================================================// Scenediff --git a/sdk/src/corePlugin.ts b/sdk/src/corePlugin.tsindex b9558e841..dd2a3e44e 100644--- a/sdk/src/corePlugin.ts+++ b/sdk/src/corePlugin.ts@@ -1,7 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { Plugin } from './app';-import { initResourceManager, shutdownResourceManager } from './resourceManager';+import { initResourceManager, shutdownResourceManager, setTextureBudget } from './resourceManager';+import { RuntimeConfig } from './defaults';import { initDrawAPI, shutdownDrawAPI } from './draw';import { clearDrawCallbacks } from './customDraw';import { initMaterialAPI, shutdownMaterialAPI } from './material';@@ -17,6 +18,10 @@ export const corePlugin: Plugin = {build(app) {const module = app.wasmModule!;initResourceManager(module.getResourceManager(), module);+ // Texture residency cache: released textures stay evictable in the C+++ // pool up to this byte budget, so the next load revives them instead of+ // re-decoding. Without this call the pool default (0) frees at once.+ setTextureBudget(RuntimeConfig.textureCacheBudget);initDrawAPI(module);initGeometryAPI(module);initMaterialAPI(module);diff --git a/sdk/src/defaults.ts b/sdk/src/defaults.tsindex 8f4299cd5..200526d9d 100644--- a/sdk/src/defaults.ts+++ b/sdk/src/defaults.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { CanvasScaleMode } from './wasm.generated';+import { getResourceManager, setTextureBudget } from './resourceManager';export const DEFAULT_DESIGN_WIDTH = 1920;export const DEFAULT_DESIGN_HEIGHT = 1080;@@ -27,6 +28,13 @@ export const RuntimeConfig = {textCanvasSize: 512,assetLoadTimeout: 30000,assetFailureCooldown: 5000,+ /**+ * Resident GPU-texture byte budget (see setTextureBudget). Released-but-+ * budgeted textures stay resident as an evictable LRU cache, so re-entering+ * a scene (or streaming an area back in) revives them instead of+ * re-fetching + re-decoding. 0 turns the cache off (free at refcount 0).+ */+ textureCacheBudget: 64 * 1024 * 1024,};export function applyRuntimeConfig(components: {@@ -57,6 +65,7 @@ export interface RuntimeBuildConfig {textCanvasSize?: number;assetLoadTimeout?: number;assetFailureCooldown?: number;+ textureCacheBudget?: number;}/** Canvas scale-mode name → value. Canonical names are single-sourced from the@@ -108,4 +117,10 @@ export function applyBuildRuntimeConfig(app: { setMaxDeltaTime(v: number): void;if (config.assetFailureCooldown !== undefined) {RuntimeConfig.assetFailureCooldown = config.assetFailureCooldown;}+ if (config.textureCacheBudget !== undefined) {+ RuntimeConfig.textureCacheBudget = config.textureCacheBudget;+ // This runs after app creation, where corePlugin already applied the+ // default budget — push the configured value through to the pool.+ if (getResourceManager()) setTextureBudget(config.textureCacheBudget);+ }}diff --git a/sdk/src/resourceManager.ts b/sdk/src/resourceManager.tsindex f59f4714e..d4c7d20bb 100644--- a/sdk/src/resourceManager.ts+++ b/sdk/src/resourceManager.ts@@ -56,8 +56,12 @@ export function requireResourceManager(): CppResourceManager {/*** Set the resident GPU-texture byte budget. When resident bytes exceed this,* the C++ ResourcePool evicts least-recently-used unreferenced textures. `0`- * (the default) disables caching — a texture frees the moment its refcount hits- * zero. Negative / fractional inputs are clamped to a non-negative integer.+ * disables caching — a texture frees the moment its refcount hits zero.+ * Negative / fractional inputs are clamped to a non-negative integer.+ *+ * The engine applies `RuntimeConfig.textureCacheBudget` at startup, so scene+ * switches keep recently-used textures warm by default; call this (or set+ * `textureCacheBudget` in the build config) to size it for your game.** This is the single game-facing surface over the C++ budget; there is no* parallel TS-side budget to drift from it.@@ -66,6 +70,34 @@ export function setTextureBudget(bytes: number): void {requireResourceManager().setTextureBudget(Math.max(0, Math.floor(bytes)));}+/** GPU resource counts + texture residency figures. See {@link getResourceStats}. */+export interface ResourceStats {+ shaderCount: number;+ textureCount: number;+ vertexBufferCount: number;+ indexBufferCount: number;+ cacheHits: number;+ cacheMisses: number;+ /** Resident texture bytes (RGBA8 estimate) — held + evictable entries. */+ textureBytes: number;+ /** The texture pool's resident-byte budget (0 = eviction off). */+ textureBudget: number;+ /** Cached refCount==0 textures awaiting revive or eviction. */+ textureEvictableCount: number;+}++/**+ * Snapshot of GPU resource usage from the C++ ResourceManager — the+ * observability side of the texture budget: watch `textureBytes` against+ * `textureBudget` and `textureEvictableCount` to size the warm cache.+ * Returns null when the resource manager isn't initialized (or a test mock+ * doesn't model stats).+ */+export function getResourceStats(): ResourceStats | null {+ if (!rm_ || typeof rm_.getResourceStats !== 'function') return null;+ return rm_.getResourceStats();+}+export function evictTextureDimensions(handle: number): void {dimsCache_.delete(handle);}diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex d703ebb71..f54d70238 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -53,6 +53,18 @@ export interface CppResourceManager {registerTextureWithPath(handle: number, path: string): void;setTextureBudget(bytes: number): void;acquireTextureByPath(path: string): number;+ invalidateTexturePath(path: string): boolean;+ getResourceStats(): {+ shaderCount: number;+ textureCount: number;+ vertexBufferCount: number;+ indexBufferCount: number;+ cacheHits: number;+ cacheMisses: number;+ textureBytes: number;+ textureBudget: number;+ textureEvictableCount: number;+ };loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;releaseBitmapFont(handle: number): void;diff --git a/sdk/tests/mocks/wasm.ts b/sdk/tests/mocks/wasm.tsindex b69379318..d4b5e590f 100644--- a/sdk/tests/mocks/wasm.ts+++ b/sdk/tests/mocks/wasm.ts@@ -117,9 +117,19 @@ export function createMockModule(): ESEngineModule {loadTexture: () => 1,releaseTexture: () => {},getTextureSize: () => ({ width: 100, height: 100 }),+ getTextureDimensions: () => ({ width: 100, height: 100 }),loadBitmapFont: () => 1,releaseBitmapFont: () => {},setTextureMetadata: () => {},+ setTextureBudget: () => {},+ registerTextureWithPath: () => {},+ acquireTextureByPath: () => 0,+ invalidateTexturePath: () => false,+ getResourceStats: () => ({+ shaderCount: 0, textureCount: 0, vertexBufferCount: 0, indexBufferCount: 0,+ cacheHits: 0, cacheMisses: 0,+ textureBytes: 0, textureBudget: 0, textureEvictableCount: 0,+ }),};return {diff --git a/sdk/tests/texture-residency.test.ts b/sdk/tests/texture-residency.test.tsnew file mode 100644index 000000000..c9086d6f9--- /dev/null+++ b/sdk/tests/texture-residency.test.ts@@ -0,0 +1,227 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file texture-residency.test.ts+ * @brief Assets ↔ C++ pool residency contract: a released texture stays+ * revivable by its residency key (no re-decode), hot-reload+ * invalidation severs that identity, and the SDK holds exactly one+ * pool reference regardless of how many callers loaded the texture.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Assets } from '../src/asset/Assets';+import type { Backend } from '../src/asset/Backend';++interface PoolEntry {+ refCount: number;+ path: string | null;+ evictable: boolean;+}++/**+ * Stateful stand-in for the C++ ResourcePool texture surface, modelling the+ * held → evictable → evicted lifecycle the SDK glue is written against.+ */+function createPoolFake() {+ const entries = new Map<number, PoolEntry>();+ const byPath = new Map<string, number>();+ let nextHandle = 1;++ const free = (handle: number): void => {+ const e = entries.get(handle);+ if (!e) return;+ if (e.path !== null && byPath.get(e.path) === handle) byPath.delete(e.path);+ entries.delete(handle);+ };++ const rm = {+ budget: 1024 * 1024,+ createTexture: vi.fn((): number => {+ const handle = nextHandle++;+ entries.set(handle, { refCount: 1, path: null, evictable: false });+ return handle;+ }),+ registerExternalTexture: vi.fn((): number => rm.createTexture()),+ registerTextureWithPath: vi.fn((handle: number, path: string): void => {+ const e = entries.get(handle);+ if (!e || e.refCount === 0) return;+ e.path = path;+ byPath.set(path, handle);+ }),+ acquireTextureByPath: vi.fn((path: string): number => {+ const handle = byPath.get(path);+ if (handle === undefined) return 0;+ const e = entries.get(handle)!;+ if (e.evictable) {+ e.evictable = false;+ e.refCount = 1;+ } else {+ e.refCount++;+ }+ return handle;+ }),+ invalidateTexturePath: vi.fn((path: string): boolean => {+ const handle = byPath.get(path);+ if (handle === undefined) return false;+ byPath.delete(path);+ const e = entries.get(handle)!;+ e.path = null;+ if (e.evictable) free(handle);+ return true;+ }),+ releaseTexture: vi.fn((handle: number): void => {+ const e = entries.get(handle);+ if (!e || e.refCount === 0) return;+ if (--e.refCount === 0) {+ if (rm.budget > 0 && e.path !== null) {+ e.evictable = true;+ } else {+ free(handle);+ }+ }+ }),+ getTextureDimensions: vi.fn((handle: number) => {+ const e = entries.get(handle);+ if (!e || e.refCount === 0) return null;+ return { width: 64, height: 64 };+ }),+ getTextureGLId: vi.fn(() => 1),+ // Test-only inspection helpers.+ entryOf: (handle: number) => entries.get(handle) ?? null,+ isResident: (handle: number) => entries.has(handle),+ };+ return rm;+}++let pool = createPoolFake();++vi.mock('../src/resourceManager', () => ({+ requireResourceManager: () => pool,+ getResourceManager: () => pool,+ evictTextureDimensions: vi.fn(),+}));++vi.mock('../src/platform', () => ({+ platformCreateCanvas: () => ({+ width: 256, height: 256,+ getContext: () => ({+ clearRect: vi.fn(),+ drawImage: vi.fn(),+ getImageData: () => ({ data: { buffer: new ArrayBuffer(256 * 256 * 4) } }),+ }),+ }),+ platformCreateImage: () => {+ const img: { width?: number; height?: number; onload?: () => void } = {};+ setTimeout(() => { img.width = 64; img.height = 64; img.onload?.(); }, 0);+ return img;+ },+ platformFetch: vi.fn(),+ platformReadFile: vi.fn(),+ platformReadTextFile: vi.fn(),+ platformFileExists: vi.fn(),+}));++const mockModule = {+ _malloc: vi.fn(() => 0),+ _free: vi.fn(),+ HEAPU8: new Uint8Array(1024 * 1024),+ GL: null,+ FS: null,+} as never;++function buildAssets(): Assets {+ const backend: Backend = {+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),+ fetchText: vi.fn(async () => '{}'),+ resolveUrl: (path: string) => `http://test/${path}`,+ } as unknown as Backend;+ return Assets.create({ backend, module: mockModule });+}++describe('texture residency (Assets ↔ pool contract)', () => {+ beforeEach(() => {+ pool = createPoolFake();+ });++ it('registers the residency key at load time', async () => {+ const assets = buildAssets();+ const result = await assets.loadTexture('tex/a.png');+ expect(pool.registerTextureWithPath).toHaveBeenCalledWith(result.handle, 'tex/a.png:f');+ });++ it('release keeps the texture evictable; the next load revives it without re-decoding', async () => {+ const assets = buildAssets();+ const first = await assets.loadTexture('tex/a.png');+ expect(pool.createTexture).toHaveBeenCalledTimes(1);++ assets.releaseTexture('tex/a.png');+ expect(pool.entryOf(first.handle)).toMatchObject({ refCount: 0, evictable: true });+ expect(assets.getTexture('tex/a.png')).toBeUndefined();++ const second = await assets.loadTexture('tex/a.png');+ expect(second.handle).toBe(first.handle);+ expect(second.width).toBe(64);+ expect(pool.createTexture).toHaveBeenCalledTimes(1); // no second decode+upload+ expect(pool.entryOf(second.handle)).toMatchObject({ refCount: 1, evictable: false });+ });++ it('the SDK holds one pool reference no matter how many callers loaded', async () => {+ const assets = buildAssets();+ const result = await assets.loadTexture('tex/a.png');+ await assets.loadTexture('tex/a.png');+ expect(pool.entryOf(result.handle)?.refCount).toBe(1);++ assets.releaseTexture('tex/a.png');+ expect(pool.releaseTexture).not.toHaveBeenCalled(); // still one SDK ref outstanding+ expect(pool.entryOf(result.handle)?.refCount).toBe(1);++ assets.releaseTexture('tex/a.png');+ expect(pool.releaseTexture).toHaveBeenCalledTimes(1);+ expect(pool.entryOf(result.handle)?.evictable).toBe(true);+ });++ it('invalidate severs the residency identity — an evicted entry is never revived', async () => {+ const assets = buildAssets();+ const first = await assets.loadTexture('tex/a.png');+ assets.releaseTexture('tex/a.png');+ expect(pool.entryOf(first.handle)?.evictable).toBe(true);++ assets.invalidate('tex/a.png');+ expect(pool.isResident(first.handle)).toBe(false); // evictable + invalidated → freed++ const second = await assets.loadTexture('tex/a.png');+ expect(second.handle).not.toBe(first.handle);+ expect(pool.createTexture).toHaveBeenCalledTimes(2); // fresh bytes, no stale revive+ });++ it('invalidate on a held texture keeps it alive for current holders but blocks future revival', async () => {+ const assets = buildAssets();+ const first = await assets.loadTexture('tex/a.png');++ assets.invalidate('tex/a.png');+ expect(pool.isResident(first.handle)).toBe(true); // old handle keeps rendering++ const second = await assets.loadTexture('tex/a.png');+ expect(second.handle).not.toBe(first.handle);+ expect(pool.createTexture).toHaveBeenCalledTimes(2);+ });++ it('flip variants are distinct residency entries', async () => {+ const assets = buildAssets();+ const flipped = await assets.loadTexture('tex/a.png');+ const raw = await assets.loadTextureRaw('tex/a.png');+ expect(raw.handle).not.toBe(flipped.handle);+ expect(pool.registerTextureWithPath).toHaveBeenCalledWith(flipped.handle, 'tex/a.png:f');+ expect(pool.registerTextureWithPath).toHaveBeenCalledWith(raw.handle, 'tex/a.png:n');+ });++ it('with the budget off, release frees outright and the next load re-decodes', async () => {+ pool.budget = 0;+ const assets = buildAssets();+ const first = await assets.loadTexture('tex/a.png');+ assets.releaseTexture('tex/a.png');+ expect(pool.isResident(first.handle)).toBe(false);++ await assets.loadTexture('tex/a.png');+ expect(pool.createTexture).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cppindex 9d04c90fb..711c2a3ac 100644--- a/src/esengine/bindings/ResourceManagerBindings.cpp+++ b/src/esengine/bindings/ResourceManagerBindings.cpp@@ -94,6 +94,25 @@ u32 rm_acquireTextureByPath(resource::ResourceManager& rm, const std::string& pareturn rm.acquireTextureByPath(path).id();}+bool rm_invalidateTexturePath(resource::ResourceManager& rm, const std::string& path) {+ return rm.invalidateTexturePath(path);+}++emscripten::val rm_getResourceStats(resource::ResourceManager& rm) {+ const auto st = rm.getStats();+ auto result = emscripten::val::object();+ result.set("shaderCount", static_cast<f64>(st.shaderCount));+ result.set("textureCount", static_cast<f64>(st.textureCount));+ result.set("vertexBufferCount", static_cast<f64>(st.vertexBufferCount));+ result.set("indexBufferCount", static_cast<f64>(st.indexBufferCount));+ result.set("cacheHits", static_cast<f64>(st.cacheHits));+ result.set("cacheMisses", static_cast<f64>(st.cacheMisses));+ result.set("textureBytes", static_cast<f64>(st.textureBytes));+ result.set("textureBudget", static_cast<f64>(st.textureBudget));+ result.set("textureEvictableCount", static_cast<f64>(st.textureEvictableCount));+ return result;+}+void rm_releaseShader(resource::ResourceManager& rm, u32 handleId) {rm.releaseShader(resource::ShaderHandle(handleId));}diff --git a/src/esengine/bindings/ResourceManagerBindings.hpp b/src/esengine/bindings/ResourceManagerBindings.hppindex 6349ff939..8da1fd0e3 100644--- a/src/esengine/bindings/ResourceManagerBindings.hpp+++ b/src/esengine/bindings/ResourceManagerBindings.hpp@@ -27,6 +27,8 @@ u32 rm_getTextureRefCount(resource::ResourceManager& rm, u32 handleId);void rm_registerTextureWithPath(resource::ResourceManager& rm, u32 handleId, const std::string& path);void rm_setTextureBudget(resource::ResourceManager& rm, u32 bytes);u32 rm_acquireTextureByPath(resource::ResourceManager& rm, const std::string& path);+bool rm_invalidateTexturePath(resource::ResourceManager& rm, const std::string& path);+emscripten::val rm_getResourceStats(resource::ResourceManager& rm);void rm_releaseShader(resource::ResourceManager& rm, u32 handleId);u32 rm_getShaderRefCount(resource::ResourceManager& rm, u32 handleId);u32 rm_getTextureGLId(resource::ResourceManager& rm, u32 handleId);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex c476c4f65..e0802d872 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -407,6 +407,8 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {.function("registerTextureWithPath", &esengine::rm_registerTextureWithPath).function("setTextureBudget", &esengine::rm_setTextureBudget).function("acquireTextureByPath", &esengine::rm_acquireTextureByPath)+ .function("invalidateTexturePath", &esengine::rm_invalidateTexturePath)+ .function("getResourceStats", &esengine::rm_getResourceStats)#ifdef ES_ENABLE_BITMAP_TEXT.function("loadBitmapFont", &esengine::rm_loadBitmapFont).function("createLabelAtlasFont", &esengine::rm_createLabelAtlasFont)diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cppindex 9a5a57310..567946db4 100644--- a/src/esengine/resource/ResourceManager.cpp+++ b/src/esengine/resource/ResourceManager.cpp@@ -229,6 +229,10 @@ TextureHandle ResourceManager::acquireTextureByPath(const std::string& path) {return handle;}+bool ResourceManager::invalidateTexturePath(const std::string& path) {+ return textures_.invalidatePath(path);+}+TextureHandle ResourceManager::loadTextureByGUID(const std::string& guid, const std::string& path) {auto it = guidToTexture_.find(guid);if (it != guidToTexture_.end() && it->second.isValid()) {@@ -422,6 +426,8 @@ ResourceStats ResourceManager::getStats() const {stats_.vertexBufferCount = vertexBuffers_.size();stats_.indexBufferCount = indexBuffers_.size();stats_.textureBytes = textures_.residentBytes();+ stats_.textureBudget = textures_.budget();+ stats_.textureEvictableCount = textures_.evictableCount();return stats_;}diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hppindex 33ec40e6d..b072ec39c 100644--- a/src/esengine/resource/ResourceManager.hpp+++ b/src/esengine/resource/ResourceManager.hpp@@ -52,6 +52,8 @@ struct ResourceStats {usize cacheHits = 0; ///< Number of cache hits since resetusize cacheMisses = 0; ///< Number of cache misses since resetusize textureBytes = 0; ///< Resident texture bytes (RGBA8 estimate) — VRAM usage+ usize textureBudget = 0; ///< Texture pool resident-byte budget (0 = eviction off)+ usize textureEvictableCount = 0; ///< Cached refCount==0 textures awaiting revive/evict};// =============================================================================@@ -283,6 +285,15 @@ public:*/TextureHandle acquireTextureByPath(const std::string& path);+ /**+ * @brief Severs a path's texture-cache identity (hot reload). The next+ * acquireTextureByPath for it misses, so stale bytes are never+ * revived; an evictable entry under that path is freed immediately.+ * @param path The path to invalidate+ * @return True if the path was registered+ */+ bool invalidateTexturePath(const std::string& path);+// =========================================================================// Texture Metadata// =========================================================================diff --git a/src/esengine/resource/ResourcePool.hpp b/src/esengine/resource/ResourcePool.hppindex 5a18bb72e..8a3a90eb8 100644--- a/src/esengine/resource/ResourcePool.hpp+++ b/src/esengine/resource/ResourcePool.hpp@@ -237,8 +237,11 @@ public:auto& entry = entries_[index];if (entry.refCount == 0 || entry.generation != gen) return;if (--entry.refCount == 0) {- if (budget_ == 0) {- freeEntry_(index); // no budget → free immediately (the default)+ if (budget_ == 0 || entry.path.empty()) {+ // No budget → free immediately. Same for pathless entries even+ // under a budget: findByPath is the only revive channel, so a+ // cached entry nobody can find would just squat on the budget.+ freeEntry_(index);} else {// 3-state lifecycle: held → evictable (cached in the LRU, still// findByPath-able for cache hits) → evicted. Drop the oldest@@ -289,6 +292,32 @@ public:/** @brief The current resident-byte budget (0 = caching disabled). */usize budget() const { return budget_; }+ /**+ * @brief Severs a path's cache identity so the entry can't be revived+ * @details For hot reload: the bytes behind `path` changed, so the cached+ * resource must never be handed out for that path again. Removes+ * the path mapping; an evictable entry is freed immediately, a+ * held entry stays alive for its current holders but loses its+ * path, so its final release frees it instead of caching it.+ * @param path The path to invalidate+ * @return True if a mapping for `path` existed+ */+ bool invalidatePath(const std::string& path) {+ auto it = pathToId_.find(path);+ if (it == pathToId_.end()) return false;+ u32 index = Handle<T>::extractIndex(it->second);+ u32 gen = Handle<T>::extractGeneration(it->second);+ pathToId_.erase(it);+ if (index >= entries_.size()) return true;+ auto& entry = entries_[index];+ if (entry.generation != gen) return true;+ entry.path.clear();+ if (entry.evictable) {+ freeEntry_(index);+ }+ return true;+ }+/** @brief Bytes currently resident (held + evictable entries). */usize residentBytes() const { return residentBytes_; }diff --git a/tests/resource/test_resource_pool.cpp b/tests/resource/test_resource_pool.cppindex 378db317e..5640f9fa0 100644--- a/tests/resource/test_resource_pool.cpp+++ b/tests/resource/test_resource_pool.cpp@@ -2,6 +2,7 @@#include <doctest.h>#include <esengine/ESEngine.hpp>+#include <esengine/resource/ResourcePool.hpp>#include <string>#include <memory>@@ -350,3 +351,66 @@ TEST_CASE("pool_set_budget_evicts_now") {CHECK(!pool.findByPath("a").isValid());CHECK(pool.findByPath("b").isValid());}++TEST_CASE("pool_budget_pathless_frees_immediately") {+ // A pathless entry can never be revived (findByPath is the only revive+ // channel), so even under a budget it frees at refCount 0 instead of+ // squatting on the budget as an unreachable cache entry.+ test::DummyPool pool;+ pool.setBudget(1000);+ auto h = pool.add(esengine::makeUnique<test::DummyResource>(1), "", 100);+ pool.release(h.id());+ CHECK_EQ(pool.residentBytes(), 0u);+ CHECK_EQ(pool.evictableCount(), 0u);+ CHECK(pool.get(h) == nullptr);+}++TEST_CASE("pool_invalidate_path_frees_evictable") {+ test::DummyPool pool;+ pool.setBudget(1000);+ auto h = pool.add(esengine::makeUnique<test::DummyResource>(1), "a.png", 100);+ pool.release(h.id());+ CHECK(pool.isEvictable(h));++ CHECK(pool.invalidatePath("a.png"));+ CHECK_EQ(pool.residentBytes(), 0u);+ CHECK_EQ(pool.evictableCount(), 0u);+ CHECK(!pool.findByPath("a.png").isValid());+ CHECK(!pool.invalidatePath("a.png")); // already gone+}++TEST_CASE("pool_invalidate_path_on_held_entry") {+ // A held entry stays alive for its current holders but loses its cache+ // identity: no future cache hit, and its final release frees it outright.+ test::DummyPool pool;+ pool.setBudget(1000);+ auto h = pool.add(esengine::makeUnique<test::DummyResource>(9), "a.png", 100);++ CHECK(pool.invalidatePath("a.png"));+ CHECK(pool.get(h) != nullptr); // still usable while held+ CHECK(!pool.findByPath("a.png").isValid()); // but no longer findable++ pool.release(h.id()); // pathless now → freed, not cached+ CHECK_EQ(pool.residentBytes(), 0u);+ CHECK_EQ(pool.evictableCount(), 0u);+ CHECK(pool.get(h) == nullptr);+}++TEST_CASE("pool_invalidate_path_then_reload_same_path") {+ // Hot-reload sequence: invalidate, then a fresh add() under the same path+ // becomes the new cache identity for it.+ test::DummyPool pool;+ pool.setBudget(1000);+ auto stale = pool.add(esengine::makeUnique<test::DummyResource>(1), "a.png", 100);+ pool.invalidatePath("a.png");++ auto fresh = pool.add(esengine::makeUnique<test::DummyResource>(2), "a.png", 100);+ auto found = pool.findByPath("a.png");+ CHECK(found.isValid());+ CHECK_EQ(found.id(), fresh.id());+ CHECK(found != stale);++ pool.release(stale.id()); // stale holder done → freed (pathless)+ CHECK(pool.findByPath("a.png").isValid()); // fresh identity unaffected+ CHECK_EQ(pool.get(fresh)->value, 2);+}