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.

7.3 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { AssetLoader, LoadContext, TilemapResult, RegistryAssetLoader } from '../AssetLoader';
import type { RegistryEra } from '../registryAssets';
import {
    packCollectionGrid, parseTmjWithExternals, resolveTiledRef,
    type TiledMapData, type TiledTilesetData,
} from '../../tilemap/tiledLoader';
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'];

    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
        // .tmx (XML) map fails loud with the fix, not with a JSON syntax error
        // — Tiled exports .tmj natively (File → Export As → JSON map files).
        if (text.trimStart().startsWith('<')) {
            throw new Error(
                `[tilemap] "${path}" is a Tiled XML map — the engine parses the JSON format only. ` +
                'In Tiled: File → Export As → "JSON map files (*.tmj)", then reference the .tmj.');
        }
        // 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) =>
            readSource(resolveTiledRef(path, source)));
        if (!mapData) {
            throw new Error(`Failed to parse tilemap: ${path}`);
        }

        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));
                continue;
            }
            const imagePath = resolveTiledRef(path, ts.image);
            let textureHandle = 0;
            try {
                const lease = await ctx.acquireTexture(imagePath, true);
                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
                // map's collision still generates — an invisible-but-solid level is
                // the single most confusing failure this loader can produce.
                log.error('tilemap',
                    `"${path}": tileset "${ts.name}" image failed to load `
                    + `("${ts.image}" → "${imagePath}") — its tiles will NOT render `
                    + '(collision still generates). Check that the image exists at that '
                    + 'path and is imported into the project.', e);
            }
            const rows = ts.columns > 0 ? Math.max(1, Math.ceil(ts.tileCount / ts.columns)) : 1;
            tilesets.push({
                textureHandle, columns: ts.columns, rows, firstId: ts.firstGid,
                margin: ts.margin ?? 0, spacing: ts.spacing ?? 0,
            });
        }

        const published: PublishedTilemap = { source: {
            tileWidth: mapData.tileWidth,
            tileHeight: mapData.tileHeight,
            // Carry every parsed field the runtime cache/plugin consume — the loader
            // previously dropped orientation/animations/properties/collision, so isometric
            // asset-loaded maps rendered flat, tile animations never ran, and tilemaps had
            // no physics collision (the B2-1 gap).
            orientation: mapData.orientation,
            hexSideLength: mapData.hexSideLength,
            staggerAxis: mapData.staggerAxis,
            staggerIndex: mapData.staggerIndex,
            layers: mapData.layers,
            tilesets,
            collisionTileIds: mapData.collisionTileIds,
            tileShapes: mapData.tileShapes,
            tileAnimations: mapData.tileAnimations,
            tileProperties: mapData.tileProperties,
            objectGroups: mapData.objectGroups,
        } };

        return { published, value: { sourceId: path } };
    }

    /**
     * Fold an image-collection tileset into one grid atlas: decode every tile
     * image through the platform's single decode path, pack them into a
     * near-square grid keyed by local id (packCollectionGrid), upload once.
     * Uniform tiles matching the map grid only — anything else has no meaning
     * on the fixed-grid renderer yet, so it fails loud with the fix.
     */
    private async foldCollection_(
        mapPath: string, ts: TiledTilesetData, mapData: TiledMapData, ctx: LoadContext,
    ): Promise<LoadedTilemapTileset> {
        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.');
        }
        const tiles = await Promise.all(ts.collectionTiles!.map(async (tile) => {
            const decoded = await ctx.decodePixels!(resolveTiledRef(mapPath, tile.image));
            if (decoded.width !== mapData.tileWidth || decoded.height !== mapData.tileHeight) {
                throw new Error(
                    `[tilemap] "${mapPath}": collection tile "${tile.image}" is `
                    + `${decoded.width}x${decoded.height}, but the map grid is `
                    + `${mapData.tileWidth}x${mapData.tileHeight} — collection tiles must match the `
                    + 'grid (resize them, or author a grid tileset image instead).');
            }
            return { id: tile.id, pixels: decoded.pixels };
        }));
        const grid = packCollectionGrid(tiles, mapData.tileWidth, mapData.tileHeight);
        // 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);
        // A folded image-collection atlas is packed gapless, so no margin/spacing.
        return {
            textureHandle: atlas.value.handle, columns: grid.columns, rows: grid.rows,
            firstId: ts.firstGid, margin: 0, spacing: 0,
        };
    }

}