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): a dependency edge is recorded by the acquisition that made it
esengine520906ab9e56
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 37edb7a55..4083b1bd7 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -764,6 +764,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal entityScopes: EntityAssetScopes@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex ac700ab6f..cb2dcb625 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -764,6 +764,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal entityScopes: EntityAssetScopes@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex cae643246..10575cedc 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -759,6 +759,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal entityScopes: EntityAssetScopes@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 8388e26d0..ed54f7e20 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -759,6 +759,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal entityScopes: EntityAssetScopes@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 58c2b6b5c..735c6eb78 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -759,6 +759,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal entityScopes: EntityAssetScopes@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => voiddiff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.tsindex bd018583d..12793c1cb 100644--- a/sdk/src/asset/AssetLoader.ts+++ b/sdk/src/asset/AssetLoader.ts@@ -138,6 +138,14 @@ export interface LoadContext {createOwnedTexture?(width: number, height: number, pixels: Uint8Array, flipY: boolean,): Promise<AssetLease<TextureResult>>;+ /**+ * Read another asset's content because it shapes what this one becomes — a+ * `.tsj` folded into a `.tmj`.+ *+ * Nothing is held; what is recorded is that this asset must be rebuilt when+ * that content changes. A log setting read during a load is not one.+ */+ readSource?(path: string): Promise<string>;/*** Audio API for the owning app, resolved lazily so that* AudioPlugin / AssetPlugin can be installed in either order.diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex fe4577f4f..d871abdcd 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -22,6 +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 } from './dependencies';import { SpineAssetLoader } from './loaders/SpineAssetLoader';import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';import { MeshAssetLoader } from './loaders/MeshAssetLoader';@@ -2028,6 +2029,17 @@ export class Assets {?? this.registrySlots_.published(type, this.resolveLoadPath_(ref))) as T | undefined;}+ /**+ * What the current era of a ref-bound asset took — the dependency graph as a+ * PROJECTION of acquisitions, never a table anyone maintains.+ *+ * @internal+ */+ 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));+ }+/*** Everything this realm publishes of one type. What a schedule analysis* reads to learn what the graphs THIS app loaded reach for.@@ -2047,7 +2059,35 @@ export class Assets {const loader = this.loaders_.get(type) as AssetLoader<T> | undefined;const registry = loader?.registry;if (!registry) return null;- return { prepare: (path) => registry.prepare(path, this.getLoadContext_()) };+ return {+ prepare: async (path) => {+ // One recorder per preparation: what the loader takes IS the+ // era's ownership and IS the graph's edges, so neither can be+ // a description it forgot to keep in step with its work.+ const recorder = new DependencyRecorder();+ const era = await registry.prepare(path, this.recordingContext_(recorder));+ return { ...era, dependencies: recorder.acquired, edges: recorder.edges };+ },+ };+ }++ /** The load context one preparation sees: every door that takes something+ * reports it, and the plain readers stay plain. */+ private recordingContext_(recorder: DependencyRecorder): LoadContext {+ const base = this.getLoadContext_();+ return {+ ...base,+ acquireTexture: async (path, flipY) =>+ recorder.own(path, await base.acquireTexture(path, flipY), 'texture'),+ createOwnedTexture: async (width, height, pixels, flipY) => {+ const lease = await base.createOwnedTexture!(width, height, pixels, flipY);+ return recorder.own(`composed:${lease.value.handle}`, lease);+ },+ readSource: async (path) => {+ recorder.read(path);+ return base.loadText(path);+ },+ };}private getLoadContext_(): LoadContext {diff --git a/sdk/src/asset/dependencies.ts b/sdk/src/asset/dependencies.tsnew file mode 100644index 000000000..61c1a24d1--- /dev/null+++ b/sdk/src/asset/dependencies.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file dependencies.ts+ * @brief What one asset's preparation took, and what it merely read.+ *+ * @details A dependency graph is a PROJECTION of what actually happened, never a+ * second source of fact. So an edge is not something a loader declares+ * beside its work — it is recorded by the door the loader went through+ * to do the work, and a loader that took nothing produces no edges no+ * matter what it says.+ *+ * Two kinds, and the difference matters:+ *+ * `owned` — the preparation acquired a runtime resource and holds it.+ * A receipt proves it, the era gives it back, and the child cannot go+ * away underneath the parent.+ *+ * `source` — the preparation READ another asset's content to decide+ * what to produce (an external `.tsj` folded into a `.tmj`). Nothing is+ * held: the parent owns no runtime object for it, and destroying+ * anything on its behalf would be wrong. It is causality, not+ * ownership — the reason the parent must be rebuilt when it changes.+ *+ * A source edge exists iff changing that content may invalidate the+ * parent's semantic value. Reading a log setting or an editor+ * preference during a load is not a dependency.+ *+ * Cycles are not refused here. `A imports B` while `B`'s metadata names+ * `A` is a real shape; what has to be acyclic is a BUILD PLAN, which is+ * this graph's condensation and not this graph.+ */+import type { AssetLease } from './AssetLease';+import { AssetScope } from './AssetLease';++export type DependencyKind = 'owned' | 'source';++/** One edge, as the acquisition that produced it named its other end. */+export interface DependencyReceipt {+ readonly kind: DependencyKind;+ /** The asset type when the acquisition had one; a source read and a+ * composed resource are identified by their path alone. */+ readonly type?: string;+ /** The identity within this realm: what the acquisition asked for. */+ readonly path: string;+}++/**+ * 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+ * remembering to report anything.+ */+export class DependencyRecorder {+ private readonly edges_: DependencyReceipt[] = [];+ readonly acquired = new AssetScope();++ /** A runtime resource this preparation now holds. */+ own<T>(path: string, lease: AssetLease<T>, type?: string): AssetLease<T> {+ this.acquired.add(lease);+ this.edges_.push(type === undefined ? { kind: 'owned', path } : { kind: 'owned', type, path });+ return lease;+ }++ /** Content this preparation read to decide what to produce. */+ read(path: string): void {+ this.edges_.push({ kind: 'source', path });+ }++ /** What this preparation took, in the order it took it. */+ get edges(): readonly DependencyReceipt[] {+ return this.edges_;+ }+}diff --git a/sdk/src/asset/loaders/AnimClipAssetLoader.ts b/sdk/src/asset/loaders/AnimClipAssetLoader.tsindex eb46d2085..5105372c5 100644--- a/sdk/src/asset/loaders/AnimClipAssetLoader.ts+++ b/sdk/src/asset/loaders/AnimClipAssetLoader.ts@@ -11,7 +11,6 @@*/import type { AssetLoader, LoadContext, AnimClipResult, RegistryAssetLoader } from '../AssetLoader';import type { RegistryEra } from '../registryAssets';-import { AssetScope } from '../AssetLease';import { extractAnimClipTexturePaths, parseAnimClipAsset, parseAnimClipData } from '../../animation/AnimClipLoader';import { log } from '../../util/logger';@@ -23,13 +22,11 @@ export class AnimClipAssetLoader implements AssetLoader<AnimClipResult> {prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<AnimClipResult>> => {const text = await ctx.loadText(ctx.catalog.getBuildPath(path));const data = parseAnimClipAsset(JSON.parse(text));- const dependencies = new AssetScope();const textureHandles = new Map<string, number>();for (const texPath of extractAnimClipTexturePaths(data)) {try {const lease = await ctx.acquireTexture(texPath, true);- dependencies.add(lease);textureHandles.set(texPath, lease.value.handle);} catch (e) {log.warn('asset', `Failed to load texture: ${texPath}`, e);@@ -39,7 +36,6 @@ export class AnimClipAssetLoader implements AssetLoader<AnimClipResult> {return {published: parseAnimClipData(path, data, textureHandles),value: { clipId: path },- dependencies,};},// Nothing: the slot holds the era, and this app's sprite animationdiff --git a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.tsindex 82d8d1bbc..3dd2358ef 100644--- a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts+++ b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts@@ -12,7 +12,6 @@ import type {AssetLoader, LoadContext, AnimatorControllerResult, RegistryAssetLoader,} from '../AssetLoader';import type { RegistryEra } from '../registryAssets';-import { AssetScope } from '../AssetLease';import type { AnimatorControllerDef } from '../../animation/Animator';export class AnimatorControllerAssetLoader implements AssetLoader<AnimatorControllerResult> {@@ -25,7 +24,6 @@ export class AnimatorControllerAssetLoader implements AssetLoader<AnimatorControreturn {published: JSON.parse(text) as AnimatorControllerDef,value: { controllerId: path },- dependencies: new AssetScope(),};},};diff --git a/sdk/src/asset/loaders/BtAssetLoader.ts b/sdk/src/asset/loaders/BtAssetLoader.tsindex 465d90496..8a6996c2b 100644--- a/sdk/src/asset/loaders/BtAssetLoader.ts+++ b/sdk/src/asset/loaders/BtAssetLoader.ts@@ -10,7 +10,6 @@*/import type { AssetLoader, LoadContext, BtResult, RegistryAssetLoader } from '../AssetLoader';import type { RegistryEra } from '../registryAssets';-import { AssetScope } from '../AssetLease';import type { BtDefinition } from '../../ai/bt/types';export class BtAssetLoader implements AssetLoader<BtResult> {@@ -23,7 +22,6 @@ export class BtAssetLoader implements AssetLoader<BtResult> {return {published: JSON.parse(text) as BtDefinition,value: { btId: path },- dependencies: new AssetScope(),};},// Nothing: the slot holds the era, and this realm's lookup reads itdiff --git a/sdk/src/asset/loaders/FsmAssetLoader.ts b/sdk/src/asset/loaders/FsmAssetLoader.tsindex 91e09d3cc..a061d5c1c 100644--- a/sdk/src/asset/loaders/FsmAssetLoader.ts+++ b/sdk/src/asset/loaders/FsmAssetLoader.ts@@ -11,7 +11,6 @@*/import type { AssetLoader, LoadContext, FsmResult, RegistryAssetLoader } from '../AssetLoader';import type { RegistryEra } from '../registryAssets';-import { AssetScope } from '../AssetLease';import { compileFsm } from '../../ai/fsm/FsmRunner';import type { FsmDefinition } from '../../ai/fsm/types';@@ -25,7 +24,7 @@ export class FsmAssetLoader implements AssetLoader<FsmResult> {const def = JSON.parse(text) as FsmDefinition;// Compiled once per era, not once per name: the names are the same// machine, and two compilations of it are two machines.- return { published: compileFsm(def), value: { fsmId: path }, dependencies: new AssetScope() };+ return { published: compileFsm(def), value: { fsmId: path } };},// Nothing: the slot holds the era, and this realm's lookup reads it// there. Writing a module-global store as well is what let one appdiff --git a/sdk/src/asset/loaders/TilemapAssetLoader.ts b/sdk/src/asset/loaders/TilemapAssetLoader.tsindex 0f47c8bd4..e2ca14445 100644--- a/sdk/src/asset/loaders/TilemapAssetLoader.ts+++ b/sdk/src/asset/loaders/TilemapAssetLoader.ts@@ -2,7 +2,6 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { AssetLoader, LoadContext, TilemapResult, RegistryAssetLoader } from '../AssetLoader';import type { RegistryEra } from '../registryAssets';-import { AssetScope } from '../AssetLease';import {packCollectionGrid, parseTmjWithExternals, resolveTiledRef,type TiledMapData, type TiledTilesetData,@@ -31,26 +30,34 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {}// External .tsj tilesets resolve relative to the map, through the same// text channel as the map itself.+ // An external `.tsj` is not something this map holds — no runtime object+ // — but folding it in decides what the map IS, so a change to it has to+ // reach this map. That is a source acquisition.+ const readSource = ctx.readSource;+ if (!readSource) {+ throw new Error(+ `[tilemap] "${path}": this asset provider cannot read a dependency, so an `+ + 'external .tsj could be folded in with nothing recording that the map '+ + 'depends on it — load it through the app Assets channel.');+ }const mapData = await parseTmjWithExternals(JSON.parse(text), (source) =>- ctx.loadText(ctx.catalog.getBuildPath(resolveTiledRef(path, source))));+ readSource(ctx.catalog.getBuildPath(resolveTiledRef(path, source))));if (!mapData) {throw new Error(`Failed to parse tilemap: ${path}`);}- const dependencies = new AssetScope();const tilesets = [];for (const ts of mapData.tilesets) {// Image-collection tileset: fold the loose per-tile images into one// grid atlas — from here on it IS a grid tileset to everyone.if (ts.collectionTiles?.length) {- tilesets.push(await this.foldCollection_(path, ts, mapData, ctx, dependencies));+ tilesets.push(await this.foldCollection_(path, ts, mapData, ctx));continue;}const imagePath = resolveTiledRef(path, ts.image);let textureHandle = 0;try {const lease = await ctx.acquireTexture(imagePath, true);- dependencies.add(lease);textureHandle = lease.value.handle;} catch (e) {// Loud, with the fix: a dead tileset texture makes every tile that@@ -97,7 +104,7 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {objectGroups: mapData.objectGroups,} };- return { published, value: { sourceId: path }, dependencies };+ return { published, value: { sourceId: path } };}/**@@ -109,7 +116,6 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {*/private async foldCollection_(mapPath: string, ts: TiledTilesetData, mapData: TiledMapData, ctx: LoadContext,- dependencies: AssetScope,): Promise<LoadedTilemapTileset> {if (!ctx.decodePixels || !ctx.createOwnedTexture) {throw new Error(@@ -131,7 +137,6 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {// The atlas is composed here and exists for this era only: nothing else// can name it, so nothing else could ever give it back.const atlas = await ctx.createOwnedTexture(grid.width, grid.height, grid.pixels, true);- dependencies.add(atlas);// A folded image-collection atlas is packed gapless, so no margin/spacing.return {textureHandle: atlas.value.handle, columns: grid.columns, rows: grid.rows,diff --git a/sdk/src/asset/loaders/TilesetAssetLoader.ts b/sdk/src/asset/loaders/TilesetAssetLoader.tsindex 339900b01..675521366 100644--- a/sdk/src/asset/loaders/TilesetAssetLoader.ts+++ b/sdk/src/asset/loaders/TilesetAssetLoader.ts@@ -10,7 +10,6 @@*/import type { AssetLoader, LoadContext, TilesetResult, RegistryAssetLoader } from '../AssetLoader';import type { RegistryEra } from '../registryAssets';-import { AssetScope } from '../AssetLease';import { parseTileset } from '../../tilemap/tilesetAsset';import type { PublishedTileset } from '../../tilemap/tilesetCache';import { log } from '../../util/logger';@@ -23,7 +22,6 @@ export class TilesetAssetLoader implements AssetLoader<TilesetResult> {prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<TilesetResult>> => {const text = await ctx.loadText(ctx.catalog.getBuildPath(path));const asset = parseTileset(JSON.parse(text));- const dependencies = new AssetScope();// The atlas is a `@uuid:` ref inside the .estileset; the acquire resolves it.let textureHandle = 0;@@ -32,7 +30,6 @@ export class TilesetAssetLoader implements AssetLoader<TilesetResult> {if (asset.texture) {try {const lease = await ctx.acquireTexture(asset.texture, true);- dependencies.add(lease);textureHandle = lease.value.handle;textureWidth = lease.value.width;textureHeight = lease.value.height;@@ -43,7 +40,7 @@ export class TilesetAssetLoader implements AssetLoader<TilesetResult> {const published: PublishedTileset = {resolved: { asset, textureHandle, textureWidth, textureHeight },};- return { published, value: { tilesetId: path }, dependencies };+ return { published, value: { tilesetId: path } };},};}diff --git a/sdk/src/asset/loaders/TimelineAssetLoader.ts b/sdk/src/asset/loaders/TimelineAssetLoader.tsindex 158e27142..b7c4fa091 100644--- a/sdk/src/asset/loaders/TimelineAssetLoader.ts+++ b/sdk/src/asset/loaders/TimelineAssetLoader.ts@@ -8,7 +8,6 @@*/import type { AssetLoader, LoadContext, TimelineResult, RegistryAssetLoader } from '../AssetLoader';import type { RegistryEra } from '../registryAssets';-import { AssetScope } from '../AssetLease';import { parseTimelineAsset, extractTimelineAssetPaths } from '../../timeline/TimelineLoader';import type { PublishedTimeline } from '../../timeline/TimelineTypes';import { log } from '../../util/logger';@@ -21,13 +20,11 @@ export class TimelineAssetLoader implements AssetLoader<TimelineResult> {prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<TimelineResult>> => {const text = await ctx.loadText(ctx.catalog.getBuildPath(path));const asset = parseTimelineAsset(JSON.parse(text));- const dependencies = new AssetScope();const textureHandles = new Map<string, number>();for (const texPath of extractTimelineAssetPaths(asset).textures) {try {const lease = await ctx.acquireTexture(texPath, true);- dependencies.add(lease);textureHandles.set(texPath, lease.value.handle);} catch (e) {log.warn('asset', `Failed to load texture: ${texPath}`, e);@@ -35,7 +32,7 @@ export class TimelineAssetLoader implements AssetLoader<TimelineResult> {}}const published: PublishedTimeline = { asset, textureHandles };- return { published, value: { timelineId: path }, dependencies };+ return { published, value: { timelineId: path } };},// Nothing: the slot holds the era, and the timeline system reads it// there. A module-level "active registry" answered with whichever appdiff --git a/sdk/src/asset/registryAssets.ts b/sdk/src/asset/registryAssets.tsindex 9ae76c363..2fc8c26a8 100644--- a/sdk/src/asset/registryAssets.ts+++ b/sdk/src/asset/registryAssets.ts@@ -23,22 +23,30 @@* today that is only prevented by the file extensions differing.*/import type { AssetLease } from './AssetLease';+import type { DependencyReceipt } from './dependencies';import { AssetScope } from './AssetLease';-/** One era of a registry-backed asset. */+/** What one preparation PRODUCED. What it took is recorded for it — see+ * dependencies.ts — so an era cannot describe a dependency it does not have. */export interface RegistryEra<T> {/** The runtime object a lookup returns while this era is the published one. */readonly published: unknown;/** The logical identity a holder keeps — the same across every era. */readonly value: T;+}++/** One era, with what its preparation took. */+export interface PreparedEra<T> extends RegistryEra<T> {/** What this era acquired for itself; released when it retires. */readonly dependencies: AssetScope;+ /** Every edge the preparation produced, owned and source alike. */+ readonly edges: readonly DependencyReceipt[];}/** How one kind of registry-backed asset is prepared. Publishing is the slot's:* it holds the era and answers the lookup, so there is nowhere else to write. */export interface RegistryAssetKind<T> {- prepare(path: string): Promise<RegistryEra<T>>;+ prepare(path: string): Promise<PreparedEra<T>>;}/** A holder's claim on a slot. Its `generation` names the SLOT, not an era —@@ -57,8 +65,8 @@ class Slot<T> {* holds: a registry answers to a ref, not to an ownership identity. */readonly names: string[] = [];refs = 0;- era: RegistryEra<T> | null = null;- loading: Promise<RegistryEra<T>> | null = null;+ era: PreparedEra<T> | null = null;+ loading: Promise<PreparedEra<T>> | null = null;constructor(readonly type: string, readonly key: string, readonly id: number) {}}@@ -91,7 +99,7 @@ export class RegistryAssetSlots {if (!slot.era) {slot.loading ??= kind.prepare(key);- let era: RegistryEra<T>;+ let era: PreparedEra<T>;try {era = await slot.loading;} catch (e) {@@ -135,6 +143,12 @@ export class RegistryAssetSlots {return this.byName_.has(lookupKey(type, name));}+ /** What the current era of (type, name) took — the graph, as a projection+ * of acquisitions rather than a table anyone maintains. */+ dependenciesOf(type: string, name: string): readonly DependencyReceipt[] {+ return this.byName_.get(lookupKey(type, name))?.era?.edges ?? [];+ }+/*** What this realm publishes for (type, name) right now — the answer a* runtime lookup reads, and the only copy of it.diff --git a/sdk/tests/asset-dependencies.test.ts b/sdk/tests/asset-dependencies.test.tsnew file mode 100644index 000000000..185cb1571--- /dev/null+++ b/sdk/tests/asset-dependencies.test.ts@@ -0,0 +1,163 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file asset-dependencies.test.ts+ * @brief What an asset's preparation took, as the acquisitions themselves say.+ *+ * @details An edge is a projection of what happened, not a description kept+ * beside the work: a loader has no door for declaring one, and the+ * doors it does have record what they hand over. Two kinds, and the+ * difference is the whole point — `owned` is a runtime resource the era+ * holds, `source` is content that decided what the era became.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Assets } from '../src/asset/Assets';+import { Catalog } from '../src/asset/Catalog';+import type { Backend } from '../src/asset/Backend';++function createPoolFake() {+ const live = new Set<number>();+ const byPath = new Map<string, number>();+ let next = 1;+ return {+ budget: 0,+ createTexture: vi.fn((): number => { const h = next++; live.add(h); return h; }),+ createTextureFromBytes: vi.fn((): number => { const h = next++; live.add(h); return h; }),+ registerTextureWithPath: vi.fn((handle: number, path: string) => { byPath.set(path, handle); }),+ acquireTextureByPath: vi.fn((path: string): number => byPath.get(path) ?? 0),+ invalidateTexturePath: vi.fn((path: string): boolean => byPath.delete(path)),+ releaseTexture: vi.fn((handle: number) => { live.delete(handle); }),+ getTextureDimensions: vi.fn(() => ({ width: 4, height: 4 })),+ getTextureGLId: vi.fn(() => 1),+ setTextureMetadata: vi.fn(),+ liveTextures: () => live.size,+ };+}+let pool = createPoolFake();+vi.mock('../src/wasm/resourceManager', () => ({+ requireResourceManager: () => pool,+ getResourceManager: () => pool,+ evictTextureDimensions: vi.fn(),+}));++const platformFactory = vi.hoisted(() => () => ({+ platformCreateCanvas: () => ({+ width: 4, height: 4,+ getContext: () => ({+ clearRect: vi.fn(), drawImage: vi.fn(),+ getImageData: () => ({ data: { buffer: new ArrayBuffer(64) } }),+ }),+ }),+ platformCreateImage: () => {+ const img: { width?: number; height?: number; onload?: () => void } = {};+ setTimeout(() => { img.width = 4; img.height = 4; img.onload?.(); }, 0);+ return img;+ },+ platformFetch: vi.fn(), platformReadFile: vi.fn(),+ platformReadTextFile: vi.fn(), platformFileExists: vi.fn(),+ platformLoadSubpackage: vi.fn(async () => {}),+ platformGetStorageItem: () => null, platformSetStorageItem: vi.fn(),+ platformWriteCacheFile: vi.fn(async () => {}),+}));+vi.mock('../src/platform', platformFactory);+vi.mock('../src/platform/base', platformFactory);++/** A `.tmj` whose one tileset lives in an external `.tsj`. */+const MAP_WITH_EXTERNAL = JSON.stringify({+ width: 1, height: 1, tilewidth: 4, tileheight: 4,+ tilesets: [{ firstgid: 1, source: 'terrain.tsj' }],+ layers: [{ type: 'tilelayer', name: 'g', width: 1, height: 1, data: [1] }],+});+const EXTERNAL_TILESET = JSON.stringify({+ name: 'terrain', image: 'terrain.png', columns: 2, tilecount: 4,+ tilewidth: 4, tileheight: 4,+});+const MAP_WITH_COLLECTION = JSON.stringify({+ width: 1, height: 1, tilewidth: 4, tileheight: 4,+ tilesets: [{+ firstgid: 1, name: 'props', columns: 0, tilecount: 1,+ tiles: [{ id: 0, image: 'rock.png', imagewidth: 4, imageheight: 4 }],+ }],+ layers: [{ type: 'tilelayer', name: 'g', width: 1, height: 1, data: [1] }],+});++function realm(docs: Record<string, string>): Assets {+ const assets = Assets.create({+ backend: {+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),+ fetchText: vi.fn(async (url: string) => {+ const key = Object.keys(docs).find((k) => url.endsWith(k));+ return key ? docs[key] : '{}';+ }),+ resolveUrl: (p: string) => `http://test/${p}`,+ } as unknown as Backend,+ catalog: Catalog.empty(),+ module: { _malloc: vi.fn(() => 0), _free: vi.fn(), HEAPU8: new Uint8Array(1 << 16), GL: null, FS: null } as never,+ });+ assets.getTextureLoader().setPixelDecoder(async () => ({+ width: 4, height: 4, pixels: new Uint8Array(64),+ }));+ return assets;+}++describe('an edge comes from the acquisition that made it', () => {+ beforeEach(() => { pool = createPoolFake(); });++ it('an external .tsj is a SOURCE dependency of the map that folded it in', async () => {+ // Nothing is held for it — there is no runtime object — but what the map+ // IS was decided by it. Read through the plain text door it would leave+ // no trace, and a change to it could never reach the map.+ const assets = realm({ 'level.tmj': MAP_WITH_EXTERNAL, 'terrain.tsj': EXTERNAL_TILESET });+ await assets.acquireTyped('tilemap', 'maps/level.tmj');++ const edges = assets.dependenciesOf('tilemap', 'maps/level.tmj');+ expect(edges).toContainEqual({ kind: 'source', path: 'maps/terrain.tsj' });+ });++ it('a texture the map loaded is an OWNED dependency, named as a texture', async () => {+ const assets = realm({ 'level.tmj': MAP_WITH_EXTERNAL, 'terrain.tsj': EXTERNAL_TILESET });+ await assets.acquireTyped('tilemap', 'maps/level.tmj');++ expect(assets.dependenciesOf('tilemap', 'maps/level.tmj'))+ .toContainEqual({ kind: 'owned', type: 'texture', path: 'maps/terrain.png' });+ });++ it('a composed atlas is owned, and is not pretending to be a path', async () => {+ // It has no asset identity at all: naming it one would put a lookup key+ // in the graph that no invalidation could ever match.+ const assets = realm({ 'level.tmj': MAP_WITH_COLLECTION });+ await assets.acquireTyped('tilemap', 'maps/level.tmj');++ const edges = assets.dependenciesOf('tilemap', 'maps/level.tmj');+ const composed = edges.filter((e) => e.path.startsWith('composed:'));+ expect(composed).toHaveLength(1);+ expect(composed[0].kind).toBe('owned');+ expect(composed[0].type, 'a composed resource has no asset type').toBeUndefined();+ });++ it('releasing the parent gives the OWNED children back and destroys nothing else', async () => {+ const assets = realm({ 'level.tmj': MAP_WITH_EXTERNAL, 'terrain.tsj': EXTERNAL_TILESET });+ const base = assets.sizes().refRows;+ const held = await assets.acquireTyped('tilemap', 'maps/level.tmj');+ expect(pool.liveTextures()).toBe(1);++ held.release();+ expect(assets.sizes().refRows).toBe(base);+ expect(pool.liveTextures(), 'the owned texture stayed').toBe(0);+ // The source edge held nothing, so there was nothing of its to destroy —+ // and the graph is gone with the era that recorded it.+ expect(assets.dependenciesOf('tilemap', 'maps/level.tmj')).toEqual([]);+ });++ it('two realms record their own edges', async () => {+ const a = realm({ 'level.tmj': MAP_WITH_EXTERNAL, 'terrain.tsj': EXTERNAL_TILESET });+ const b = realm({ 'level.tmj': MAP_WITH_COLLECTION });+ await a.acquireTyped('tilemap', 'maps/level.tmj');+ await b.acquireTyped('tilemap', 'maps/level.tmj');++ expect(a.dependenciesOf('tilemap', 'maps/level.tmj'))+ .toContainEqual({ kind: 'source', path: 'maps/terrain.tsj' });+ expect(b.dependenciesOf('tilemap', 'maps/level.tmj').some((e) => e.kind === 'source'),+ 'one realm\'s edges showed up in the other').toBe(false);+ });+});diff --git a/sdk/tests/registry-asset-slots.test.ts b/sdk/tests/registry-asset-slots.test.tsindex bf3ecdf3f..75137e483 100644--- a/sdk/tests/registry-asset-slots.test.ts+++ b/sdk/tests/registry-asset-slots.test.ts@@ -10,7 +10,7 @@* behind what is actually on screen the moment a hot update landed.*/import { describe, it, expect } from 'vitest';-import { RegistryAssetSlots, type RegistryAssetKind, type RegistryEra } from '../src/asset/registryAssets';+import { RegistryAssetSlots, type RegistryAssetKind } from '../src/asset/registryAssets';import { AssetScope, type AssetLease } from '../src/asset/AssetLease';/** A kind whose every era is a distinguishable object owning one dependency. */@@ -18,11 +18,11 @@ function fixture() {const released: string[] = [];let era = 0;const kind: RegistryAssetKind<{ id: string }> = {- prepare: async (path: string): Promise<RegistryEra<{ id: string }>> => {+ prepare: async (path: string) => {const name = `${path}#${++era}`;const dependencies = new AssetScope();dependencies.add(fakeLease(`${name}:texture`, released));- return { published: { name }, value: { id: path }, dependencies };+ return { published: { name }, value: { id: path }, dependencies, edges: [] };},};return { released, kind };diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.tsindex ca2b8408d..991e3e55e 100644--- a/sdk/tests/tilemap.test.ts+++ b/sdk/tests/tilemap.test.ts@@ -156,6 +156,7 @@ describe('image-collection tilesets fold into a grid atlas', () => {const ctx = {catalog: { getBuildPath: (p: string) => p },loadText: async (p: string) => sources.get(p)!,+ readSource: async (p: string) => sources.get(p)!,decodePixels: async (p: string) => ({width: 2, height: 2, pixels: tilePixels(p.includes('rock') ? 10 : 30),}),@@ -178,6 +179,7 @@ describe('image-collection tilesets fold into a grid atlas', () => {const loader = new TilemapAssetLoader();const ctx = {catalog: { getBuildPath: (p: string) => p },+ readSource: async () => '{}',loadText: async () => JSON.stringify({width: 1, height: 1, tilewidth: 2, tileheight: 2,tilesets: [{@@ -199,6 +201,7 @@ describe('image-collection tilesets fold into a grid atlas', () => {const loader = new TilemapAssetLoader();const ctx = {catalog: { getBuildPath: (p: string) => p },+ readSource: async () => '{}',loadText: async () => JSON.stringify({width: 1, height: 1, tilewidth: 2, tileheight: 2,tilesets: [{diff --git a/tools/check-live-asset-rebind.mjs b/tools/check-live-asset-rebind.mjsindex 1ff7d2964..a1437b412 100644--- a/tools/check-live-asset-rebind.mjs+++ b/tools/check-live-asset-rebind.mjs@@ -34,6 +34,10 @@* a subsystem's own map as well is a second copy of "which asset this name* means" — and a module-global one crosses realms, so an editor world and* a play world answered each other's lookups.+ * 9. No loader describes a dependency. An edge is a projection of the+ * acquisition that made it, and a door for declaring one beside the work+ * is a second source of fact — the exact shape this line of work removed+ * from ownership.** Run: node tools/check-live-asset-rebind.mjs (exit 1 on violation)*/@@ -181,6 +185,10 @@ for (const file of REBIND_PATH) {findings.push(`${file}:${code.slice(0, hit.index).split('\n').length} works out who owns an entity's assets for itself — call assetScopeForEntity.`);}+// Nobody declares an edge. The recorder is the asset layer's; a loader reaches+// dependencies only by acquiring something.+const DECLARES_EDGE = /\b(?:addEdge|addDependency|DependencyRecorder)\b/;+// A registry-backed loader writes nothing. `register*`/`publish*` inside one is// the mirror this model exists to remove.const PUBLISHES = /\b(?:register|publish|unregister|unpublish)[A-Z]\w*\s*\(/;@@ -199,6 +207,10 @@ for (const name of readdirSync(LOADERS_DIR).filter((f) => f.endsWith('.ts'))) {if (registry === direct) {findings.push(`sdk/src/asset/loaders/${name} has ${registry ? 'BOTH doors' : 'neither door'} — a loader answers with load/unload or with registry, never both.`);}+ const declares = DECLARES_EDGE.exec(code);+ if (declares) {+ findings.push(`sdk/src/asset/loaders/${name}:${code.slice(0, declares.index).split('\n').length} describes a dependency (${declares[0]}) — an edge comes from the acquisition, never from a loader saying so.`);+ }const writes = registry ? PUBLISHES.exec(code) : null;if (writes) {findings.push(`sdk/src/asset/loaders/${name}:${code.slice(0, writes.index).split('\n').length} publishes into a registry of its own (${writes[0].trim()}) — a registry-backed loader only prepares; the slot holds the era and answers the lookup.`);@@ -210,7 +222,7 @@ if (loaders < 10) {}if (findings.length === 0) {- console.log(`check-live-asset-rebind: the rebind path reads the declaration for all ${components.size} asset-bearing components, acquires by receipt, asks one place who owns what, and each of the ${loaders} loaders has one door.`);+ console.log(`check-live-asset-rebind: the rebind path reads the declaration for all ${components.size} asset-bearing components, acquires by receipt, asks one place who owns what, and each of the ${loaders} loaders has one door and declares no edges.`);process.exit(0);}for (const f of findings) console.error(f);diff --git a/tools/check-tilemap-realm.mjs b/tools/check-tilemap-realm.mjsindex 6f67c40fa..6f0280740 100644--- a/tools/check-tilemap-realm.mjs+++ b/tools/check-tilemap-realm.mjs@@ -13,7 +13,8 @@* 1. No module-level cache of a loaded map or resolved tileset. The realm's* slot table is where the current era of a ref-bound asset lives.* 2. The tilemap/tileset loaders acquire (a receipt) or compose (an owned- * texture) — never `loadTexture`, which hands back nothing to release.+ * texture) — never `loadTexture`, which hands back nothing to release and+ * records no dependency.* 3. No module-level mutable "active" binding in the tilemap sources: an* editor world and a play world are two apps, and a pointer answers one.* 4. `TilemapPlugin` holds no state. What it installs is per app.@@ -73,8 +74,8 @@ for (const file of LOADERS) {if (loose) {findings.push(`${file}:${at(code, loose.index)} takes a texture with no owner (${loose[0].trim()}) — acquireTexture for one that has a path, createOwnedTexture for one this composes.`);}- if (!/\bdependencies\.add\s*\(/.test(code)) {- findings.push(`${file} puts nothing in its era's dependencies — whatever it resolved is pinned for the life of the app.`);+ if (!/\bctx\.(?:acquireTexture|createOwnedTexture)\s*\(/.test(code)) {+ findings.push(`${file} takes no texture through a recorded door — whatever it resolves is pinned for the life of the app, and its era owns nothing.`);}}