Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(tilemap): .estileset tileset-asset SDK format (REARCH_TILEMAP T2a)

esengine9db003ba3738
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index d2f90453d..a64b493e2 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -281,6 +281,11 @@ export {
registerTilemapSource,
getTilemapSource,
clearTilemapSourceCache,
+ TILESET_FORMAT_VERSION,
+ parseTileset,
+ serializeTileset,
+ createTileset,
+ collidableTileIds,
type TilemapData,
type TilemapLayerData,
type TiledMapData,
@@ -290,6 +295,10 @@ export {
type LoadedTilemapSource,
type LoadedTilemapLayer,
type LoadedTilemapTileset,
+ type TilesetAsset,
+ type TilesetTile,
+ type TilesetCollision,
+ type TilesetAnimFrame,
} from './tilemap';
// =============================================================================
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index 67247175f..26f2b9896 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -5,12 +5,16 @@ export { TilemapAPI, initTilemapAPI, shutdownTilemapAPI } from './tilemapAPI';
export { TilemapPlugin, tilemapPlugin } from './tilemapPlugin';
export {
parseTiledMap, parseTmjJson, loadTiledMap, loadTiledCollisionObjects,
- generateTileCollision, resolveRelativePath,
+ generateTileCollision, generateLayerCollision, resolveRelativePath,
type TiledMapData, type TiledLayerData, type TiledTilesetData,
type TiledObjectData, type TiledObjectGroupData, type TiledObjectShape,
type TiledAnimFrame, type TilemapLoadOptions,
} from './tiledLoader';
export { mergeCollisionTiles, type MergedRect } from './collisionMerge';
+export {
+ TILESET_FORMAT_VERSION, parseTileset, serializeTileset, createTileset, collidableTileIds,
+ type TilesetAsset, type TilesetTile, type TilesetCollision, type TilesetAnimFrame,
+} from './tilesetAsset';
export {
registerTilemapSource, getTilemapSource, clearTilemapSourceCache,
type LoadedTilemapSource, type LoadedTilemapLayer, type LoadedTilemapTileset,
diff --git a/sdk/src/tilemap/tilesetAsset.ts b/sdk/src/tilemap/tilesetAsset.ts
new file mode 100644
index 000000000..0ecb20aa1
--- /dev/null
+++ b/sdk/src/tilemap/tilesetAsset.ts
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tilesetAsset.ts
+ * @brief The `.estileset` tileset-palette asset — atlas slicing + per-tile behaviour
+ * (docs/REARCH_TILEMAP.md). The reusable asset the Tileset editor authors and the
+ * single source of truth for how a tile looks (atlas grid) AND behaves (collision
+ * shape / animation / properties). Tilemaps reference it; collision is derived from
+ * it at runtime, so editing the tileset updates every map.
+ *
+ * Mirrors the `.esanim` format seam (`AnimationClip.ts`): one in-memory model
+ * ({@link TilesetAsset}), a structure-tolerant {@link parseTileset}, and a clean
+ * {@link serializeTileset} so `parse(serialize(x))` round-trips. The schema is
+ * deliberately extensible — terrain/autotile (wang/rule) rules and physics-layer/one-way
+ * flags slot onto tiles later without a version break.
+ */
+
+/** The current `.estileset` format version. */
+export const TILESET_FORMAT_VERSION = '1';
+
+/**
+ * A tile's collision shape. `box` = the full cell AABB (greedy-merged at runtime);
+ * `polygon` = custom points in tile-local pixels (origin top-left, y-down like the atlas),
+ * for slopes / partial tiles. Absence of `collision` on a tile = no collision.
+ */
+export type TilesetCollision =
+ | { type: 'box' }
+ | { type: 'polygon'; points: [number, number][] };
+
+/** One animation frame: show tile `tile` for `durationMs` milliseconds. */
+export interface TilesetAnimFrame {
+ tile: number;
+ durationMs: number;
+}
+
+/** Per-tile metadata. Sparse — only tiles that carry any of these appear in the map. */
+export interface TilesetTile {
+ collision?: TilesetCollision;
+ properties?: Record<string, string>;
+ animation?: TilesetAnimFrame[];
+}
+
+/** A reusable tileset palette asset (`.estileset`). */
+export interface TilesetAsset {
+ version: string;
+ /** `@uuid:` ref to the atlas texture. */
+ texture: string;
+ tileWidth: number;
+ tileHeight: number;
+ /** Tiles per atlas row. */
+ columns: number;
+ /** Border (px) inside the atlas before the first tile. */
+ margin: number;
+ /** Gap (px) between adjacent tiles. */
+ spacing: number;
+ /** Total tile count (optional; otherwise derived from the texture + grid). */
+ tileCount?: number;
+ /** Per-tile metadata keyed by tile id (1-based; id 0 = empty). */
+ tiles: Record<number, TilesetTile>;
+}
+
+function posInt(v: unknown, fallback: number): number {
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback;
+}
+
+function nonNeg(v: unknown, fallback: number): number {
+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback;
+}
+
+function normalizeCollision(raw: any): TilesetCollision | undefined {
+ if (raw === true) return { type: 'box' }; // legacy / Tiled-style boolean flag
+ if (!raw || typeof raw !== 'object') return undefined;
+ if (raw.type === 'polygon' && Array.isArray(raw.points)) {
+ const points = raw.points
+ .filter((p: any) => Array.isArray(p) && p.length >= 2
+ && typeof p[0] === 'number' && typeof p[1] === 'number')
+ .map((p: any) => [p[0], p[1]] as [number, number]);
+ return points.length >= 3 ? { type: 'polygon', points } : undefined;
+ }
+ // Any other truthy collision (incl. `{type:'box'}` or a legacy `true`) = a full-cell box.
+ return { type: 'box' };
+}
+
+/** Parse arbitrary JSON into a normalized {@link TilesetAsset} (tolerant of missing fields). */
+export function parseTileset(raw: any): TilesetAsset {
+ const tiles: Record<number, TilesetTile> = {};
+ const rawTiles = (raw && typeof raw.tiles === 'object' && raw.tiles) || {};
+ for (const key of Object.keys(rawTiles)) {
+ const id = Number(key);
+ if (!Number.isInteger(id) || id <= 0) continue;
+ const t = rawTiles[key] ?? {};
+ const tile: TilesetTile = {};
+ const collision = normalizeCollision(t.collision);
+ if (collision) tile.collision = collision;
+ if (t.properties && typeof t.properties === 'object') {
+ tile.properties = {};
+ for (const k of Object.keys(t.properties)) tile.properties[k] = String(t.properties[k]);
+ }
+ if (Array.isArray(t.animation)) {
+ const frames = t.animation
+ .filter((f: any) => f && Number.isInteger(f.tile))
+ .map((f: any) => ({ tile: f.tile, durationMs: nonNeg(f.durationMs, 100) }));
+ if (frames.length > 0) tile.animation = frames;
+ }
+ if (tile.collision || tile.properties || tile.animation) tiles[id] = tile;
+ }
+ return {
+ version: typeof raw?.version === 'string' ? raw.version : TILESET_FORMAT_VERSION,
+ texture: typeof raw?.texture === 'string' ? raw.texture : '',
+ tileWidth: posInt(raw?.tileWidth, 16),
+ tileHeight: posInt(raw?.tileHeight, 16),
+ columns: posInt(raw?.columns, 1),
+ margin: nonNeg(raw?.margin, 0),
+ spacing: nonNeg(raw?.spacing, 0),
+ tileCount: Number.isInteger(raw?.tileCount) ? raw.tileCount : undefined,
+ tiles,
+ };
+}
+
+/** Serialize a {@link TilesetAsset} to a plain JSON-ready object (drops empty/undefined). */
+export function serializeTileset(asset: TilesetAsset): Record<string, unknown> {
+ const tiles: Record<string, TilesetTile> = {};
+ for (const id of Object.keys(asset.tiles)) tiles[id] = asset.tiles[Number(id)];
+ const out: Record<string, unknown> = {
+ version: asset.version || TILESET_FORMAT_VERSION,
+ texture: asset.texture,
+ tileWidth: asset.tileWidth,
+ tileHeight: asset.tileHeight,
+ columns: asset.columns,
+ margin: asset.margin,
+ spacing: asset.spacing,
+ tiles,
+ };
+ if (asset.tileCount !== undefined) out.tileCount = asset.tileCount;
+ return out;
+}
+
+/** A fresh tileset over a texture (no per-tile metadata yet). */
+export function createTileset(
+ texture: string, tileWidth = 16, tileHeight = 16, columns = 1,
+): TilesetAsset {
+ return {
+ version: TILESET_FORMAT_VERSION,
+ texture, tileWidth, tileHeight, columns,
+ margin: 0, spacing: 0, tiles: {},
+ };
+}
+
+/**
+ * The tile ids flagged collidable — feeds `generateLayerCollision` (the box-merge set) and
+ * the Tiled-style `collisionTileIds`. Polygon tiles are included (their custom shape is
+ * emitted separately at collider-build time).
+ */
+export function collidableTileIds(asset: TilesetAsset): number[] {
+ return Object.keys(asset.tiles)
+ .map(Number)
+ .filter((id) => asset.tiles[id].collision !== undefined)
+ .sort((a, b) => a - b);
+}
diff --git a/sdk/tests/tileset-asset.test.ts b/sdk/tests/tileset-asset.test.ts
new file mode 100644
index 000000000..f4df83434
--- /dev/null
+++ b/sdk/tests/tileset-asset.test.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import {
+ TILESET_FORMAT_VERSION,
+ parseTileset,
+ serializeTileset,
+ createTileset,
+ collidableTileIds,
+ type TilesetAsset,
+} from '../src/tilemap/tilesetAsset';
+
+describe('tilesetAsset (.estileset format)', () => {
+ describe('createTileset', () => {
+ it('makes a fresh tileset with defaults and no tiles', () => {
+ const ts = createTileset('@uuid:abc', 16, 16, 8);
+ expect(ts).toEqual({
+ version: TILESET_FORMAT_VERSION,
+ texture: '@uuid:abc',
+ tileWidth: 16, tileHeight: 16, columns: 8,
+ margin: 0, spacing: 0, tiles: {},
+ });
+ });
+ });
+
+ describe('parseTileset', () => {
+ it('fills sane defaults from an empty object', () => {
+ const ts = parseTileset({});
+ expect(ts.version).toBe(TILESET_FORMAT_VERSION);
+ expect(ts.texture).toBe('');
+ expect(ts.tileWidth).toBe(16);
+ expect(ts.columns).toBe(1);
+ expect(ts.tiles).toEqual({});
+ });
+
+ it('keeps a box collision and normalizes a legacy truthy collision to a box', () => {
+ const ts = parseTileset({
+ texture: '@uuid:x', tileWidth: 32, tileHeight: 32, columns: 4,
+ tiles: { 5: { collision: { type: 'box' } }, 7: { collision: true } },
+ });
+ expect(ts.tiles[5].collision).toEqual({ type: 'box' });
+ expect(ts.tiles[7].collision).toEqual({ type: 'box' });
+ });
+
+ it('keeps a valid polygon and drops a degenerate (<3 point) one', () => {
+ const ts = parseTileset({
+ tiles: {
+ 9: { collision: { type: 'polygon', points: [[0, 0], [16, 0], [16, 8]] } },
+ 10: { collision: { type: 'polygon', points: [[0, 0], [1, 1]] } },
+ },
+ });
+ expect(ts.tiles[9].collision).toEqual({ type: 'polygon', points: [[0, 0], [16, 0], [16, 8]] });
+ expect(ts.tiles[10]).toBeUndefined(); // degenerate polygon → no collision → empty tile dropped
+ });
+
+ it('drops empty tile entries and non-positive ids', () => {
+ const ts = parseTileset({
+ tiles: { 0: { collision: { type: 'box' } }, 3: {}, 4: { properties: { a: 'b' } } },
+ });
+ expect(ts.tiles[0]).toBeUndefined(); // id 0 = empty, never carries metadata
+ expect(ts.tiles[3]).toBeUndefined(); // no metadata → dropped
+ expect(ts.tiles[4]).toEqual({ properties: { a: 'b' } });
+ });
+
+ it('normalizes animation frames and coerces property values to strings', () => {
+ const ts = parseTileset({
+ tiles: {
+ 2: {
+ animation: [{ tile: 2, durationMs: 100 }, { tile: 3 }, { foo: 1 }],
+ properties: { hp: 5 },
+ },
+ },
+ });
+ expect(ts.tiles[2].animation).toEqual([
+ { tile: 2, durationMs: 100 },
+ { tile: 3, durationMs: 100 },
+ ]);
+ expect(ts.tiles[2].properties).toEqual({ hp: '5' });
+ });
+ });
+
+ describe('round-trip', () => {
+ it('parse(serialize(x)) is identity over a rich tileset', () => {
+ const original: TilesetAsset = {
+ version: '1', texture: '@uuid:t', tileWidth: 16, tileHeight: 16,
+ columns: 8, margin: 1, spacing: 2, tileCount: 64,
+ tiles: {
+ 5: { collision: { type: 'box' } },
+ 12: { collision: { type: 'polygon', points: [[0, 0], [16, 0], [16, 16]] }, properties: { kind: 'slope' } },
+ 20: { animation: [{ tile: 20, durationMs: 80 }, { tile: 21, durationMs: 80 }] },
+ },
+ };
+ expect(parseTileset(serializeTileset(original))).toEqual(original);
+ });
+ });
+
+ describe('collidableTileIds', () => {
+ it('returns sorted ids of box and polygon tiles, excluding non-collision', () => {
+ const ts = parseTileset({
+ tiles: {
+ 20: { collision: { type: 'box' } },
+ 5: { collision: { type: 'polygon', points: [[0, 0], [1, 0], [1, 1]] } },
+ 8: { properties: { a: 'b' } }, // not collidable
+ },
+ });
+ expect(collidableTileIds(ts)).toEqual([5, 20]);
+ });
+ });
+});