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): multi-tileset painting - a layer paints from multiple tilesets

yhhaa804537c3e6
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index bfc9ab2ee..1ecd36325 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -15,7 +15,7 @@ import {
FlipHorizontal, FlipVertical, RotateCw, Mountain,
} from 'lucide-react';
import { parseTileset, encodeTile, type TilesetAsset } from 'esengine';
-import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';
+import { useTilemapPaint, type PaintTool, type PaletteTileset } from '@/store/tilemapPaintStore';
import { useSelection } from '@/store/selectionStore';
import { SceneModel } from '@/engine/SceneModel';
import { ProjectStore } from '@/project/ProjectStore';
@@ -43,14 +43,27 @@ const TOOLS: { id: PaintTool; icon: typeof Brush; label: string }[] = [
const TERRAIN_COLORS = ['#4caf50', '#d6884c', '#4c8fd6', '#b14cd6', '#d6c64c', '#d64c6e'];
-/** Resolve the .estileset path a selected TilemapLayer references (its `tilesetAsset` @uuid). */
-function selectedTilemapTilesetPath(selectedId: number | null): string | null {
- if (selectedId == null) return null;
+/** Resolve the .estileset ref(s) a selected TilemapLayer references — the `tilesetAssets`
+ * list (multi-tileset) or the singular `tilesetAsset` — as @uuid refs (not yet paths). */
+function selectedTilemapTilesetRefs(selectedId: number | null): string[] {
+ if (selectedId == null) return [];
const e = SceneModel.entityBySource(selectedId);
const layer = e?.components.find((c) => c.type === 'TilemapLayer');
- if (!layer) return null;
- const ref = (layer.data as Record<string, unknown>).tilesetAsset;
- return typeof ref === 'string' ? (ProjectStore.assetInfo(ref)?.path ?? null) : null;
+ if (!layer) return [];
+ const data = layer.data as Record<string, unknown>;
+ const list = data.tilesetAssets;
+ if (Array.isArray(list)) return list.filter((r): r is string => typeof r === 'string' && r !== '');
+ return typeof data.tilesetAsset === 'string' && data.tilesetAsset ? [data.tilesetAsset] : [];
+}
+
+/** Natural pixel size of an image URL (for deriving a tileset's rows → tile count). */
+function loadImageDims(url: string): Promise<{ w: number; h: number }> {
+ return new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => resolve({ w: img.naturalWidth, h: img.naturalHeight });
+ img.onerror = () => resolve({ w: 0, h: 0 });
+ img.src = url;
+ });
}
interface SelRect { c0: number; r0: number; c1: number; r1: number }
@@ -60,18 +73,41 @@ const normRect = (a: { c: number; r: number }, b: { c: number; r: number }): Sel
export function TilemapPainter() {
const {
- tilesetPath, stamp, tool, terrainSet,
- setTileset, setTilesetAsset, setStamp, setTool, setTerrainSet, flipH, flipV, rotateCW,
+ tilesetPath, tilesets, activeTileset, stamp, tool, terrainSet,
+ setTilesets, setActiveTileset, setTilesetAsset, setStamp, setTool, setTerrainSet, flipH, flipV, rotateCW,
} = useTilemapPaint();
const selectedId = useSelection((s) => s.selectedId);
const hasTilemap = selectedId != null
&& !!SceneModel.entityBySource(selectedId)?.components.some((c) => c.type === 'TilemapLayer');
- // Selecting a TilemapLayer loads its referenced .estileset as the active palette.
+ // Selecting a TilemapLayer loads ALL its referenced .estileset(s) into the palette,
+ // each assigned its firstId (matching resolveTilesetModel's running sum), so the tab
+ // bar can switch between them and painted cells encode to the right global gid.
useEffect(() => {
- const path = selectedTilemapTilesetPath(selectedId);
- if (path && path !== tilesetPath) setTileset(path);
- }, [selectedId, tilesetPath, setTileset]);
+ const paths = selectedTilemapTilesetRefs(selectedId)
+ .map((r) => ProjectStore.assetInfo(r)?.path).filter((p): p is string => !!p);
+ if (paths.length === 0) { setTilesets([]); return; }
+ let alive = true;
+ void (async () => {
+ const entries: PaletteTileset[] = [];
+ let firstId = 1;
+ for (const path of paths) {
+ try {
+ const a = parseTileset(JSON.parse(await window.estella.fs.read(path)));
+ entries.push({ path, asset: a, firstId });
+ let count = a.tileCount ?? 0;
+ if (count <= 0) {
+ const url = `estella://project/${ProjectStore.assetInfo(a.texture)?.path ?? ''}`;
+ const dims = await loadImageDims(url);
+ count = a.columns * rowsFor(dims.h, a.tileHeight, a.margin, a.spacing);
+ }
+ firstId += Math.max(1, count);
+ } catch { /* skip a bad tileset */ }
+ }
+ if (alive) setTilesets(entries);
+ })();
+ return () => { alive = false; };
+ }, [selectedId, setTilesets]);
const [asset, setAsset] = useState<TilesetAsset | null>(null);
useEffect(() => {
@@ -135,6 +171,9 @@ export function TilemapPainter() {
const sp = asset?.spacing ?? 0;
const cols = natural ? colsFor(natural.w, tw, mg, sp) : (asset?.columns ?? 1);
const rows = natural ? rowsFor(natural.h, th, mg, sp) : 0;
+ // Global tile-id base of the active tileset — a cell's gid = firstId + (row*cols + col),
+ // so the renderer resolves it back to THIS tileset (single-tileset layers have firstId 1).
+ const activeFirstId = tilesets[activeTileset]?.firstId ?? 1;
const commitSel = (r: SelRect) => {
const w = r.c1 - r.c0 + 1;
@@ -142,7 +181,7 @@ export function TilemapPainter() {
const cells: number[] = [];
for (let dy = 0; dy < h; dy++) {
for (let dx = 0; dx < w; dx++) {
- cells.push(encodeTile((r.r0 + dy) * cols + (r.c0 + dx) + 1));
+ cells.push(encodeTile((r.r0 + dy) * cols + (r.c0 + dx) + activeFirstId));
}
}
setStamp({ w, h, cells });
@@ -161,7 +200,7 @@ export function TilemapPainter() {
if (texUrl && natural) {
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
- const id = row * cols + col + 1;
+ const id = row * cols + col + activeFirstId;
cells.push(
<div
key={id}
@@ -209,6 +248,21 @@ export function TilemapPainter() {
<span className="tp-grow" />
<span className="tp-brush">{tool === 'terrain' ? '地形画笔' : `刷子 ${stamp.w}×${stamp.h}`}</span>
</div>
+ {tilesets.length > 1 && tool !== 'terrain' && (
+ <div className="tp-tilesets">
+ {tilesets.map((ts, i) => (
+ <button
+ key={ts.path}
+ type="button"
+ className={'tp-tsbtn' + (i === activeTileset ? ' is-active' : '')}
+ title={`${ts.path} (gid ${ts.firstId}+)`}
+ onClick={() => setActiveTileset(i)}
+ >
+ {ts.path.split(/[\\/]/).pop()?.replace(/\.estileset$/, '') ?? `瓦片集 ${i + 1}`}
+ </button>
+ ))}
+ </div>
+ )}
{tool === 'terrain' ? (
<div className="tp-terrains">
{(asset?.terrains ?? []).length === 0 ? (
diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.ts
index 345cfc39d..648eb6dc3 100644
--- a/desktop/src/store/tilemapPaintStore.ts
+++ b/desktop/src/store/tilemapPaintStore.ts
@@ -16,6 +16,15 @@ import {
export type PaintTool = 'brush' | 'erase' | 'rect' | 'line' | 'bucket' | 'select' | 'eyedropper' | 'terrain';
+/** One tileset in the active layer's palette: its `.estileset` path, parsed asset, and
+ * the GLOBAL tile-id base (firstId) it occupies — matching the runtime tileset model, so
+ * a cell painted from this tileset encodes to the gid the renderer resolves back to it. */
+export interface PaletteTileset {
+ path: string;
+ asset: TilesetAsset;
+ firstId: number;
+}
+
/** A rectangular tile-grid selection (inclusive corners, unordered). */
export interface TileRect {
x0: number;
@@ -25,7 +34,11 @@ export interface TileRect {
}
interface TilemapPaintState {
- /** Active `.estileset` palette (project-relative path), or null. */
+ /** The active layer's tilesets, in firstId order (one entry = a single-tileset layer). */
+ tilesets: PaletteTileset[];
+ /** Index into `tilesets` of the palette the painter shows + paints from. */
+ activeTileset: number;
+ /** Active `.estileset` palette (project-relative path), or null. Mirrors tilesets[activeTileset]. */
tilesetPath: string | null;
/** The parsed active palette asset (kept here so the viewport terrain tool can resolve). */
tilesetAsset: TilesetAsset | null;
@@ -39,6 +52,10 @@ interface TilemapPaintState {
clipboard: TileStamp | null;
/** The active tool; null = not painting (the Viewport selects normally). */
tool: PaintTool | null;
+ /** Replace the active layer's palette list (from its tilesetAssets); resets active to 0. */
+ setTilesets(tilesets: PaletteTileset[]): void;
+ /** Switch which tileset in the list the palette shows/paints from. */
+ setActiveTileset(index: number): void;
setTileset(path: string | null): void;
setTilesetAsset(asset: TilesetAsset | null): void;
setStamp(stamp: TileStamp): void;
@@ -54,6 +71,8 @@ interface TilemapPaintState {
}
export const useTilemapPaint = create<TilemapPaintState>((set) => ({
+ tilesets: [],
+ activeTileset: 0,
tilesetPath: null,
tilesetAsset: null,
stamp: singleStamp(encodeTile(1)),
@@ -61,6 +80,16 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({
selection: null,
clipboard: null,
tool: null,
+ setTilesets: (tilesets) => set({
+ tilesets,
+ activeTileset: 0,
+ tilesetPath: tilesets[0]?.path ?? null,
+ tilesetAsset: tilesets[0]?.asset ?? null,
+ }),
+ setActiveTileset: (index) => set((s) => {
+ const ts = s.tilesets[index];
+ return ts ? { activeTileset: index, tilesetPath: ts.path, tilesetAsset: ts.asset } : {};
+ }),
setTileset: (tilesetPath) => set({ tilesetPath }),
setTilesetAsset: (tilesetAsset) => set({ tilesetAsset }),
setStamp: (stamp) => set({ stamp }),
diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.css
index e64230eb4..92da44164 100644
--- a/desktop/src/theme/tilemap.css
+++ b/desktop/src/theme/tilemap.css
@@ -76,6 +76,29 @@
}
.tp-terrain.is-active { border-color: var(--star, #4c8fd6); color: var(--text, #d6d9de); }
.tp-tswatch { width: 12px; height: 12px; border-radius: 2px; display: inline-block; }
+
+/* Multi-tileset tab bar — switch which of the layer's tilesets the palette paints from. */
+.tp-tilesets {
+ display: flex;
+ gap: 4px;
+ padding: 6px 8px;
+ overflow-x: auto;
+ background: var(--srf-0, #101216);
+ border-bottom: 1px solid var(--line, #2a2d33);
+}
+.tp-tsbtn {
+ flex: 0 0 auto;
+ background: var(--control, #24272d);
+ border: 1px solid var(--line, #2a2d33);
+ border-radius: 3px;
+ color: var(--text-dim, #9aa0aa);
+ padding: 3px 9px;
+ cursor: pointer;
+ font: inherit;
+ white-space: nowrap;
+}
+.tp-tsbtn:hover { color: var(--text, #d6d9de); border-color: var(--control-hover, #333740); }
+.tp-tsbtn.is-active { border-color: var(--star, #4c8fd6); color: var(--text, #d6d9de); }
.tp-warn { color: var(--text-faint, #6b717c); padding: 12px; font-size: 11px; }
.tp-cell {
diff --git a/sdk/src/asset/loaders/TilesetAssetLoader.ts b/sdk/src/asset/loaders/TilesetAssetLoader.ts
index fa5602f12..943826b04 100644
--- a/sdk/src/asset/loaders/TilesetAssetLoader.ts
+++ b/sdk/src/asset/loaders/TilesetAssetLoader.ts
@@ -22,16 +22,20 @@ export class TilesetAssetLoader implements AssetLoader<TilesetResult> {
// 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);
}
}
- registerResolvedTileset(path, { asset, textureHandle });
+ registerResolvedTileset(path, { asset, textureHandle, textureWidth, textureHeight });
return { tilesetId: path };
}
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 82f6896e7..a8fbca521 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -759,8 +759,15 @@ export const TilemapLayer = defineBuiltin<TilemapLayerData>('TilemapLayer',
const refs: AssetRef[] = [];
const texture = data.tileset;
if (typeof texture === 'string' && texture) refs.push({ type: 'texture', path: texture });
- const ref = data.tilesetAsset;
- if (typeof ref === 'string' && ref) refs.push({ type: 'tileset', path: ref });
+ // `tilesetAssets` (a list of `.estileset` refs) is the multi-tileset model;
+ // fall back to the singular `tilesetAsset` for older single-tileset layers.
+ const list = (data as { tilesetAssets?: unknown }).tilesetAssets;
+ if (Array.isArray(list) && list.length > 0) {
+ for (const r of list) if (typeof r === 'string' && r) refs.push({ type: 'tileset', path: r });
+ } else {
+ const ref = data.tilesetAsset;
+ if (typeof ref === 'string' && ref) refs.push({ type: 'tileset', path: ref });
+ }
return refs;
},
},
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 84cb4f81e..944c6be5a 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -43,8 +43,10 @@ export class TilemapPlugin implements Plugin {
private nativeCollisionIds_ = new Map<number, number[]>();
/** TilemapLayer entity → per-tile polygon collision outlines (global id → normalized points). */
private nativePolygonShapes_ = new Map<number, Map<number, [number, number][]>>();
- /** TilemapLayer entity → its `.estileset` ref (out-of-band; resolved live → table/collision/anim). */
- private tilesetRefs_ = new Map<number, string>();
+ /** TilemapLayer entity → its `.estileset` refs, in firstId order (out-of-band; the
+ * whole list resolves live → multi-slot table/collision/anim). One entry = the
+ * common single-tileset layer. */
+ private tilesetRefs_ = new Map<number, string[]>();
/** Entities whose `.estileset` has been resolved+applied (so we do it once per load). */
private liveResolved_ = new Set<number>();
/** Resolved `.estileset` paths a load has already been kicked off for (de-dupes the lazy load). */
@@ -70,10 +72,15 @@ export class TilemapPlugin implements Plugin {
// runtime can derive collision; it isn't a C++ component field.
const ids = nativeCollisionIds.get(entity);
if (ids && ids.length > 0) data.collidableTileIds = ids.slice();
- const ref = tilesetRefs.get(entity);
- if (ref) data.tilesetAsset = ref;
+ const refs = tilesetRefs.get(entity);
+ if (refs && refs.length > 0) {
+ data.tilesetAssets = refs.slice();
+ // Back-compat: keep the singular field (first tileset) so an older
+ // runtime still renders the primary tileset.
+ data.tilesetAsset = refs[0];
+ }
},
- outOfBandFields: ['chunks', 'collidableTileIds', 'tilesetAsset'],
+ outOfBandFields: ['chunks', 'collidableTileIds', 'tilesetAsset', 'tilesetAssets'],
importData: (entity, outOfBand) => {
const blob = outOfBand.chunks;
if (typeof blob === 'string' && blob !== '') {
@@ -85,11 +92,19 @@ export class TilemapPlugin implements Plugin {
} else {
nativeCollisionIds.delete(entity);
}
- // The `.estileset` reference: resolved live in the sync (table + collision
- // + animations) instead of trusting the baked collidableTileIds snapshot.
- const ref = outOfBand.tilesetAsset;
- if (typeof ref === 'string' && ref !== '') {
- tilesetRefs.set(entity, ref);
+ // The `.estileset` reference(s): resolved live in the sync (multi-slot
+ // table + collision + animations). Accept the new `tilesetAssets` list;
+ // fall back to the singular `tilesetAsset` (old scenes).
+ const list = outOfBand.tilesetAssets;
+ const single = outOfBand.tilesetAsset;
+ let refs: string[] | undefined;
+ if (Array.isArray(list)) {
+ refs = list.filter((r): r is string => typeof r === 'string' && r !== '');
+ } else if (typeof single === 'string' && single !== '') {
+ refs = [single];
+ }
+ if (refs && refs.length > 0) {
+ tilesetRefs.set(entity, refs);
} else {
tilesetRefs.delete(entity);
}
@@ -152,9 +167,9 @@ export class TilemapPlugin implements Plugin {
const layerData = world.tryGet(entity, TilemapLayer) as TilemapLayerData | null;
if (!layerData) continue;
- const tilesetRef = tilesetRefs.get(entity);
- // A layer needs either a copied texture (legacy) or a .estileset ref.
- if (!layerData.tileset && !tilesetRef) continue;
+ const refs = tilesetRefs.get(entity);
+ // A layer needs either a copied texture (legacy) or .estileset ref(s).
+ if (!layerData.tileset && (!refs || refs.length === 0)) continue;
// RC2a: the TilemapLayer component is the single source of visual
// metadata; the C++ renderer reads tint/opacity/tileset/columns/
@@ -169,14 +184,28 @@ export class TilemapPlugin implements Plugin {
initializedLayers.add(entity);
}
- // Live tileset: when the layer references a `.estileset` that has loaded,
- // derive its render table + animations + collision LIVE (once per load) —
- // replacing the copied columns and the baked collidableTileIds snapshot.
- if (tilesetRef && !liveResolved.has(entity)) {
- const tilesetKey = resolveAssetKey(assets, tilesetRef);
- const resolved = getResolvedTileset(tilesetKey) ?? getResolvedTileset(tilesetRef);
- if (resolved) {
- const model = resolveTilesetModel([resolved]);
+ // Live tileset(s): when ALL the layer's `.estileset` refs have loaded,
+ // derive its multi-slot render table + animations + collision LIVE (once
+ // per load) — replacing copied columns + the baked collidableTileIds. The
+ // whole list must resolve together so firstId ranges are contiguous.
+ if (refs && refs.length > 0 && !liveResolved.has(entity)) {
+ const resolvedList = [];
+ for (const ref of refs) {
+ const key = resolveAssetKey(assets, ref);
+ const r = getResolvedTileset(key) ?? getResolvedTileset(ref);
+ if (r) {
+ resolvedList.push(r);
+ } else if (assets && !requestedTilesetLoads.has(key)) {
+ // Out-of-band ref (invisible to scene asset discovery) — kick
+ // the load; once it lands we resolve live next frame.
+ requestedTilesetLoads.add(key);
+ assets.load('tileset', ref).catch((e) => {
+ log.warn('tilemap', `failed to load tileset asset '${ref}'`, e);
+ });
+ }
+ }
+ if (resolvedList.length === refs.length) {
+ const model = resolveTilesetModel(resolvedList);
TilemapAPI.setTilesets(entity, model.slots);
for (const [tileId, frames] of model.animations) {
TilemapAPI.setTileAnimation(entity, tileId, frames);
@@ -189,16 +218,6 @@ export class TilemapPlugin implements Plugin {
nativePolygonShapes.set(entity, model.polygonShapes);
}
liveResolved.add(entity);
- } else if (assets && !requestedTilesetLoads.has(tilesetKey)) {
- // The `.estileset` is referenced but not loaded. It's an
- // out-of-band ref (invisible to scene asset discovery), so
- // nothing preloads it — kick the load off here (the loader
- // resolves the ref itself). Once it lands getResolvedTileset()
- // hits next frame and we resolve live.
- requestedTilesetLoads.add(tilesetKey);
- assets.load('tileset', tilesetRef).catch((e) => {
- log.warn('tilemap', `failed to load tileset asset '${tilesetRef}'`, e);
- });
}
}
diff --git a/sdk/src/tilemap/tilesetResolve.ts b/sdk/src/tilemap/tilesetResolve.ts
index a274373e6..522562aa1 100644
--- a/sdk/src/tilemap/tilesetResolve.ts
+++ b/sdk/src/tilemap/tilesetResolve.ts
@@ -22,6 +22,11 @@ import type { TilesetAsset } from './tilesetAsset';
export interface ResolvedTileset {
asset: TilesetAsset;
textureHandle: number;
+ /** Atlas texture pixel size, when known — lets the tile count (and thus the
+ * multi-tileset firstId span) be derived from the grid without an explicit
+ * `tileCount` on the asset. */
+ textureWidth?: number;
+ textureHeight?: number;
}
/** One render-table slot: a tileset's global id base, atlas texture, and grid width. */
@@ -46,9 +51,21 @@ export interface TilesetModel {
polygonShapes: Map<number, [number, number][]>;
}
-/** Tiles in a tileset: explicit `tileCount`, else the highest authored tile id. */
-function tilesetCount(asset: TilesetAsset): number {
+/**
+ * Tiles in a tileset — the span its global ids occupy. Explicit `tileCount` wins;
+ * else derive `columns × rows` from the atlas texture height (the correct span for
+ * a full grid, so multiple tilesets get non-overlapping firstId ranges); else fall
+ * back to the highest authored tile id (single-tileset maps never hit the collision).
+ */
+function tilesetCount(asset: TilesetAsset, textureHeight?: number): number {
if (typeof asset.tileCount === 'number' && asset.tileCount > 0) return asset.tileCount;
+ if (typeof textureHeight === 'number' && textureHeight > 0) {
+ const th = asset.tileHeight || 1;
+ const m = asset.margin || 0;
+ const sp = asset.spacing || 0;
+ const rows = Math.max(1, Math.floor((textureHeight - 2 * m + sp) / (th + sp)));
+ return Math.max(1, asset.columns * rows);
+ }
let max = 0;
for (const k of Object.keys(asset.tiles)) max = Math.max(max, Number(k));
return max; // local ids are 1-based, so the max id == count of the spanned range
@@ -66,7 +83,7 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {
const polygonShapes = new Map<number, [number, number][]>();
let firstId = 1;
- for (const { asset, textureHandle } of tilesets) {
+ for (const { asset, textureHandle, textureHeight } of tilesets) {
slots.push({ firstId, textureHandle, columns: asset.columns });
const tw = asset.tileWidth || 1;
const th = asset.tileHeight || 1;
@@ -93,7 +110,7 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {
}
}
- firstId += Math.max(1, tilesetCount(asset));
+ firstId += Math.max(1, tilesetCount(asset, textureHeight));
}
collidable.sort((a, b) => a - b);
diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.ts
index 96214cb11..b46088998 100644
--- a/sdk/tests/tilemap.test.ts
+++ b/sdk/tests/tilemap.test.ts
@@ -19,6 +19,8 @@ import {
type TiledObjectData, type TiledObjectGroupData,
} from '../src/tilemap/tiledLoader';
import type { TiledMapData } from '../src/tilemap/tiledLoader';
+import { resolveTilesetModel } from '../src/tilemap/tilesetResolve';
+import type { TilesetAsset } from '../src/tilemap/tilesetAsset';
import { mergeCollisionTiles } from '../src/tilemap/collisionMerge';
import { BodyType } from '../src/physics/PhysicsComponents';
import { clearUserComponents } from '../src/component';
@@ -607,6 +609,20 @@ describe('parseTmjJson — Phase B: objectgroup parsing', () => {
expect(result.objectGroups[0].objects[1].gid).toBeUndefined();
});
+ it('resolveTilesetModel: multiple tilesets get non-overlapping firstId ranges from texture height', () => {
+ const mk = (columns: number, tileH: number): TilesetAsset => ({
+ version: '1', texture: '', tileWidth: tileH, tileHeight: tileH,
+ columns, margin: 0, spacing: 0, tiles: {},
+ });
+ // A: 4 cols, 64px tall / 16px tiles → 4 rows → 16 tiles → firstId 1, then +16.
+ // B: 2 cols, 32px tall / 16px tiles → 2 rows → 4 tiles → firstId 17.
+ const model = resolveTilesetModel([
+ { asset: mk(4, 16), textureHandle: 1, textureHeight: 64 },
+ { asset: mk(2, 16), textureHandle: 2, textureHeight: 32 },
+ ]);
+ expect(model.slots.map((s) => s.firstId)).toEqual([1, 17]); // pre-fix: [1, 2] (collision)
+ });
+
it('decodeTiledGid splits the global id + H/V/D flip flags', () => {
expect(decodeTiledGid(5)).toEqual({ globalId: 5, flipH: false, flipV: false, flipD: false });
// Tiled packs flips in the high bits: H=0x80000000, V=0x40000000, D=0x20000000.