Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(asset): onInvalidate event for hot-reload subscribers

esengine840f99efc653
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 606547f7c..85083c1be 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -27,6 +27,9 @@ import type { AssetRegistry } from './AssetRegistry';
import type { AssetRefCounter } from './AssetRefCounter';
import { log } from '../logger';
+/** Callback fired when `Assets.invalidate(ref)` actually dropped cache entries. */
+export type InvalidateListener = (ref: string) => void;
+
/**
* Default upper bound on concurrent loads inside preloadSceneAssets.
* Picked to match typical browser per-origin connection limits; scenes
@@ -139,6 +142,7 @@ export class Assets {
private assetRefResolver_: AssetRefResolver | null = null;
private assetRegistry_: AssetRegistry | null = null;
private refCounter_: AssetRefCounter | null = null;
+ private invalidateListeners_ = new Set<InvalidateListener>();
private constructor(options: AssetsOptions) {
this.backend = options.backend;
@@ -569,6 +573,11 @@ export class Assets {
* is evicted from the cache but not freed, so currently-rendering
* entities don't flicker.
*
+ * If any cache held `ref`, invokes every listener registered via
+ * `onInvalidate` with the original ref. Listeners that throw are
+ * caught and logged — one bad subscriber can't prevent other
+ * subscribers from observing the invalidation.
+ *
* Returns true if any cache held `ref`.
*/
invalidate(ref: string): boolean {
@@ -587,9 +596,35 @@ export class Assets {
if (cache.invalidate(path)) hit = true;
}
+ if (hit) {
+ for (const listener of this.invalidateListeners_) {
+ try {
+ listener(ref);
+ } catch (e) {
+ log.warn('asset', 'onInvalidate listener threw', e);
+ }
+ }
+ }
+
return hit;
}
+ /**
+ * Subscribe to cache invalidations. The listener fires once per
+ * successful `invalidate(ref)` call with the original ref (not the
+ * resolved path). Returns an unsubscribe function.
+ *
+ * Typical use: a scene-graph controller or renderer that holds cached
+ * handles for assets — subscribe to re-bind / re-load on hot reload
+ * so stale GPU handles stop being rendered.
+ */
+ onInvalidate(listener: InvalidateListener): () => void {
+ this.invalidateListeners_.add(listener);
+ return () => {
+ this.invalidateListeners_.delete(listener);
+ };
+ }
+
releaseAll(): void {
const rm = requireResourceManager();
for (const info of this.textureCache_.values()) {
diff --git a/sdk/tests/assets-invalidate-event.test.ts b/sdk/tests/assets-invalidate-event.test.ts
new file mode 100644
index 000000000..f9f3588b2
--- /dev/null
+++ b/sdk/tests/assets-invalidate-event.test.ts
@@ -0,0 +1,127 @@
+/**
+ * @file assets-invalidate-event.test.ts
+ * @brief Assets.onInvalidate subscription contract: listeners fire on
+ * successful invalidations, unsubscribe works, and a throwing
+ * listener doesn't starve others.
+ */
+import { describe, expect, it, vi } from 'vitest';
+import { Assets } from '../src/asset/Assets';
+import type { Backend } from '../src/asset/Backend';
+import type { ESEngineModule } from '../src/wasm';
+
+function buildAssets(): Assets {
+ const backend: Backend = {
+ resolveUrl: (p: string) => p,
+ fetchText: async () => '',
+ fetchBinary: async () => new ArrayBuffer(0),
+ } as unknown as Backend;
+ return new Assets({
+ backend,
+ module: { _malloc: () => 0, _free: () => {} } as unknown as ESEngineModule,
+ });
+}
+
+describe('Assets.onInvalidate', () => {
+ it('does NOT fire when invalidate() finds no matching cache entry', () => {
+ const assets = buildAssets();
+ const listener = vi.fn();
+ assets.onInvalidate(listener);
+
+ // No cache populated → invalidate returns false → no listener fires.
+ const hit = assets.invalidate('tex/never.png');
+ expect(hit).toBe(false);
+ expect(listener).not.toHaveBeenCalled();
+ });
+
+ it('fires with the original ref when invalidate hits a cache', async () => {
+ const assets = buildAssets();
+ // Seed the texture cache manually via internal map to avoid
+ // wiring up a real WASM texture loader.
+ const internal = assets as unknown as {
+ textureCache_: { cache_: Map<string, unknown> };
+ textureCacheKey_: (path: string, flip: boolean) => string;
+ textureRefCounts_: Map<string, number>;
+ };
+ const key = internal.textureCacheKey_('tex/hot.png', false);
+ internal.textureCache_.cache_.set(key, { handle: 42 });
+ internal.textureRefCounts_.set(key, 1);
+
+ const listener = vi.fn();
+ assets.onInvalidate(listener);
+
+ const hit = assets.invalidate('tex/hot.png');
+ expect(hit).toBe(true);
+ expect(listener).toHaveBeenCalledWith('tex/hot.png');
+ });
+
+ it('unsubscribe function prevents further notifications', () => {
+ const assets = buildAssets();
+ const internal = assets as unknown as {
+ textureCache_: { cache_: Map<string, unknown> };
+ textureCacheKey_: (path: string, flip: boolean) => string;
+ textureRefCounts_: Map<string, number>;
+ };
+ const key = internal.textureCacheKey_('tex/hot.png', false);
+ internal.textureCache_.cache_.set(key, { handle: 42 });
+ internal.textureRefCounts_.set(key, 1);
+
+ const listener = vi.fn();
+ const unsubscribe = assets.onInvalidate(listener);
+
+ assets.invalidate('tex/hot.png');
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+
+ // Re-populate cache and invalidate again — listener should NOT fire.
+ internal.textureCache_.cache_.set(key, { handle: 43 });
+ internal.textureRefCounts_.set(key, 1);
+ assets.invalidate('tex/hot.png');
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+
+ it('isolates listeners from each other — a throwing one does not starve others', () => {
+ const assets = buildAssets();
+ const internal = assets as unknown as {
+ textureCache_: { cache_: Map<string, unknown> };
+ textureCacheKey_: (path: string, flip: boolean) => string;
+ textureRefCounts_: Map<string, number>;
+ };
+ const key = internal.textureCacheKey_('tex/hot.png', false);
+ internal.textureCache_.cache_.set(key, { handle: 42 });
+ internal.textureRefCounts_.set(key, 1);
+
+ const bad = vi.fn(() => { throw new Error('listener failed'); });
+ const good = vi.fn();
+ assets.onInvalidate(bad);
+ assets.onInvalidate(good);
+
+ expect(() => assets.invalidate('tex/hot.png')).not.toThrow();
+ expect(bad).toHaveBeenCalledTimes(1);
+ expect(good).toHaveBeenCalledTimes(1);
+ });
+
+ it('supports multiple listeners observing the same invalidation', () => {
+ const assets = buildAssets();
+ const internal = assets as unknown as {
+ textureCache_: { cache_: Map<string, unknown> };
+ textureCacheKey_: (path: string, flip: boolean) => string;
+ textureRefCounts_: Map<string, number>;
+ };
+ const key = internal.textureCacheKey_('tex/a.png', false);
+ internal.textureCache_.cache_.set(key, { handle: 1 });
+ internal.textureRefCounts_.set(key, 1);
+
+ const a = vi.fn();
+ const b = vi.fn();
+ const c = vi.fn();
+ assets.onInvalidate(a);
+ assets.onInvalidate(b);
+ assets.onInvalidate(c);
+
+ assets.invalidate('tex/a.png');
+ expect(a).toHaveBeenCalledWith('tex/a.png');
+ expect(b).toHaveBeenCalledWith('tex/a.png');
+ expect(c).toHaveBeenCalledWith('tex/a.png');
+ });
+});