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.

fix(tilemap): a map and a tileset belong to the realm that loaded them, and own what they resolved

esengine019fe2c36abc
diff --git a/docs/astro/src/content/docs/world/tilemaps.mdx b/docs/astro/src/content/docs/world/tilemaps.mdx
index e221b9bb5..cb9b25f13 100644
--- a/docs/astro/src/content/docs/world/tilemaps.mdx
+++ b/docs/astro/src/content/docs/world/tilemaps.mdx
@@ -350,19 +350,21 @@ modern way to read them is `Query(Marker)`: on load, point objects converge into
regions — the very same entities you author by hand — so one query reads objects
whether they came from Tiled or the Estella editor.
-The raw group data is still available by the map's source path with `getTilemapSource`
+The raw group data is still available by the map's source path with `tilemapSource`
— each group carries its objects with position, size, `type` (Tiled's class), `shape`,
and custom `properties`:
```typescript
-import { getTilemapSource } from 'esengine';
-
-const src = getTilemapSource('assets/maps/level.tmj');
-for (const group of src?.objectGroups ?? []) {
- for (const obj of group.objects) {
- if (obj.type === 'spawn') spawnPlayer(obj.x, obj.y);
+import { defineSystem, Res, Assets, tilemapSource } from 'esengine';
+
+const readSpawns = defineSystem([Res(Assets)], (assets) => {
+ const src = tilemapSource(assets, 'assets/maps/level.tmj');
+ for (const group of src?.objectGroups ?? []) {
+ for (const obj of group.objects) {
+ if (obj.type === 'spawn') spawnPlayer(obj.x, obj.y);
+ }
}
-}
+});
```
Objects that carry a tile reference (a **gid** — tiles stamped onto an object layer
diff --git a/docs/astro/src/content/docs/zh-cn/world/tilemaps.mdx b/docs/astro/src/content/docs/zh-cn/world/tilemaps.mdx
index 75cf09f9f..5e7a7966a 100644
--- a/docs/astro/src/content/docs/zh-cn/world/tilemaps.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/tilemaps.mdx
@@ -307,14 +307,16 @@ Tiled 还是 Estella 编辑器。
尺寸、`type`(Tiled 的 class)、`shape` 和自定义 `properties`:
```typescript
-import { getTilemapSource } from 'esengine';
-
-const src = getTilemapSource('assets/maps/level.tmj');
-for (const group of src?.objectGroups ?? []) {
- for (const obj of group.objects) {
- if (obj.type === 'spawn') spawnPlayer(obj.x, obj.y);
+import { defineSystem, Res, Assets, tilemapSource } from 'esengine';
+
+const readSpawns = defineSystem([Res(Assets)], (assets) => {
+ const src = tilemapSource(assets, 'assets/maps/level.tmj');
+ for (const group of src?.objectGroups ?? []) {
+ for (const obj of group.objects) {
+ if (obj.type === 'spawn') spawnPlayer(obj.x, obj.y);
+ }
}
-}
+});
```
携带瓦片引用(**gid**——在 Tiled 里盖到对象层上的瓦片)的对象会渲染为地图的精灵
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 5983e03b2..fefa22e37 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 89,
- "experimental": 1641,
+ "experimental": 1640,
"deprecated": 3
},
- "total": 1843,
+ "total": 1842,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index d6ba9e116..9b3101c3b 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 82 beta · 1504 experimental · 3 deprecated
+Symbols: 113 public · 82 beta · 1503 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -9865,11 +9865,6 @@ BtPlugin
(): void
```
-## clearTilemapSourceCache — function @experimental
-```
-(): void
-```
-
## clearUserComponents — function @experimental
```
(): void
@@ -10790,11 +10785,6 @@ FsmPlugin
(): ThemeTokens
```
-## getTilemapSource — function @experimental
-```
-(path: string): LoadedTilemapSource | undefined
-```
-
## getUserComponent — function @experimental
```
(name: string): ComponentDef<any> | undefined
@@ -11675,11 +11665,6 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
-## registerTilemapSource — function @experimental
-```
-(path: string, data: LoadedTilemapSource): void
-```
-
## remapComponentEntityRefs — function @experimental
```
(components: ComponentData[], idMapping: Map<PrefabEntityId, number>): void
@@ -11820,6 +11805,11 @@ ReplicationPlugin
(index: WangIndex, corners: readonly number[]): number
```
+## resolvedTileset — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
@@ -12285,6 +12275,11 @@ TextPlugin
TilemapPlugin
```
+## tilemapSource — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): LoadedTilemapSource | undefined
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 9a2b0b993..b346db868 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 87 beta · 1523 experimental · 3 deprecated
+Symbols: 113 public · 87 beta · 1522 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -10073,11 +10073,6 @@ BtPlugin
(): void
```
-## clearTilemapSourceCache — function @experimental
-```
-(): void
-```
-
## clearUserComponents — function @experimental
```
(): void
@@ -11023,11 +11018,6 @@ FsmPlugin
(): ThemeTokens
```
-## getTilemapSource — function @experimental
-```
-(path: string): LoadedTilemapSource | undefined
-```
-
## getUserComponent — function @experimental
```
(name: string): ComponentDef<any> | undefined
@@ -11918,11 +11908,6 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
-## registerTilemapSource — function @experimental
-```
-(path: string, data: LoadedTilemapSource): void
-```
-
## remapComponentEntityRefs — function @experimental
```
(components: ComponentData[], idMapping: Map<PrefabEntityId, number>): void
@@ -12063,6 +12048,11 @@ ReplicationPlugin
(index: WangIndex, corners: readonly number[]): number
```
+## resolvedTileset — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
@@ -12528,6 +12518,11 @@ TextPlugin
TilemapPlugin
```
+## tilemapSource — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): LoadedTilemapSource | undefined
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 4d47cf143..30d114063 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 84 beta · 1503 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1502 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -9860,11 +9860,6 @@ BtPlugin
(): void
```
-## clearTilemapSourceCache — function @experimental
-```
-(): void
-```
-
## clearUserComponents — function @experimental
```
(): void
@@ -10785,11 +10780,6 @@ FsmPlugin
(): ThemeTokens
```
-## getTilemapSource — function @experimental
-```
-(path: string): LoadedTilemapSource | undefined
-```
-
## getUserComponent — function @experimental
```
(name: string): ComponentDef<any> | undefined
@@ -11680,11 +11670,6 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
-## registerTilemapSource — function @experimental
-```
-(path: string, data: LoadedTilemapSource): void
-```
-
## remapComponentEntityRefs — function @experimental
```
(components: ComponentData[], idMapping: Map<PrefabEntityId, number>): void
@@ -11825,6 +11810,11 @@ ReplicationPlugin
(index: WangIndex, corners: readonly number[]): number
```
+## resolvedTileset — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
@@ -12290,6 +12280,11 @@ TextPlugin
TilemapPlugin
```
+## tilemapSource — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): LoadedTilemapSource | undefined
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index bc0792fb5..336440055 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 82 beta · 1525 experimental · 3 deprecated
+Symbols: 113 public · 82 beta · 1524 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -10112,11 +10112,6 @@ BtPlugin
(): void
```
-## clearTilemapSourceCache — function @experimental
-```
-(): void
-```
-
## clearUserComponents — function @experimental
```
(): void
@@ -11042,11 +11037,6 @@ FsmPlugin
(): ThemeTokens
```
-## getTilemapSource — function @experimental
-```
-(path: string): LoadedTilemapSource | undefined
-```
-
## getUserComponent — function @experimental
```
(name: string): ComponentDef<any> | undefined
@@ -11937,11 +11927,6 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
-## registerTilemapSource — function @experimental
-```
-(path: string, data: LoadedTilemapSource): void
-```
-
## remapComponentEntityRefs — function @experimental
```
(components: ComponentData[], idMapping: Map<PrefabEntityId, number>): void
@@ -12082,6 +12067,11 @@ ReplicationPlugin
(index: WangIndex, corners: readonly number[]): number
```
+## resolvedTileset — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
@@ -12547,6 +12537,11 @@ TextPlugin
TilemapPlugin
```
+## tilemapSource — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): LoadedTilemapSource | undefined
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index b1b759ee2..6e274ed81 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 82 beta · 1515 experimental · 3 deprecated
+Symbols: 113 public · 82 beta · 1514 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -9888,11 +9888,6 @@ BtPlugin
(): void
```
-## clearTilemapSourceCache — function @experimental
-```
-(): void
-```
-
## clearUserComponents — function @experimental
```
(): void
@@ -10813,11 +10808,6 @@ FsmPlugin
(): ThemeTokens
```
-## getTilemapSource — function @experimental
-```
-(path: string): LoadedTilemapSource | undefined
-```
-
## getUserComponent — function @experimental
```
(name: string): ComponentDef<any> | undefined
@@ -11703,11 +11693,6 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
-## registerTilemapSource — function @experimental
-```
-(path: string, data: LoadedTilemapSource): void
-```
-
## remapComponentEntityRefs — function @experimental
```
(components: ComponentData[], idMapping: Map<PrefabEntityId, number>): void
@@ -11848,6 +11833,11 @@ ReplicationPlugin
(index: WangIndex, corners: readonly number[]): number
```
+## resolvedTileset — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
@@ -12313,6 +12303,11 @@ TextPlugin
TilemapPlugin
```
+## tilemapSource — function @experimental
+```
+(assets: AssetsData | null | undefined, ref: string): LoadedTilemapSource | undefined
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index c24b088fd..bd018583d 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -129,6 +129,15 @@ export interface LoadContext {
createTextureFromPixels?(
width: number, height: number, pixels: Uint8Array, flipY: boolean,
): Promise<TextureResult>;
+ /**
+ * The same upload, as something an era can OWN: a texture composed from
+ * pixels has no path, no generation and no cache, so there is no receipt to
+ * acquire — but it still has to be given back, and only the era that
+ * composed it knows when. Releasing destroys it.
+ */
+ createOwnedTexture?(
+ width: number, height: number, pixels: Uint8Array, flipY: boolean,
+ ): Promise<AssetLease<TextureResult>>;
/**
* 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.ts
index e62709e42..fe4577f4f 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -1437,6 +1437,31 @@ export class Assets {
};
}
+ /**
+ * A receipt for a texture this engine COMPOSED — no path, no generation, no
+ * cache entry to join. Its only identity is the handle, so the last holder
+ * destroys it rather than handing it back to a pool that could revive it.
+ */
+ private ownedTextureLease_(value: TextureResult): AssetLease<TextureResult> {
+ let holders = 0;
+ const lease = (): AssetLease<TextureResult> => {
+ holders++;
+ let spent = false;
+ return {
+ key: `composed:${value.handle}`, generation: value.handle, value,
+ release: () => {
+ if (spent) return;
+ spent = true;
+ if (--holders > 0) return;
+ requireResourceManager().releaseTexture(value.handle);
+ evictTextureDimensions(value.handle);
+ },
+ retain: () => lease(),
+ };
+ };
+ return lease();
+ }
+
/** {@link textureLease_} for everything that goes through a typed loader. */
private typedLease_<T>(
type: string, lease: AssetRefLease<unknown>, value: T,
@@ -2061,6 +2086,11 @@ export class Assets {
async createTextureFromPixels(width, height, pixels, flipY) {
return self.textureLoader_.loadFromPixels(width, height, pixels, flipY);
},
+ async createOwnedTexture(width, height, pixels, flipY) {
+ return self.ownedTextureLease_(
+ await self.textureLoader_.loadFromPixels(width, height, pixels, flipY),
+ );
+ },
getAudio() {
return self.getAudio_();
},
diff --git a/sdk/src/asset/loaders/TilemapAssetLoader.ts b/sdk/src/asset/loaders/TilemapAssetLoader.ts
index 5360cc928..0f47c8bd4 100644
--- a/sdk/src/asset/loaders/TilemapAssetLoader.ts
+++ b/sdk/src/asset/loaders/TilemapAssetLoader.ts
@@ -1,18 +1,24 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { AssetLoader, LoadContext, TilemapResult } from '../AssetLoader';
+import type { AssetLoader, LoadContext, TilemapResult, RegistryAssetLoader } from '../AssetLoader';
+import type { RegistryEra } from '../registryAssets';
+import { AssetScope } from '../AssetLease';
import {
packCollectionGrid, parseTmjWithExternals, resolveTiledRef,
type TiledMapData, type TiledTilesetData,
} from '../../tilemap/tiledLoader';
-import { registerTilemapSource, unregisterTilemapSource, type LoadedTilemapTileset } from '../../tilemap/tilesetCache';
+import type { LoadedTilemapTileset, PublishedTilemap } from '../../tilemap/tilesetCache';
import { log } from '../../util/logger';
export class TilemapAssetLoader implements AssetLoader<TilemapResult> {
readonly type = 'tilemap';
readonly extensions = ['.tmj', '.tmx'];
- async load(path: string, ctx: LoadContext): Promise<TilemapResult> {
+ readonly registry: RegistryAssetLoader<TilemapResult> = {
+ prepare: (path, ctx) => this.prepare_(path, ctx),
+ };
+
+ private async prepare_(path: string, ctx: LoadContext): Promise<RegistryEra<TilemapResult>> {
const buildPath = ctx.catalog.getBuildPath(path);
const text = await ctx.loadText(buildPath);
// The engine has ONE Tiled parser and it speaks the JSON format. A
@@ -31,19 +37,21 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {
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));
+ tilesets.push(await this.foldCollection_(path, ts, mapData, ctx, dependencies));
continue;
}
const imagePath = resolveTiledRef(path, ts.image);
let textureHandle = 0;
try {
- const result = await ctx.loadTexture(imagePath, true);
- textureHandle = result.handle;
+ 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
// uses it invisible (the renderer drops handle-0 slots), while the
@@ -62,7 +70,7 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {
});
}
- registerTilemapSource(path, {
+ const published: PublishedTilemap = { source: {
tileWidth: mapData.tileWidth,
tileHeight: mapData.tileHeight,
// Carry every parsed field the runtime cache/plugin consume — the loader
@@ -87,9 +95,9 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {
tileAnimations: mapData.tileAnimations,
tileProperties: mapData.tileProperties,
objectGroups: mapData.objectGroups,
- });
+ } };
- return { sourceId: path };
+ return { published, value: { sourceId: path }, dependencies };
}
/**
@@ -101,8 +109,9 @@ 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.createTextureFromPixels) {
+ if (!ctx.decodePixels || !ctx.createOwnedTexture) {
throw new Error(
`[tilemap] "${mapPath}": tileset "${ts.name}" is an image collection, but this `
+ 'asset provider cannot decode/compose pixels — load it through the app Assets channel.');
@@ -119,18 +128,15 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {
return { id: tile.id, pixels: decoded.pixels };
}));
const grid = packCollectionGrid(tiles, mapData.tileWidth, mapData.tileHeight);
- const tex = await ctx.createTextureFromPixels(grid.width, grid.height, grid.pixels, true);
+ // 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: tex.handle, columns: grid.columns, rows: grid.rows, firstId: ts.firstGid, margin: 0, spacing: 0 };
- }
-
- unload(_asset: TilemapResult): void {
- // Tilemap sources registered globally
+ return {
+ textureHandle: atlas.value.handle, columns: grid.columns, rows: grid.rows,
+ firstId: ts.firstGid, margin: 0, spacing: 0,
+ };
}
- /** Hot reload: sever the global source registration too — the Assets-level
- * cache drop alone would leave the tilemap sync rendering the stale parse. */
- invalidate(path: string): boolean {
- return unregisterTilemapSource(path);
- }
}
diff --git a/sdk/src/asset/loaders/TilesetAssetLoader.ts b/sdk/src/asset/loaders/TilesetAssetLoader.ts
index 7377e81a3..339900b01 100644
--- a/sdk/src/asset/loaders/TilesetAssetLoader.ts
+++ b/sdk/src/asset/loaders/TilesetAssetLoader.ts
@@ -1,46 +1,49 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file Runtime `.estileset` loader — parses the tileset asset and loads its
- * atlas texture, caching the resolved tileset so the tilemap sync can
- * derive the render table + collision + animations LIVE (no baking).
- * Mirrors {@link TilemapAssetLoader} (the `.tmj` path).
+ * @file Runtime `.estileset` loader — parses the tileset and acquires its atlas,
+ * so the tilemap sync can derive the render table + collision + animations
+ * LIVE (no baking). Mirrors {@link TilemapAssetLoader} (the `.tmj` path).
+ *
+ * A component names a tileset by REF, so what an owner owns is the slot; the
+ * atlas belongs to the ERA that resolved it, and goes back when that era retires.
*/
-import type { AssetLoader, LoadContext, TilesetResult } from '../AssetLoader';
+import type { AssetLoader, LoadContext, TilesetResult, RegistryAssetLoader } from '../AssetLoader';
+import type { RegistryEra } from '../registryAssets';
+import { AssetScope } from '../AssetLease';
import { parseTileset } from '../../tilemap/tilesetAsset';
-import { registerResolvedTileset } from '../../tilemap/tilesetCache';
+import type { PublishedTileset } from '../../tilemap/tilesetCache';
import { log } from '../../util/logger';
export class TilesetAssetLoader implements AssetLoader<TilesetResult> {
readonly type = 'tileset';
readonly extensions = ['.estileset'];
- async load(path: string, ctx: LoadContext): Promise<TilesetResult> {
- const buildPath = ctx.catalog.getBuildPath(path);
- const text = await ctx.loadText(buildPath);
- const asset = parseTileset(JSON.parse(text));
+ readonly registry: RegistryAssetLoader<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; loadTexture resolves it.
- let textureHandle = 0;
- let textureWidth: number | undefined;
- let textureHeight: number | undefined;
- if (asset.texture) {
- try {
- const tex = await ctx.loadTexture(asset.texture, true);
- textureHandle = tex.handle;
- textureWidth = tex.width;
- textureHeight = tex.height;
- } catch (e) {
- log.warn('asset', `Failed to load tileset atlas: ${asset.texture}`, e);
+ // The atlas is a `@uuid:` ref inside the .estileset; the acquire resolves it.
+ let textureHandle = 0;
+ let textureWidth: number | undefined;
+ let textureHeight: number | undefined;
+ 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;
+ } catch (e) {
+ log.warn('asset', `Failed to load tileset atlas: ${asset.texture}`, e);
+ }
}
- }
-
- registerResolvedTileset(path, { asset, textureHandle, textureWidth, textureHeight });
- return { tilesetId: path };
- }
-
- unload(_asset: TilesetResult): void {
- // Resolved tilesets live in the module cache (cleared on scene reset); the
- // atlas texture is ref-counted by the texture loader. Nothing per-asset here.
- }
+ const published: PublishedTileset = {
+ resolved: { asset, textureHandle, textureWidth, textureHeight },
+ };
+ return { published, value: { tilesetId: path }, dependencies };
+ },
+ };
}
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 9eb24b069..f21c71935 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -545,9 +545,6 @@ export {
loadTiledMap,
resolveRelativePath,
getTextureDimensions,
- registerTilemapSource,
- getTilemapSource,
- clearTilemapSourceCache,
TILESET_FORMAT_VERSION,
parseTileset,
serializeTileset,
@@ -613,6 +610,8 @@ export {
type TiledLayerData,
type TiledTilesetData,
type TextureDimensions,
+ tilemapSource,
+ resolvedTileset,
type LoadedTilemapSource,
type LoadedTilemapLayer,
type LoadedTilemapTileset,
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index b6eb0a56c..5f9bb1fbf 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -51,9 +51,9 @@ export {
type TerrainIndex, type TerrainIndices, type WangIndex, type WangIndices,
} from './autotile';
export {
- registerTilemapSource, getTilemapSource, clearTilemapSourceCache,
- registerResolvedTileset, getResolvedTileset, clearResolvedTilesetCache,
+ tilemapSource, resolvedTileset,
type LoadedTilemapSource, type LoadedTilemapLayer, type LoadedTilemapTileset,
+ type PublishedTilemap, type PublishedTileset,
} from './tilesetCache';
export { getTextureDimensions, type TextureDimensions } from '../wasm/resourceManager';
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 39a845dc8..71695b2fd 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -9,7 +9,7 @@ import { initTilemapAPI, shutdownTilemapAPI, TilemapAPI } from './tilemapAPI';
import { TilemapLiveSync } from './tilemapLiveSync';
import { Tilemap } from './components';
import { registerSceneComponentCodec } from '../scene/scene';
-import { getTilemapSource, getResolvedTileset, type LoadedTilemapSource } from './tilesetCache';
+import { tilemapSource, resolvedTileset, type LoadedTilemapSource } from './tilesetCache';
import { resolveTilesetModel } from './tilesetResolve';
import { isCollisionPaletteRef, buildCollisionPaletteModel, parseCollisionMaterial } from './collisionPalette';
import { _bindTileCollisionLookup, type LayerCollisionTable } from './tileQuery';
@@ -306,7 +306,7 @@ export class TilemapPlugin implements Plugin {
const resolvedList = [];
for (const ref of refs) {
const key = resolveAssetKey(assets, ref);
- const r = getResolvedTileset(key) ?? getResolvedTileset(ref);
+ const r = resolvedTileset(assets, ref);
if (r) {
resolvedList.push(r);
} else if (assets && !requestedTilesetLoads.has(key)) {
@@ -383,12 +383,9 @@ export class TilemapPlugin implements Plugin {
const tilemap = world.tryGet(entity, Tilemap) as { source: string } | null;
- // The loader keys the source cache by the RESOLVED path and
- // `resolveSceneAssetPaths` leaves `source` as the authored ref, so
- // resolve at lookup (see resolveAssetKey), falling back to the raw ref.
- const cached = tilemap?.source
- ? getTilemapSource(resolveAssetKey(assets, tilemap.source)) ?? getTilemapSource(tilemap.source)
- : undefined;
+ // This app's realm, by the ref the component carries: the slot
+ // answers to that spelling and to the path it resolved to.
+ const cached = tilemap?.source ? tilemapSource(assets, tilemap.source) : undefined;
// Derived children must mirror the CURRENT source. A cleared field,
// an invalidated cache entry (hot reload), or different source data
diff --git a/sdk/src/tilemap/tilesetCache.ts b/sdk/src/tilemap/tilesetCache.ts
index b1edc996f..d56d59083 100644
--- a/sdk/src/tilemap/tilesetCache.ts
+++ b/sdk/src/tilemap/tilesetCache.ts
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { ResolvedTileset, ResolvedTileCollision } from './tilesetResolve';
import type { TiledObjectGroupData } from './tiledLoader';
+import type { AssetsData } from '../asset/AssetPlugin';
export interface LoadedTilemapChunk {
x: number;
@@ -49,48 +50,41 @@ export interface LoadedTilemapSource {
/** Rich per-tile collision (Tiled collision editor / modifier properties) — see TiledMapData.tileShapes. */
tileShapes?: Map<number, ResolvedTileCollision>;
/**
- * Tiled object layers — spawn/marker data queryable by gameplay via
- * `getTilemapSource`; groups marked per `isCollisionObjectGroup` also spawn
- * static colliders in play mode.
+ * Tiled object layers — spawn/marker data queryable by gameplay through the
+ * app's Assets; groups marked per `isCollisionObjectGroup` also spawn static
+ * colliders in play mode.
*/
objectGroups?: TiledObjectGroupData[];
}
-const tilemapCache_ = new Map<string, LoadedTilemapSource>();
-export function registerTilemapSource(path: string, data: LoadedTilemapSource): void {
- tilemapCache_.set(path, data);
-}
-
-export function getTilemapSource(path: string): LoadedTilemapSource | undefined {
- return tilemapCache_.get(path);
-}
-/** Drop one source (hot reload: the `.tmj` changed on disk). The tilemap sync
- * notices the entry vanish and tears the derived layers down; the reload
- * registers fresh data and they re-derive. Returns true if the path was held. */
-export function unregisterTilemapSource(path: string): boolean {
- return tilemapCache_.delete(path);
+/** One era of a `.tmj` as its realm publishes it. */
+export interface PublishedTilemap {
+ source: LoadedTilemapSource;
}
-export function clearTilemapSourceCache(): void {
- tilemapCache_.clear();
-}
-
-// — Resolved `.estileset` tilesets (parsed asset + loaded atlas texture) —
-// The runtime tileset loader registers here; the tilemap sync resolves a layer's
-// tileset(s) into the render table + collision + animations LIVE off these (no
-// columns copied onto the layer, no collision baked at author-time).
-const resolvedTilesetCache_ = new Map<string, ResolvedTileset>();
-
-export function registerResolvedTileset(path: string, data: ResolvedTileset): void {
- resolvedTilesetCache_.set(path, data);
+/** One era of a `.estileset` as its realm publishes it. */
+export interface PublishedTileset {
+ resolved: ResolvedTileset;
}
-export function getResolvedTileset(path: string): ResolvedTileset | undefined {
- return resolvedTilesetCache_.get(path);
+/**
+ * The map `ref` names in this realm — object groups, tile properties, collision
+ * ids, the parsed layers.
+ *
+ * Takes the Assets to ask: a map belongs to the realm that loaded it, and an
+ * editor world beside a play world is two of them.
+ */
+export function tilemapSource(
+ assets: AssetsData | null | undefined, ref: string,
+): LoadedTilemapSource | undefined {
+ return assets?.resolveRegistryAsset<PublishedTilemap>('tilemap', ref)?.source;
}
-export function clearResolvedTilesetCache(): void {
- resolvedTilesetCache_.clear();
+/** The tileset `ref` names in this realm: the parsed asset plus its atlas. */
+export function resolvedTileset(
+ assets: AssetsData | null | undefined, ref: string,
+): ResolvedTileset | undefined {
+ return assets?.resolveRegistryAsset<PublishedTileset>('tileset', ref)?.resolved;
}
diff --git a/sdk/tests/tilemap-realm-assets.test.ts b/sdk/tests/tilemap-realm-assets.test.ts
new file mode 100644
index 000000000..5c5510124
--- /dev/null
+++ b/sdk/tests/tilemap-realm-assets.test.ts
@@ -0,0 +1,152 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tilemap-realm-assets.test.ts
+ * @brief A tilemap era owns every texture it resolved — including the atlas it
+ * composed itself, which no ledger can account for.
+ *
+ * @details Both loaders took their textures with `loadTexture` and released
+ * none: a tileset atlas, every Tiled tileset image, and the grid an
+ * image collection is folded into stayed on the GPU for the life of
+ * the app. The folded one is the interesting case — it has no path, so
+ * it never was in the reference ledger and only the pool can say
+ * whether it is still alive.
+ */
+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';
+import type { PublishedTilemap, PublishedTileset } from '../src/tilemap/tilesetCache';
+
+/** The pool, modelled: what is live is what has not been released. */
+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);
+
+const GRID_MAP = JSON.stringify({
+ width: 1, height: 1, tilewidth: 4, tileheight: 4,
+ tilesets: [{ firstgid: 1, name: 'ground', image: '../tiles/atlas.png', columns: 2, tilecount: 4 }],
+ layers: [{ type: 'tilelayer', name: 'g', width: 1, height: 1, data: [1] }],
+});
+const COLLECTION_MAP = JSON.stringify({
+ width: 1, height: 1, tilewidth: 4, tileheight: 4,
+ tilesets: [{
+ firstgid: 1, name: 'props', columns: 0, tilecount: 2,
+ tiles: [
+ { id: 0, image: '../tiles/rock.png', imagewidth: 4, imageheight: 4 },
+ { id: 1, image: '../tiles/bush.png', imagewidth: 4, imageheight: 4 },
+ ],
+ }],
+ layers: [{ type: 'tilelayer', name: 'g', width: 1, height: 1, data: [1] }],
+});
+const TILESET_DOC = JSON.stringify({
+ version: 1, type: 'tileset', texture: 'tiles/atlas.png',
+ tileWidth: 4, tileHeight: 4, columns: 2, rows: 2,
+});
+
+function realm(text: string): Assets {
+ const assets = Assets.create({
+ backend: {
+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),
+ fetchText: vi.fn(async () => text),
+ 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,
+ });
+ // The realm's one decode path, as a platform provides it.
+ assets.getTextureLoader().setPixelDecoder(async () => ({
+ width: 4, height: 4, pixels: new Uint8Array(64),
+ }));
+ return assets;
+}
+
+describe('a tilemap era owns the textures it resolved', () => {
+ beforeEach(() => { pool = createPoolFake(); });
+
+ it('a tileset gives its atlas back when the last holder goes', async () => {
+ const assets = realm(TILESET_DOC);
+ const base = assets.sizes().refRows;
+
+ const held = await assets.acquireTyped('tileset', 'tiles/ground.estileset');
+ const resolved = assets.resolveRegistryAsset<PublishedTileset>('tileset', 'tiles/ground.estileset')!.resolved;
+ expect(resolved.textureHandle).toBeGreaterThan(0);
+ expect(pool.liveTextures()).toBe(1);
+ expect(assets.sizes().refRows, 'the atlas is the era\'s acquisition').toBe(base + 1);
+
+ held.release();
+ expect(assets.sizes().refRows).toBe(base);
+ expect(pool.liveTextures(), 'the atlas outlived every holder').toBe(0);
+ });
+
+ it('a tilemap gives back every tileset image it loaded', async () => {
+ const assets = realm(GRID_MAP);
+ const base = assets.sizes().refRows;
+ const held = await assets.acquireTyped('tilemap', 'maps/level.tmj');
+ expect(assets.sizes().refRows).toBe(base + 1);
+
+ held.release();
+ expect(assets.sizes().refRows).toBe(base);
+ expect(pool.liveTextures()).toBe(0);
+ });
+
+ it('and the atlas it COMPOSED, which no ledger accounts for', async () => {
+ // An image-collection tileset is decoded and packed into one grid the
+ // engine uploads itself: no path, no cache entry, no reference row —
+ // only the pool can say whether it is still there.
+ const assets = realm(COLLECTION_MAP);
+ const base = assets.sizes().refRows;
+
+ const held = await assets.acquireTyped('tilemap', 'maps/level.tmj');
+ const source = assets.resolveRegistryAsset<PublishedTilemap>('tilemap', 'maps/level.tmj')!.source;
+ expect(source.tilesets[0].columns, 'the collection folded into one page').toBe(2);
+ expect(pool.liveTextures(), 'the composed atlas').toBe(1);
+ expect(assets.sizes().refRows, 'and it is nobody\'s reference row').toBe(base);
+
+ held.release();
+ expect(pool.liveTextures(), 'a composed texture nothing can name was left behind').toBe(0);
+ });
+});
diff --git a/sdk/tests/tilemap-source-invalidate.test.ts b/sdk/tests/tilemap-source-invalidate.test.ts
index 363f46a43..8ef2e8069 100644
--- a/sdk/tests/tilemap-source-invalidate.test.ts
+++ b/sdk/tests/tilemap-source-invalidate.test.ts
@@ -1,48 +1,79 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file Tilemap source hot-reload contract: `Assets.invalidate` reaches the
- * loader's `invalidate`, which must sever the GLOBAL source registration
- * (tilesetCache) too — dropping only the Assets-level cache would leave
- * the tilemap sync rendering the stale parse forever. The sync detects
- * the vanished/replaced entry by object identity and re-derives.
+ * @file tilemap-source-invalidate.test.ts
+ * @brief A `.tmj` changed on disk: the realm publishes a new era, and the
+ * sync notices because the object it derived from is not the one the
+ * lookup answers with any more.
+ *
+ * @details The tilemap sync re-derives on IDENTITY (`sourceDerivedFrom_ !==
+ * cached`), so a hot reload that mutated a cached record in place
+ * would leave every derived layer as it was.
*/
-import { describe, it, expect, afterEach } from 'vitest';
-import {
- registerTilemapSource, getTilemapSource, unregisterTilemapSource,
- clearTilemapSourceCache, type LoadedTilemapSource,
-} from '../src/tilemap/tilesetCache';
-import { TilemapAssetLoader } from '../src/asset/loaders/TilemapAssetLoader';
-
-const SRC: LoadedTilemapSource = {
- tileWidth: 16, tileHeight: 16, layers: [], tilesets: [],
-};
-
-afterEach(() => clearTilemapSourceCache());
-
-describe('tilemap source invalidation', () => {
- it('unregisterTilemapSource drops the entry and reports whether it was held', () => {
- registerTilemapSource('assets/maps/level.tmj', SRC);
- expect(getTilemapSource('assets/maps/level.tmj')).toBe(SRC);
- expect(unregisterTilemapSource('assets/maps/level.tmj')).toBe(true);
- expect(getTilemapSource('assets/maps/level.tmj')).toBeUndefined();
- expect(unregisterTilemapSource('assets/maps/level.tmj')).toBe(false);
- });
-
- it('TilemapAssetLoader.invalidate severs the global registration', () => {
- const loader = new TilemapAssetLoader();
- registerTilemapSource('assets/maps/level.tmj', SRC);
- expect(loader.invalidate('assets/maps/level.tmj')).toBe(true);
- expect(getTilemapSource('assets/maps/level.tmj')).toBeUndefined();
- expect(loader.invalidate('assets/maps/level.tmj')).toBe(false);
- });
-
- it('a re-registered source is a NEW object — the identity the sync re-derives on', () => {
- registerTilemapSource('assets/maps/level.tmj', SRC);
- const before = getTilemapSource('assets/maps/level.tmj');
- const fresh: LoadedTilemapSource = { ...SRC };
- registerTilemapSource('assets/maps/level.tmj', fresh);
- expect(getTilemapSource('assets/maps/level.tmj')).toBe(fresh);
- expect(getTilemapSource('assets/maps/level.tmj')).not.toBe(before);
- });
+import { describe, it, expect, vi } from 'vitest';
+import { Assets } from '../src/asset/Assets';
+import { Catalog } from '../src/asset/Catalog';
+import type { Backend } from '../src/asset/Backend';
+import type { PublishedTilemap } from '../src/tilemap/tilesetCache';
+
+vi.mock('../src/wasm/resourceManager', () => ({
+ requireResourceManager: () => ({ releaseTexture: vi.fn(), invalidateTexturePath: vi.fn(() => false) }),
+ getResourceManager: () => null,
+ evictTextureDimensions: vi.fn(),
+}));
+
+const PATH = 'assets/maps/level.tmj';
+
+/** A map whose one property carries the era, so a lookup can say which it is. */
+const mapDocument = (tileWidth: number): string => JSON.stringify({
+ width: 1, height: 1, tilewidth: tileWidth, tileheight: 16,
+ tilesets: [], layers: [{ type: 'tilelayer', name: 'ground', width: 1, height: 1, data: [0] }],
+});
+
+function realm(doc: () => string): Assets {
+ return Assets.create({
+ backend: {
+ fetchBinary: vi.fn(async () => new ArrayBuffer(0)),
+ fetchText: vi.fn(async () => doc()),
+ resolveUrl: (p: string) => p,
+ } as unknown as Backend,
+ catalog: Catalog.empty(),
+ module: null as never,
+ });
+}
+
+describe('a tilemap source is its realm\'s, and a reload is a new era', () => {
+ it('publishes for the ref, and takes it back when the last holder goes', async () => {
+ const assets = realm(() => mapDocument(16));
+ const held = await assets.acquireTyped('tilemap', PATH);
+
+ expect(assets.resolveRegistryAsset<PublishedTilemap>('tilemap', PATH)?.source.tileWidth).toBe(16);
+ held.release();
+ expect(assets.resolveRegistryAsset('tilemap', PATH), 'the module cache never released one').toBeUndefined();
+ });
+
+ it('a reload publishes a NEW object — the identity the sync re-derives on', async () => {
+ let width = 16;
+ const assets = realm(() => mapDocument(width));
+ await assets.acquireTyped('tilemap', PATH);
+ const before = assets.resolveRegistryAsset<PublishedTilemap>('tilemap', PATH)!.source;
+
+ width = 32;
+ assets.invalidate(PATH);
+ await new Promise((r) => setTimeout(r, 0));
+
+ const after = assets.resolveRegistryAsset<PublishedTilemap>('tilemap', PATH)!.source;
+ expect(after.tileWidth).toBe(32);
+ expect(after, 'the sync only re-derives when the object changes').not.toBe(before);
+ });
+
+ it('two realms hold their own map of the same name', async () => {
+ const a = realm(() => mapDocument(16));
+ const b = realm(() => mapDocument(32));
+ await a.acquireTyped('tilemap', PATH);
+ await b.acquireTyped('tilemap', PATH);
+
+ expect(a.resolveRegistryAsset<PublishedTilemap>('tilemap', PATH)?.source.tileWidth).toBe(16);
+ expect(b.resolveRegistryAsset<PublishedTilemap>('tilemap', PATH)?.source.tileWidth).toBe(32);
+ });
});
diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.ts
index 954b3492c..ca2b8408d 100644
--- a/sdk/tests/tilemap.test.ts
+++ b/sdk/tests/tilemap.test.ts
@@ -8,11 +8,7 @@ import {
initTilemapAPI,
shutdownTilemapAPI,
} from '../src/tilemap';
-import {
- registerTilemapSource,
- getTilemapSource,
- clearTilemapSourceCache,
-} from '../src/tilemap/tilesetCache';
+import type { LoadedTilemapSource } from '../src/tilemap/tilesetCache';
import {
loadTiledMap, parseTmjJson, parseTmjWithExternals, resolveRelativePath, loadTiledCollisionObjects,
generateLayerCollision, generateObjectCollision, spawnObjectRegion, isCollisionObjectGroup, decodeTiledGid,
@@ -145,6 +141,7 @@ describe('image-collection tilesets fold into a grid atlas', () => {
it('the loader folds a collection into one uploaded grid tileset', async () => {
const loader = new TilemapAssetLoader();
const uploads: Array<{ width: number; height: number }> = [];
+ const destroyed: number[] = [];
const sources = new Map<string, string>([['maps/level.tmj', JSON.stringify({
width: 1, height: 1, tilewidth: 2, tileheight: 2,
tilesets: [{
@@ -162,15 +159,18 @@ describe('image-collection tilesets fold into a grid atlas', () => {
decodePixels: async (p: string) => ({
width: 2, height: 2, pixels: tilePixels(p.includes('rock') ? 10 : 30),
}),
- createTextureFromPixels: async (width: number, height: number) => {
+ createOwnedTexture: async (width: number, height: number) => {
uploads.push({ width, height });
- return { handle: 77, width, height };
+ return {
+ key: 'composed:77', generation: 77, value: { handle: 77, width, height },
+ release: () => { destroyed.push(77); }, retain: () => null,
+ };
},
} as unknown as LoadContext;
- await loader.load('maps/level.tmj', ctx);
+ const era = await loader.registry.prepare('maps/level.tmj', ctx);
expect(uploads).toEqual([{ width: 4, height: 2 }]); // ONE folded 2x1 page
- const src = getTilemapSource('maps/level.tmj')!;
+ const src = (era.published as { source: LoadedTilemapSource }).source;
expect(src.tilesets[0]).toEqual({ textureHandle: 77, columns: 2, rows: 1, firstId: 5, margin: 0, spacing: 0 });
});
@@ -187,9 +187,12 @@ describe('image-collection tilesets fold into a grid atlas', () => {
layers: [{ type: 'tilelayer', width: 1, height: 1, data: [1] }],
}),
decodePixels: async () => ({ width: 4, height: 4, pixels: new Uint8Array(64) }),
- createTextureFromPixels: async () => ({ handle: 1, width: 4, height: 4 }),
+ createOwnedTexture: async () => ({
+ key: 'composed:1', generation: 1, value: { handle: 1, width: 4, height: 4 },
+ release: () => {}, retain: () => null,
+ }),
} as unknown as LoadContext;
- await expect(loader.load('maps/level.tmj', ctx)).rejects.toThrow(/match the\s+grid/);
+ await expect(loader.registry.prepare('maps/level.tmj', ctx)).rejects.toThrow(/match the\s+grid/);
});
it('a provider without pixel plumbing fails loud, not silently white', async () => {
@@ -205,7 +208,7 @@ describe('image-collection tilesets fold into a grid atlas', () => {
layers: [{ type: 'tilelayer', width: 1, height: 1, data: [1] }],
}),
} as unknown as LoadContext;
- await expect(loader.load('maps/level.tmj', ctx)).rejects.toThrow(/image collection/);
+ await expect(loader.registry.prepare('maps/level.tmj', ctx)).rejects.toThrow(/image collection/);
});
});
@@ -216,40 +219,7 @@ describe('TilemapAssetLoader — .tmx fails loud with the fix', () => {
catalog: { getBuildPath: (p: string) => p },
loadText: async () => '<?xml version="1.0" encoding="UTF-8"?>\n<map version="1.10"></map>',
} as unknown as LoadContext;
- await expect(loader.load('maps/level.tmx', ctx)).rejects.toThrow(/JSON map files \(\*\.tmj\)/);
- });
-});
-
-describe('TilemapSource cache', () => {
- beforeEach(() => {
- clearTilemapSourceCache();
- });
-
- it('should register and retrieve tilemap source', () => {
- const source = {
- tileWidth: 16,
- tileHeight: 16,
- layers: [{ name: 'Ground', width: 10, height: 10, tiles: new Uint16Array([1, 2, 3]) }],
- tilesets: [{ textureHandle: 42, columns: 8, rows: 8, firstId: 1 }],
- };
- registerTilemapSource('maps/level1.tmj', source);
- expect(getTilemapSource('maps/level1.tmj')).toBe(source);
- });
-
- it('should return undefined for unregistered path', () => {
- expect(getTilemapSource('nonexistent.tmj')).toBeUndefined();
- });
-
- it('should clear all entries', () => {
- const source = {
- tileWidth: 16, tileHeight: 16,
- layers: [], tilesets: [],
- };
- registerTilemapSource('a.tmj', source);
- registerTilemapSource('b.tmj', source);
- clearTilemapSourceCache();
- expect(getTilemapSource('a.tmj')).toBeUndefined();
- expect(getTilemapSource('b.tmj')).toBeUndefined();
+ await expect(loader.registry.prepare('maps/level.tmx', ctx)).rejects.toThrow(/JSON map files \(\*\.tmj\)/);
});
});
@@ -1588,12 +1558,4 @@ describe('generateLayerCollision (B2-1 runtime tile collision)', () => {
expect(generateLayerCollision(world, tiles, 2, 2, 16, 16, new Set([1]), 0, 0)).toHaveLength(0);
});
- it('carries collisionTileIds through the runtime source cache', () => {
- clearTilemapSourceCache();
- registerTilemapSource('lvl.tmj', {
- tileWidth: 16, tileHeight: 16, layers: [], tilesets: [],
- collisionTileIds: [3, 7],
- });
- expect(getTilemapSource('lvl.tmj')?.collisionTileIds).toEqual([3, 7]);
- });
});