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): wire AssetRefCounter into the load/despawn lifecycle

esengine58a1cfc434e6
diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.ts
index 522230409..e23c3a93b 100644
--- a/sdk/src/asset/AssetPlugin.ts
+++ b/sdk/src/asset/AssetPlugin.ts
@@ -3,6 +3,7 @@ import { defineResource } from '../resource';
import { Assets as AssetsClass } from './Assets';
import { HttpBackend } from './Backend';
import { initBuiltinAssetFields } from './AssetFieldRegistry';
+import { AssetRefCounter } from './AssetRefCounter';
export type AssetsData = AssetsClass;
@@ -27,6 +28,15 @@ export class AssetPlugin implements Plugin {
backend: new HttpBackend({ baseUrl: '' }),
module,
});
+
+ // Install the ref counter so resolveSceneAssetPaths records who
+ // uses what, and wire it to world despawns so entries don't
+ // outlive their entities. Tools / debug UI read it via
+ // `assets.getRefCounter()`.
+ const counter = new AssetRefCounter();
+ assets.setRefCounter(counter);
+ app.world.onDespawn((entity) => counter.removeAllRefsForEntity(entity));
+
app.insertResource(Assets, assets);
}
}
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 3e1d68835..d40c9f507 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -24,6 +24,7 @@ import { discoverSceneAssets } from './discoverAssets';
import type { SceneData } from '../scene';
import { SceneHandle, type ReleaseCallback } from './SceneHandle';
import type { AssetRegistry } from './AssetRegistry';
+import type { AssetRefCounter } from './AssetRefCounter';
export interface AssetsOptions {
backend: Backend;
@@ -90,6 +91,7 @@ export class Assets {
private loadContext_: LoadContext | null = null;
private assetRefResolver_: AssetRefResolver | null = null;
private assetRegistry_: AssetRegistry | null = null;
+ private refCounter_: AssetRefCounter | null = null;
private constructor(options: AssetsOptions) {
this.backend = options.backend;
@@ -385,6 +387,7 @@ export class Assets {
resolveSceneAssetPaths(sceneData: SceneData, result: SceneAssetResult): void {
const { textureHandles, materialHandles, fontHandles } = result;
+ const counter = this.refCounter_;
for (const entity of sceneData.entities) {
for (const comp of entity.components) {
@@ -404,7 +407,9 @@ export class Assets {
switch (type) {
case 'texture': {
- comp.data[field] = textureHandles.get(path) ?? 0;
+ const handle = textureHandles.get(path) ?? 0;
+ comp.data[field] = handle;
+ if (counter && handle) counter.addTextureRef(path, entity.id);
const atlasInfo = this.catalog.getAtlasFrame(path);
if (atlasInfo) {
comp.data['uvOffset'] = { x: atlasInfo.uvOffset[0], y: atlasInfo.uvOffset[1] };
@@ -418,12 +423,18 @@ export class Assets {
}
break;
}
- case 'material':
- comp.data[field] = materialHandles.get(path) ?? 0;
+ case 'material': {
+ const handle = materialHandles.get(path) ?? 0;
+ comp.data[field] = handle;
+ if (counter && handle) counter.addMaterialRef(path, entity.id);
break;
- case 'font':
- comp.data[field] = fontHandles.get(path) ?? 0;
+ }
+ case 'font': {
+ const handle = fontHandles.get(path) ?? 0;
+ comp.data[field] = handle;
+ if (counter && handle) counter.addFontRef(path, entity.id);
break;
+ }
}
}
}
@@ -562,6 +573,23 @@ export class Assets {
return this.assetRegistry_;
}
+ /**
+ * Attach an AssetRefCounter. When set, resolveSceneAssetPaths records
+ * which entity references which texture/material/font path as it
+ * hands out handles. Paired with `world.onDespawn(e =>
+ * counter.removeAllRefsForEntity(e))` — which AssetPlugin installs
+ * — this gives editor tools visibility into "who's holding X" and
+ * "does anything still need this asset?". Optional; null means no
+ * tracking (default, zero overhead).
+ */
+ setRefCounter(counter: AssetRefCounter): void {
+ this.refCounter_ = counter;
+ }
+
+ getRefCounter(): AssetRefCounter | null {
+ return this.refCounter_;
+ }
+
/**
* Resolve any serialized asset ref (UUID or plain path) to a concrete
* path. Returns null when a UUID ref can't be matched to a known
diff --git a/sdk/tests/asset-refcounter-integration.test.ts b/sdk/tests/asset-refcounter-integration.test.ts
new file mode 100644
index 000000000..6cfbe5ba1
--- /dev/null
+++ b/sdk/tests/asset-refcounter-integration.test.ts
@@ -0,0 +1,166 @@
+/**
+ * Verifies that Assets.resolveSceneAssetPaths populates an attached
+ * AssetRefCounter so tools can answer "which entities hold this asset?".
+ *
+ * We only exercise the bookkeeping path — no WASM, no real loader.
+ * resolveSceneAssetPaths takes a SceneAssetResult whose handle maps we
+ * prebuild here; the refCounter should then reflect every (path,entity)
+ * pair that got a non-zero handle.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { defineComponent, clearUserComponents } from '../src/component';
+import { Assets } from '../src/asset/Assets';
+import { AssetRefCounter } from '../src/asset/AssetRefCounter';
+import { registerAssetFields, clearAssetFieldRegistry } from '../src/asset/AssetFieldRegistry';
+import type { Backend } from '../src/asset/Backend';
+import type { SceneData } from '../src/scene';
+import type { SceneAssetResult } from '../src/asset/Assets';
+
+vi.mock('../src/resourceManager', () => ({
+ requireResourceManager: () => ({ releaseTexture: vi.fn() }),
+ evictTextureDimensions: vi.fn(),
+}));
+
+const SPRITE = 'RefCountTest_Sprite';
+const LABEL = 'RefCountTest_Label';
+
+const mockModule = {} as never;
+const mockBackend: Backend = {
+ fetchText: vi.fn(), fetchBinary: vi.fn(), fetchJson: vi.fn(),
+ resolveUrl: (p: string) => p,
+} as unknown as Backend;
+
+function makeAssets(): Assets {
+ return Assets.create({ backend: mockBackend, module: mockModule });
+}
+
+function sceneWith(entityId: number, sprite: { texture: string; material?: string }): SceneData {
+ const data: Record<string, unknown> = { texture: sprite.texture, color: { r: 1, g: 1, b: 1, a: 1 } };
+ if (sprite.material !== undefined) data.material = sprite.material;
+ return {
+ version: '1.0',
+ name: 'test',
+ entities: [{
+ id: entityId, name: 'e', parent: null, children: [],
+ components: [{ type: SPRITE, data }],
+ }],
+ };
+}
+
+function emptyResult(): SceneAssetResult {
+ return {
+ textureHandles: new Map(),
+ materialHandles: new Map(),
+ fontHandles: new Map(),
+ releaseCallbacks: [],
+ missing: [],
+ };
+}
+
+beforeEach(() => {
+ clearUserComponents();
+ clearAssetFieldRegistry();
+ defineComponent(SPRITE, {
+ texture: '',
+ material: '',
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ });
+ defineComponent(LABEL, { font: '', text: '' });
+ // resolveSceneAssetPaths pulls fields from this registry, not from
+ // defineComponent metadata.
+ registerAssetFields(SPRITE, [
+ { field: 'texture', type: 'texture' },
+ { field: 'material', type: 'material' },
+ ]);
+ registerAssetFields(LABEL, [{ field: 'font', type: 'font' }]);
+});
+
+describe('Assets.resolveSceneAssetPaths → AssetRefCounter', () => {
+ it('records texture refs against the entity id when a handle resolves', () => {
+ const assets = makeAssets();
+ const counter = new AssetRefCounter();
+ assets.setRefCounter(counter);
+
+ const scene = sceneWith(7, { texture: 'assets/player.png' });
+ const result = emptyResult();
+ result.textureHandles.set('assets/player.png', 42);
+
+ assets.resolveSceneAssetPaths(scene, result);
+
+ expect(counter.getTextureRefCount('assets/player.png')).toBe(1);
+ expect(counter.getTextureRefs('assets/player.png')).toEqual([7]);
+ });
+
+ it('does not record when the handle is 0 (asset load failed)', () => {
+ const assets = makeAssets();
+ const counter = new AssetRefCounter();
+ assets.setRefCounter(counter);
+
+ const scene = sceneWith(7, { texture: 'assets/missing.png' });
+ // Result has the path but the handle is 0 (load failed).
+ const result = emptyResult();
+ result.textureHandles.set('assets/missing.png', 0);
+
+ assets.resolveSceneAssetPaths(scene, result);
+
+ expect(counter.getTextureRefCount('assets/missing.png')).toBe(0);
+ });
+
+ it('records material and font refs under their own buckets', () => {
+ const assets = makeAssets();
+ const counter = new AssetRefCounter();
+ assets.setRefCounter(counter);
+
+ const scene: SceneData = {
+ version: '1.0', name: 't',
+ entities: [
+ {
+ id: 1, name: 'a', parent: null, children: [],
+ components: [{
+ type: SPRITE,
+ data: { texture: 'a.png', material: 'a.mat', color: { r: 1, g: 1, b: 1, a: 1 } },
+ }],
+ },
+ {
+ id: 2, name: 'b', parent: null, children: [],
+ components: [{ type: LABEL, data: { font: 'font.fnt', text: 'hi' } }],
+ },
+ ],
+ };
+ const result = emptyResult();
+ result.textureHandles.set('a.png', 10);
+ result.materialHandles.set('a.mat', 20);
+ result.fontHandles.set('font.fnt', 30);
+
+ assets.resolveSceneAssetPaths(scene, result);
+
+ expect(counter.getTextureRefCount('a.png')).toBe(1);
+ expect(counter.getMaterialRefCount('a.mat')).toBe(1);
+ expect(counter.getFontRefCount('font.fnt')).toBe(1);
+ });
+
+ it('is a no-op when no counter is attached', () => {
+ const assets = makeAssets();
+ // deliberately no setRefCounter
+
+ const scene = sceneWith(7, { texture: 'assets/player.png' });
+ const result = emptyResult();
+ result.textureHandles.set('assets/player.png', 42);
+
+ // Must not throw.
+ expect(() => assets.resolveSceneAssetPaths(scene, result)).not.toThrow();
+ expect(assets.getRefCounter()).toBeNull();
+ });
+
+ it('removeAllRefsForEntity cleans up after despawn', () => {
+ const counter = new AssetRefCounter();
+ counter.addTextureRef('a.png', 1);
+ counter.addTextureRef('a.png', 2);
+ counter.addMaterialRef('a.mat', 1);
+
+ counter.removeAllRefsForEntity(1);
+
+ expect(counter.getTextureRefs('a.png')).toEqual([2]);
+ expect(counter.getMaterialRefCount('a.mat')).toBe(0);
+ });
+});