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.

refactor(assets): a handle-bound asset's era owns what its load acquired

esengine4aeee3d4dad7
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 4083b1bd7..e0d30c8c2 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -769,7 +769,7 @@ ResourceDef<AssetsClass>
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
-@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
+@internal releaseTypedLease: (type: string, lease: AssetRefLease<PreparedLoad<unknown>>) => void
@internal resolveRegistryAsset: <T>(type: string, ref: string) => T | undefined
@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }
acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index cb2dcb625..d70dae3d4 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -769,7 +769,7 @@ ResourceDef<AssetsClass>
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
-@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
+@internal releaseTypedLease: (type: string, lease: AssetRefLease<PreparedLoad<unknown>>) => void
@internal resolveRegistryAsset: <T>(type: string, ref: string) => T | undefined
@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }
acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 10575cedc..3feb6d1f1 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -764,7 +764,7 @@ ResourceDef<AssetsClass>
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
-@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
+@internal releaseTypedLease: (type: string, lease: AssetRefLease<PreparedLoad<unknown>>) => void
@internal resolveRegistryAsset: <T>(type: string, ref: string) => T | undefined
@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }
acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index ed54f7e20..0eda6fd1f 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -764,7 +764,7 @@ ResourceDef<AssetsClass>
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
-@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
+@internal releaseTypedLease: (type: string, lease: AssetRefLease<PreparedLoad<unknown>>) => void
@internal resolveRegistryAsset: <T>(type: string, ref: string) => T | undefined
@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }
acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 735c6eb78..20915f1ac 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -764,7 +764,7 @@ ResourceDef<AssetsClass>
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
-@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
+@internal releaseTypedLease: (type: string, lease: AssetRefLease<PreparedLoad<unknown>>) => void
@internal resolveRegistryAsset: <T>(type: string, ref: string) => T | undefined
@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }
acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index 12793c1cb..7dc208024 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -25,9 +25,6 @@ export interface SpineLoadResult {
export interface MaterialResult {
handle: number;
shaderHandle: number;
- /** Receipts for the textures this material bound; released on unload. Not
- * paths: a hot update between load and unload makes one path name two. */
- textureLeases?: AssetLease<TextureResult>[];
/** Parent material handle for an `instanceOf` material, released on unload. */
parentHandle?: number;
}
@@ -107,12 +104,6 @@ export interface LoadContext {
* this loader was handed.
*/
acquireTexture(path: string, flipY?: boolean): Promise<AssetLease<TextureResult>>;
- /**
- * Release by path — the compatibility door for a loader that only ever had
- * one. Exact while a path names one instance; after an invalidate it gives
- * back the OLDEST era sharing the path. See {@link acquireTexture}.
- */
- releaseTexture(path: string): void;
loadText(path: string): Promise<string>;
loadBinary(path: string): Promise<ArrayBuffer>;
/**
@@ -187,9 +178,9 @@ export interface AssetLoader<T> {
readonly type: string;
readonly extensions: string[];
load?(path: string, ctx: LoadContext): Promise<T>;
- /** Free the loaded asset. `ctx` gives loaders that pulled sub-assets during
- * load (e.g. a material's bound textures) a channel to release them. */
- unload?(asset: T, ctx: LoadContext): void;
+ /** Destroy what `load` made. What it ACQUIRED is the preparation's and goes
+ * back with the era — a loader releasing it here would free it twice. */
+ unload?(asset: T): void;
/** Set instead of `load`/`unload` when the asset is published by name. */
registry?: RegistryAssetLoader<T>;
/**
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index bdc7599cf..a7994b876 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -22,7 +22,7 @@ import { AssetRefLedger, type AssetRefLease } from './AssetRefLedger';
import { AssetScope, type AssetLease } from './AssetLease';
import { EntityAssetScopes } from './entityAssetScopes';
import { RegistryAssetSlots, type RegistryAssetKind } from './registryAssets';
-import { DependencyRecorder, type DependencyReceipt, type Preparation } from './dependencies';
+import { DependencyRecorder, type DependencyReceipt, type Preparation, type PreparedLoad } from './dependencies';
import { SpineAssetLoader } from './loaders/SpineAssetLoader';
import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';
import { MeshAssetLoader } from './loaders/MeshAssetLoader';
@@ -371,12 +371,12 @@ export class Assets {
/** Handles already disowned in this epoch, so N callers sharing one load
* drop its single C++ reference once between them, not N times. */
private abandoned_ = new Set<number>();
- private genericCache_ = new Map<string, AsyncCache<unknown>>();
+ private genericCache_ = new Map<string, AsyncCache<PreparedLoad<unknown>>>();
/** Per-asset reference counts for the generic caches, keyed `type:path`.
* Same contract as textures: every load*() increments, every release*()
* decrements, and the loader's unload runs only at zero — so an asset
* shared by two scenes survives the first scene's unload. */
- private genericRefs_ = new AssetRefLedger<unknown>();
+ private genericRefs_ = new AssetRefLedger<PreparedLoad<unknown>>();
private loadContext_: LoadContext | null = null;
private assetRefResolver_: AssetRefResolver | null = null;
private assetRegistry_: AssetRegistry | null = null;
@@ -1465,7 +1465,7 @@ export class Assets {
/** {@link textureLease_} for everything that goes through a typed loader. */
private typedLease_<T>(
- type: string, lease: AssetRefLease<unknown>, value: T,
+ type: string, lease: AssetRefLease<PreparedLoad<unknown>>, value: T,
): AssetLease<T> {
return {
key: lease.key, generation: lease.generation, value,
@@ -1593,7 +1593,7 @@ export class Assets {
* @internal The typed twin of {@link releaseTextureLease}; callers use the
* lease's own `release()`.
*/
- releaseTypedLease(type: string, lease: AssetRefLease<unknown>): void {
+ releaseTypedLease(type: string, lease: AssetRefLease<PreparedLoad<unknown>>): void {
const dropped = this.genericRefs_.release(lease);
if (!dropped?.exhausted) return;
const path = lease.key.slice(type.length + 1);
@@ -1601,10 +1601,21 @@ export class Assets {
}
/** The last reference to a typed asset is gone: hand it to its loader. */
- private disposeGeneric_(type: string, path: string, value: unknown): void {
- this.loaders_.get(type)?.unload?.(value, this.getLoadContext_());
+ private disposeGeneric_(type: string, path: string, era: PreparedLoad<unknown>): void {
+ this.retire_(type, era);
const cache = this.genericCache_.get(type);
- if (cache && cache.get(path) === value) cache.delete(path);
+ if (cache && cache.get(path) === era) cache.delete(path);
+ }
+
+ /** End one handle-bound era: its loader destroys what it made, then what its
+ * preparation acquired goes back — in that order, since the value is what
+ * is still using it. */
+ private retire_(type: string, era: PreparedLoad<unknown>): void {
+ try {
+ this.loaders_.get(type)?.unload?.(era.value);
+ } finally {
+ era.dependencies.releaseAll();
+ }
}
/**
@@ -1655,7 +1666,7 @@ export class Assets {
// Generic caches: material / font / anim-clip / tilemap / timeline / audio / prefab.
for (const [type, cache] of this.genericCache_.entries()) {
- const bound = cache.get(path);
+ const bound = cache.get(path)?.value;
if (cache.invalidate(path)) { hit = true; dropped.set(type as AssetFieldType, bound); }
// The ledger stays: the outgoing generation's holders still owe a
// release. Its era is closed so the next acquire cannot join it.
@@ -1820,7 +1831,7 @@ export class Assets {
}
this.genericCache_.clear();
for (const { key, value } of this.genericRefs_.drain()) {
- this.loaders_.get(key.slice(0, key.indexOf(':')))?.unload?.(value, this.getLoadContext_());
+ this.retire_(key.slice(0, key.indexOf(':')), value);
}
this.handleToPath_.clear();
}
@@ -1989,32 +2000,38 @@ export class Assets {
private async acquireTyped_<T>(
type: string, ref: string,
- ): Promise<{ value: T; lease: AssetRefLease<unknown> }> {
+ ): Promise<{ value: T; lease: AssetRefLease<PreparedLoad<unknown>> }> {
const loader = this.loaders_.get(type) as AssetLoader<T> | undefined;
if (!loader) {
throw new Error(`No loader registered for type: ${type}`);
}
const path = this.resolveLoadPath_(ref);
-
- let cache = this.genericCache_.get(type);
- if (!cache) {
- cache = new AsyncCache<unknown>();
- this.genericCache_.set(type, cache);
- }
-
if (!loader.load) {
throw new Error(`Loader for "${type}" publishes by name; acquire it through its slot`);
}
const load = loader.load.bind(loader);
- const result = await (cache.getOrLoad(path, () =>
- load(path, this.getLoadContext_()),
- ) as Promise<T>);
- const lease = this.genericRefs_.acquire(`${type}:${path}`, result);
+ const era = await this.genericCacheFor_(type).getOrLoad(path, () =>
+ this.prepared_(async (ctx) => ({ value: await load(path, ctx) as unknown })),
+ );
+ const lease = this.genericRefs_.acquire(`${type}:${path}`, era);
+ const result = era.value as T;
const handle = (result as { handle?: unknown } | null)?.handle;
if (typeof handle === 'number' && handle !== 0) this.recordHandlePath_(type, handle, path);
return { value: result, lease };
}
+ /** The cache of current eras for one handle-bound type. A load that lands
+ * after its own deadline was never handed to anyone, so this is the last
+ * place that knows it and what it acquired. */
+ private genericCacheFor_(type: string): AsyncCache<PreparedLoad<unknown>> {
+ let cache = this.genericCache_.get(type);
+ if (!cache) {
+ cache = new AsyncCache<PreparedLoad<unknown>>((era) => this.retire_(type, era));
+ this.genericCache_.set(type, cache);
+ }
+ return cache;
+ }
+
/**
* What THIS realm publishes for a ref-bound asset — the answer a runtime
* lookup reads, and the only copy of it.
@@ -2037,7 +2054,11 @@ export class Assets {
*/
dependenciesOf(type: string, ref: string): readonly DependencyReceipt[] {
const own = this.registrySlots_.dependenciesOf(type, ref);
- return own.length > 0 ? own : this.registrySlots_.dependenciesOf(type, this.resolveLoadPath_(ref));
+ if (own.length > 0) return own;
+ const path = this.resolveLoadPath_(ref);
+ const byPath = this.registrySlots_.dependenciesOf(type, path);
+ if (byPath.length > 0) return byPath;
+ return this.genericCache_.get(type)?.get(path)?.edges ?? [];
}
/**
@@ -2116,9 +2137,6 @@ export class Assets {
const { result, lease } = await self.acquireTextureVariant_(path, flipY !== false);
return self.textureLease_(lease, result);
},
- releaseTexture(path: string): void {
- self.releaseTexture(path);
- },
async loadText(path: string): Promise<string> {
return self.backend.fetchText(self.backend.resolveUrl(path));
},
diff --git a/sdk/src/asset/dependencies.ts b/sdk/src/asset/dependencies.ts
index 1416fe9ab..3fb35cf24 100644
--- a/sdk/src/asset/dependencies.ts
+++ b/sdk/src/asset/dependencies.ts
@@ -54,6 +54,13 @@ export interface Preparation {
readonly edges: readonly DependencyReceipt[];
}
+/**
+ * What a handle-bound load produced, and what its preparation took — the same
+ * sealing an era gets, for the asset kind whose current value lives in a cache
+ * rather than under a slot's name.
+ */
+export type PreparedLoad<T> = Preparation & { readonly value: T };
+
/**
* The recorder behind one preparation: everything it acquires lands here, so
* neither the era's ownership nor the graph's edges depend on a loader
diff --git a/sdk/src/asset/loaders/EnvironmentAssetLoader.ts b/sdk/src/asset/loaders/EnvironmentAssetLoader.ts
index 2f53f1a65..e3daf6d90 100644
--- a/sdk/src/asset/loaders/EnvironmentAssetLoader.ts
+++ b/sdk/src/asset/loaders/EnvironmentAssetLoader.ts
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { AssetLoader, LoadContext, TextureResult } from '../AssetLoader';
-import type { AssetLease } from '../AssetLease';
+import type { AssetLoader, LoadContext } from '../AssetLoader';
import { resolveDocumentRef } from '../documentRef';
import type { EngineApi } from '../../ecs/bridge/engineApi';
import { marshallingCore } from './engineCore';
@@ -22,17 +21,14 @@ interface EnvironmentAssetData {
/** A baked environment, named by the handle a Light references. */
export interface EnvironmentResult {
handle: number;
- /** The receipt for the atlas, so unload gives back the era this load took —
- * a path names two of them once a hot update has landed. */
- specularLease?: AssetLease<TextureResult>;
}
/**
* Loads `.esenv` — an environment's irradiance and its prefiltered reflection.
*
- * The reflection is an ordinary texture asset, loaded through the same door as
- * any other: the environment holds a ref to it while it lives, and gives it back
- * on unload. Only the nine coefficients are the environment's own.
+ * The reflection is an ordinary texture asset, acquired through the same door as
+ * any other — so the preparation holds the receipt and the era gives it back.
+ * Only the nine coefficients are the environment's own.
*/
export class EnvironmentAssetLoader implements AssetLoader<EnvironmentResult> {
readonly type = 'environment';
@@ -57,15 +53,13 @@ export class EnvironmentAssetLoader implements AssetLoader<EnvironmentResult> {
// the load: nine coefficients still light the scene, and a reflection that
// silently took the whole asset down would be the worse answer.
let specularHandle = 0;
- let specularLease: AssetLease<TextureResult> | undefined;
if (data.specular) {
const resolved = resolveDocumentRef(path, data.specular);
try {
// flipY false: the atlas' rows are a layout, not a picture. Row 0
// is mip 0, and a load that turned it over would put the mip
// offsets — and every face's v — upside down.
- specularLease = await ctx.acquireTexture(resolved, false);
- specularHandle = specularLease.value.handle;
+ specularHandle = (await ctx.acquireTexture(resolved, false)).value.handle;
} catch (e) {
log.warn('asset', `${path}: no reflection atlas at '${resolved}'`, e);
}
@@ -79,15 +73,13 @@ export class EnvironmentAssetLoader implements AssetLoader<EnvironmentResult> {
});
if (!handle) {
- specularLease?.release();
throw new Error(`the engine rejected the environment in ${path}`);
}
- return { handle, specularLease };
+ return { handle };
}
unload(asset: EnvironmentResult): void {
this.core_()?.environment_release?.(asset.handle);
- asset.specularLease?.release();
}
}
diff --git a/sdk/src/asset/loaders/MaterialAssetLoader.ts b/sdk/src/asset/loaders/MaterialAssetLoader.ts
index e7ffce218..8a1e469bf 100644
--- a/sdk/src/asset/loaders/MaterialAssetLoader.ts
+++ b/sdk/src/asset/loaders/MaterialAssetLoader.ts
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { AssetLoader, LoadContext, MaterialResult, TextureResult } from '../AssetLoader';
-import type { AssetLease } from '../AssetLease';
+import type { AssetLoader, LoadContext, MaterialResult } from '../AssetLoader';
import { BUILTIN_REF_PREFIX, isBuiltinAssetRef, resolveDocumentRef } from '../documentRef';
import type { MaterialAssetData, ShaderHandle } from '../../render/material';
import { Material } from '../../render/material';
@@ -31,54 +30,43 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {
const parentPath = resolveDocumentRef(path, data.instanceOf);
const parent = await this.load(parentPath, ctx);
const handle = Material.createFromAsset(data, 0, parent.handle);
- const textureLeases = await this.applyTextureProps(handle, data, path, ctx);
- return {
- handle,
- shaderHandle: parent.shaderHandle,
- textureLeases: [...(parent.textureLeases ?? []), ...textureLeases],
- parentHandle: parent.handle,
- };
+ await this.applyTextureProps(handle, data, path, ctx);
+ return { handle, shaderHandle: parent.shaderHandle, parentHandle: parent.handle };
}
// Enabled static switches select the shader permutation (compiled once per switch-set).
const features = enabledSwitches(data.switches);
const shaderHandle = await this.loadShader(path, data.shader, features, ctx);
const handle = Material.createFromAsset(data, shaderHandle);
- const textureLeases = await this.applyTextureProps(handle, data, path, ctx);
+ await this.applyTextureProps(handle, data, path, ctx);
- return { handle, shaderHandle, textureLeases };
+ return { handle, shaderHandle };
}
// A texture param is a string property (an asset ref); scalar/vector params are
- // numbers/objects (handled by createFromAsset). Bind each texture and keep its
- // RECEIPT, so unload gives back the era this material bound rather than
- // whichever one shares its path by then.
+ // numbers/objects (handled by createFromAsset). The acquisition holds the
+ // receipt — this material's era gives it back — so binding is all there is
+ // to do here.
private async applyTextureProps(
handle: number,
data: MaterialAssetData,
matPath: string,
ctx: LoadContext,
- ): Promise<AssetLease<TextureResult>[]> {
- const bound: AssetLease<TextureResult>[] = [];
+ ): Promise<void> {
for (const [name, value] of Object.entries(data.properties)) {
if (typeof value !== 'string') continue;
const texPath = resolveDocumentRef(matPath, value);
try {
const tex = await ctx.acquireTexture(texPath);
Material.setUniform(handle, name, Material.tex(tex.value.handle));
- bound.push(tex); // recorded only on success — matches the acquisition taken
} catch (e) {
// Missing texture: leave the param unbound (it samples whatever is at the unit).
log.warn('asset', `Material ${matPath}: failed to load texture '${texPath}' for param '${name}'`, e);
}
}
- return bound;
}
unload(asset: MaterialResult): void {
- if (asset.textureLeases) {
- for (const lease of asset.textureLeases) lease.release();
- }
if (asset.parentHandle !== undefined) Material.release(asset.parentHandle);
Material.release(asset.handle);
}
diff --git a/sdk/tests/asset-dependencies.test.ts b/sdk/tests/asset-dependencies.test.ts
index 69bd1a35f..d084411b6 100644
--- a/sdk/tests/asset-dependencies.test.ts
+++ b/sdk/tests/asset-dependencies.test.ts
@@ -62,6 +62,16 @@ const platformFactory = vi.hoisted(() => () => ({
vi.mock('../src/platform', platformFactory);
vi.mock('../src/platform/base', platformFactory);
+vi.mock('../src/render/material', () => ({
+ Material: {
+ createFromAsset: vi.fn(() => 11),
+ setUniform: vi.fn(),
+ tex: vi.fn((handle: number) => ({ kind: 'tex', handle })),
+ compileShader: vi.fn(() => 7),
+ release: vi.fn(),
+ },
+}));
+
/** A `.tmj` whose one tileset lives in an external `.tsj`. */
const MAP_WITH_EXTERNAL = JSON.stringify({
width: 1, height: 1, tilewidth: 4, tileheight: 4,
@@ -81,6 +91,11 @@ const MAP_WITH_COLLECTION = JSON.stringify({
layers: [{ type: 'tilelayer', name: 'g', width: 1, height: 1, data: [1] }],
});
+/** A material binding one texture, on a built-in shader (no shader file). */
+const MATERIAL = JSON.stringify({
+ type: 'material', shader: 'builtin:sprite-unlit', properties: { mainTex: 'wall.png' },
+});
+
function realm(docs: Record<string, string>): Assets {
const assets = Assets.create({
backend: {
@@ -204,3 +219,83 @@ describe('a preparation is a transaction', () => {
expect(assets.resolveRegistryAsset('brittle', 'x.brittle')).toBeUndefined();
});
});
+
+describe('a handle-bound load is a preparation too', () => {
+ beforeEach(() => { pool = createPoolFake(); });
+
+ /** A loader whose asset a component holds BY HANDLE, binding one texture. */
+ function gadget(assets: Assets, opts: { fail?: boolean } = {}): void {
+ assets.register<{ handle: number }>({
+ type: 'gadget',
+ extensions: ['.gadget'],
+ load: async (_path, ctx) => {
+ const tex = await ctx.acquireTexture('g.png');
+ if (opts.fail) throw new Error('load failed');
+ return { handle: tex.value.handle };
+ },
+ unload: () => {},
+ });
+ }
+
+ it('the texture it bound is an owned dependency of it', async () => {
+ // Nothing about a dependency is registry-shaped: what makes the edge is
+ // the acquisition, and a handle-bound asset acquires the same way.
+ const assets = realm({});
+ gadget(assets);
+ await assets.acquireTyped('gadget', 'x.gadget');
+
+ expect(assets.dependenciesOf('gadget', 'x.gadget'))
+ .toContainEqual({ kind: 'owned', type: 'texture', path: 'g.png' });
+ });
+
+ it('the last holder giving it back gives back what its preparation took', async () => {
+ const assets = realm({});
+ gadget(assets);
+ const held = await assets.acquireTyped('gadget', 'x.gadget');
+ expect(pool.liveTextures()).toBe(1);
+
+ held.release();
+ expect(pool.liveTextures(), 'the texture the load took').toBe(0);
+ expect(assets.dependenciesOf('gadget', 'x.gadget')).toEqual([]);
+ });
+
+ it('a load that throws keeps nothing it acquired', async () => {
+ const assets = realm({});
+ gadget(assets, { fail: true });
+ const base = assets.sizes().refRows;
+
+ await expect(assets.acquireTyped('gadget', 'x.gadget')).rejects.toThrow('load failed');
+
+ expect(pool.liveTextures(), 'the texture the failed load took').toBe(0);
+ expect(assets.sizes().refRows).toBe(base);
+ });
+});
+
+describe('a handle-bound loader owns nothing of its own', () => {
+ beforeEach(() => { pool = createPoolFake(); });
+
+ it('a material\'s bound texture is its era\'s, and goes back with it', async () => {
+ // The receipts are the era's, not a field the loader keeps beside its
+ // result and remembers to hand back.
+ const assets = realm({ 'hero.esmaterial': MATERIAL });
+ const held = await assets.acquireTyped('material', 'materials/hero.esmaterial');
+ expect(pool.liveTextures()).toBe(1);
+
+ expect(assets.dependenciesOf('material', 'materials/hero.esmaterial'))
+ .toContainEqual({ kind: 'owned', type: 'texture', path: 'materials/wall.png' });
+
+ held.release();
+ expect(pool.liveTextures(), 'the texture the material bound').toBe(0);
+ });
+
+ it('two holders keep it, and the last one lets it go', async () => {
+ const assets = realm({ 'hero.esmaterial': MATERIAL });
+ const first = await assets.acquireTyped('material', 'materials/hero.esmaterial');
+ const second = await assets.acquireTyped('material', 'materials/hero.esmaterial');
+
+ first.release();
+ expect(pool.liveTextures(), 'released while a holder was still using it').toBe(1);
+ second.release();
+ expect(pool.liveTextures()).toBe(0);
+ });
+});
diff --git a/sdk/tests/material-asset-loader.test.ts b/sdk/tests/material-asset-loader.test.ts
index 63841a8a6..207db4a4d 100644
--- a/sdk/tests/material-asset-loader.test.ts
+++ b/sdk/tests/material-asset-loader.test.ts
@@ -63,7 +63,7 @@ describe('MaterialAssetLoader texture failure', () => {
});
});
-describe('MaterialAssetLoader texture release on unload', () => {
+describe('MaterialAssetLoader ownership on unload', () => {
beforeEach(() => {
vi.clearAllMocks();
(Material.createFromAsset as ReturnType<typeof vi.fn>).mockReturnValue(11);
@@ -90,20 +90,17 @@ describe('MaterialAssetLoader texture release on unload', () => {
return { ctx, released };
}
- it('keeps the RECEIPT for each bound texture and gives it back on unload', async () => {
+ it('destroys what it made and gives back nothing it acquired', async () => {
+ // The era that acquired it gives it back; releasing here frees it twice.
+ // That it DOES come back is asserted in asset-dependencies.test.ts.
const loader = new MaterialAssetLoader();
const { ctx, released } = makeCtxWithTexture();
const result = await loader.load(MAT_PATH, ctx);
- // The acquisition is recorded, not the path: a hot update between load
- // and unload makes one path name two eras, and a release addressed by
- // path gives back the older one — a stranger's.
- expect(result.textureLeases?.map((l) => l.key))
- .toEqual(['texture:assets/materials/missing.png']);
expect(Material.setUniform).toHaveBeenCalled();
- loader.unload(result, ctx);
- expect(released).toEqual([{ key: 'texture:assets/materials/missing.png', generation: 1 }]);
+ loader.unload(result);
+ expect(released, 'the loader released a receipt it does not own').toEqual([]);
expect(Material.release).toHaveBeenCalledWith(11);
});
});