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(editor): add/remove tilesets on a layer, live

yhha727571cf7bb
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 8559ef5a1..cb27aa5c1 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { SceneData, PrefabData, ProcessedEntity } from 'esengine';
-import { TilemapAPI, UIPositionType, DimensionUnit } from 'esengine';
+import { TilemapAPI, TilemapLiveSync, UIPositionType, DimensionUnit } from 'esengine';
import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';
import { EditorHistory, EditorHistoryImpl } from './EditorHistory';
import { SceneModel, SceneModelImpl } from './SceneModel';
@@ -997,6 +997,37 @@ export class SceneCommandsImpl {
if (rt !== undefined) TilemapAPI.importChunks(rt, s.before);
}
+ /**
+ * Set the `.estileset` ref list a TilemapLayer paints/renders from (its multi-tileset
+ * `tilesetAssets`). Like the chunks blob, this is out-of-band data, so — mirroring the
+ * paint commit — we write BOTH the model (for save / undo / play-rebuild) AND push the
+ * list to the running tilemap plugin live via {@link TilemapLiveSync}. The reconciler
+ * can't carry an out-of-band field, so without the live push the viewport would keep
+ * rendering the old tilesets until a reload. One undo step; empty list clears the refs.
+ */
+ setLayerTilesets(sourceId: EntityId, refs: string[]): void {
+ const e = this.model.entityBySource(sourceId);
+ if (!e) return;
+ const data = (e.components.find((c) => c.type === 'TilemapLayer')?.data ?? {}) as Record<string, unknown>;
+ const cur = Array.isArray(data.tilesetAssets)
+ ? (data.tilesetAssets as unknown[]).filter((r): r is string => typeof r === 'string' && r !== '')
+ : (typeof data.tilesetAsset === 'string' && data.tilesetAsset ? [data.tilesetAsset] : []);
+ const next = refs.filter((r) => typeof r === 'string' && r !== '');
+ if (valueEqual(cur, next)) return;
+
+ const apply = (list: string[]) => {
+ // Model: out-of-band (carried like the chunks blob). Keep the singular `tilesetAsset`
+ // in sync as the back-compat first tileset; an empty list deletes both keys.
+ this.model.setField(sourceId, 'TilemapLayer', 'tilesetAssets', list.length > 0 ? list.slice() : undefined);
+ this.model.setField(sourceId, 'TilemapLayer', 'tilesetAsset', list[0]);
+ // Runtime: the reconciler drops out-of-band fields, so push straight to the plugin.
+ const rt = this.model.runtimeFor(sourceId);
+ if (rt !== undefined) TilemapLiveSync.setLayerTilesets(rt, list);
+ };
+ apply(next);
+ this.history.record('Set Tilesets', () => apply(next), () => apply(cur));
+ }
+
// Shared commit: snapshot the post-edit blob, write it to the model (the truth
// for save + rebuild), and record one undo step whose closures re-resolve the
// runtime entity (it changes across a play→stop rebuild) and re-import the blob.
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index 1ecd36325..417416195 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -12,12 +12,13 @@
import { useEffect, useRef, useState } from 'react';
import {
Brush, Eraser, Square, Slash, PaintBucket, BoxSelect, Pipette,
- FlipHorizontal, FlipVertical, RotateCw, Mountain,
+ FlipHorizontal, FlipVertical, RotateCw, Mountain, Plus, X,
} from 'lucide-react';
import { parseTileset, encodeTile, type TilesetAsset } from 'esengine';
import { useTilemapPaint, type PaintTool, type PaletteTileset } from '@/store/tilemapPaintStore';
import { useSelection } from '@/store/selectionStore';
import { SceneModel } from '@/engine/SceneModel';
+import { SceneCommands } from '@/engine/SceneCommands';
import { ProjectStore } from '@/project/ProjectStore';
import { copySelection, cutSelection, deleteSelection, pasteClipboard } from '@/tools/tileClipboard';
@@ -79,6 +80,10 @@ export function TilemapPainter() {
const selectedId = useSelection((s) => s.selectedId);
const hasTilemap = selectedId != null
&& !!SceneModel.entityBySource(selectedId)?.components.some((c) => c.type === 'TilemapLayer');
+ // Bumped after add/remove tileset: the layer's `tilesetAssets` changed but selectedId
+ // did not, so the palette-load effect below wouldn't otherwise re-read the new list.
+ const [reloadKey, setReloadKey] = useState(0);
+ const [addOpen, setAddOpen] = useState(false);
// Selecting a TilemapLayer loads ALL its referenced .estileset(s) into the palette,
// each assigned its firstId (matching resolveTilesetModel's running sum), so the tab
@@ -107,7 +112,7 @@ export function TilemapPainter() {
if (alive) setTilesets(entries);
})();
return () => { alive = false; };
- }, [selectedId, setTilesets]);
+ }, [selectedId, setTilesets, reloadKey]);
const [asset, setAsset] = useState<TilesetAsset | null>(null);
useEffect(() => {
@@ -156,6 +161,15 @@ export function TilemapPainter() {
return () => window.removeEventListener('keydown', onKey);
}, []);
+ // Dismiss the add-tileset menu on any outside click (the menu + its opener stop
+ // their own pointerdown so those don't self-close it).
+ useEffect(() => {
+ if (!addOpen) return;
+ const close = () => setAddOpen(false);
+ window.addEventListener('pointerdown', close);
+ return () => window.removeEventListener('pointerdown', close);
+ }, [addOpen]);
+
if (!hasTilemap) {
return (
<div className="tp-empty">
@@ -196,6 +210,24 @@ export function TilemapPainter() {
const inSel = (col: number, row: number): boolean =>
sel != null && col >= sel.c0 && col <= sel.c1 && row >= sel.r0 && row <= sel.r1;
+ // Add/remove a tileset on the selected layer (writes `tilesetAssets` + live-syncs the
+ // runtime), then reload the palette. Refs are @uuid, in firstId order == tab order.
+ const addTileset = (ref: string) => {
+ if (selectedId == null) return;
+ SceneCommands.setLayerTilesets(selectedId, [...selectedTilemapTilesetRefs(selectedId), ref]);
+ setAddOpen(false);
+ setReloadKey((k) => k + 1);
+ };
+ const removeTilesetAt = (i: number) => {
+ if (selectedId == null) return;
+ SceneCommands.setLayerTilesets(selectedId, selectedTilemapTilesetRefs(selectedId).filter((_, j) => j !== i));
+ setReloadKey((k) => k + 1);
+ };
+ // The project's .estileset assets not already on this layer (populated on open).
+ const addable = addOpen
+ ? ProjectStore.listAssets('tileset').filter((a) => !selectedTilemapTilesetRefs(selectedId).includes(a.ref))
+ : [];
+
const cells = [];
if (texUrl && natural) {
for (let row = 0; row < rows; row++) {
@@ -248,19 +280,42 @@ export function TilemapPainter() {
<span className="tp-grow" />
<span className="tp-brush">{tool === 'terrain' ? '地形画笔' : `刷子 ${stamp.w}×${stamp.h}`}</span>
</div>
- {tilesets.length > 1 && tool !== 'terrain' && (
+ {tool !== 'terrain' && (
<div className="tp-tilesets">
{tilesets.map((ts, i) => (
- <button
+ <span
key={ts.path}
- type="button"
- className={'tp-tsbtn' + (i === activeTileset ? ' is-active' : '')}
+ className={'tp-tschip' + (i === activeTileset ? ' is-active' : '')}
title={`${ts.path} (gid ${ts.firstId}+)`}
- onClick={() => setActiveTileset(i)}
>
- {ts.path.split(/[\\/]/).pop()?.replace(/\.estileset$/, '') ?? `瓦片集 ${i + 1}`}
- </button>
+ <button type="button" className="tp-tsbtn" onClick={() => setActiveTileset(i)}>
+ {ts.path.split(/[\\/]/).pop()?.replace(/\.estileset$/, '') ?? `瓦片集 ${i + 1}`}
+ </button>
+ {tilesets.length > 1 && (
+ <button type="button" className="tp-tsx" title="移除图集" onClick={() => removeTilesetAt(i)}>
+ <X size={11} />
+ </button>
+ )}
+ </span>
))}
+ <div className="tp-tsadd-wrap" onPointerDown={(e) => e.stopPropagation()}>
+ <button type="button" className="tp-tsadd" title="添加图集" onClick={() => setAddOpen((o) => !o)}>
+ <Plus size={13} />
+ </button>
+ {addOpen && (
+ <div className="tp-tsmenu">
+ {addable.length === 0 ? (
+ <div className="tp-tsmenu-empty">没有可添加的瓦片集</div>
+ ) : (
+ addable.map((a) => (
+ <button key={a.ref} type="button" className="tp-tsmenu-item" onClick={() => addTileset(a.ref)}>
+ {a.name.replace(/\.estileset$/, '')}
+ </button>
+ ))
+ )}
+ </div>
+ )}
+ </div>
</div>
)}
{tool === 'terrain' ? (
diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.css
index 92da44164..34b26df3c 100644
--- a/desktop/src/theme/tilemap.css
+++ b/desktop/src/theme/tilemap.css
@@ -80,25 +80,92 @@
/* Multi-tileset tab bar — switch which of the layer's tilesets the palette paints from. */
.tp-tilesets {
display: flex;
+ align-items: center;
gap: 4px;
padding: 6px 8px;
overflow-x: auto;
background: var(--srf-0, #101216);
border-bottom: 1px solid var(--line, #2a2d33);
}
-.tp-tsbtn {
+/* A tileset tab = a name button + (when the layer has >1 tileset) a remove ×. */
+.tp-tschip {
flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
background: var(--control, #24272d);
border: 1px solid var(--line, #2a2d33);
border-radius: 3px;
+ overflow: hidden;
+}
+.tp-tschip.is-active { border-color: var(--star, #4c8fd6); }
+.tp-tsbtn {
+ background: none;
+ border: none;
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-tsbtn:hover { color: var(--text, #d6d9de); }
+.tp-tschip.is-active .tp-tsbtn { color: var(--text, #d6d9de); }
+.tp-tsx {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ align-self: stretch;
+ background: none;
+ border: none;
+ border-left: 1px solid var(--line, #2a2d33);
+ color: var(--text-faint, #6b717c);
+ cursor: pointer;
+}
+.tp-tsx:hover { color: var(--danger, #e5484d); background: var(--control-hover, #333740); }
+/* Add-tileset opener + dropdown of the project's other .estileset assets. */
+.tp-tsadd-wrap { position: relative; flex: 0 0 auto; }
+.tp-tsadd {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ background: var(--control, #24272d);
+ border: 1px dashed var(--line, #2a2d33);
+ border-radius: 3px;
+ color: var(--text-dim, #9aa0aa);
+ cursor: pointer;
+}
+.tp-tsadd:hover { color: var(--text, #d6d9de); border-color: var(--star, #4c8fd6); }
+.tp-tsmenu {
+ position: absolute;
+ top: calc(100% + 4px);
+ left: 0;
+ z-index: 20;
+ min-width: 140px;
+ max-height: 240px;
+ overflow-y: auto;
+ padding: 4px;
+ background: var(--srf-2, #1b1e23);
+ border: 1px solid var(--line, #2a2d33);
+ border-radius: 4px;
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
+}
+.tp-tsmenu-item {
+ display: block;
+ width: 100%;
+ text-align: left;
+ background: none;
+ border: none;
+ border-radius: 3px;
+ color: var(--text-dim, #9aa0aa);
+ padding: 5px 8px;
+ cursor: pointer;
+ font: inherit;
+ white-space: nowrap;
+}
+.tp-tsmenu-item:hover { background: var(--control-hover, #333740); color: var(--text, #d6d9de); }
+.tp-tsmenu-empty { color: var(--text-faint, #6b717c); padding: 6px 8px; font-size: 11px; }
.tp-warn { color: var(--text-faint, #6b717c); padding: 12px; font-size: 11px; }
.tp-cell {
diff --git a/desktop/src/tilemap/createTilemap.ts b/desktop/src/tilemap/createTilemap.ts
index 79c301b4c..622d1c6f6 100644
--- a/desktop/src/tilemap/createTilemap.ts
+++ b/desktop/src/tilemap/createTilemap.ts
@@ -42,10 +42,12 @@ export async function createTilemapFromTileset(tilesetPath: string): Promise<voi
// collidableTileIds into the model: three snapshots that went stale the moment
// the tileset changed.
SceneCommands.setField(sourceId, 'TilemapLayer', 'cellSize', 'vec2', [asset.tileWidth, asset.tileHeight]);
- // The .estileset link. Not a C++ field — carried losslessly in the model like
- // the chunks blob, and preloaded via the component's discoverAssets.
- SceneCommands.setField(sourceId, 'TilemapLayer', 'tilesetAsset', 'string', tilesetRef);
SceneCommands.endGesture();
+ // The .estileset link. Not a C++ field — carried losslessly in the model like the
+ // chunks blob. setLayerTilesets also pushes it to the runtime plugin live (the
+ // reconciler can't project an out-of-band field), so the fresh layer resolves its
+ // render table and is paintable immediately, without a reload.
+ SceneCommands.setLayerTilesets(sourceId, [tilesetRef]);
useSelection.getState().select(sourceId);
useTilemapPaint.getState().setTileset(tilesetPath);
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index fbf2f8456..ccf493bd4 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -345,6 +345,7 @@ export {
shutdownTilemapAPI,
TilemapPlugin,
tilemapPlugin,
+ TilemapLiveSync,
parseTmjJson,
parseTmjWithExternals,
loadTiledMap,
@@ -408,6 +409,7 @@ export {
type TilesetTileTerrain,
type TerrainIndex,
type TerrainIndices,
+ type ApplyTilesetRefs,
} from './tilemap';
// =============================================================================
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index e6add6a2b..721094c6d 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
export { Tilemap, TilemapLayer, type TilemapData, type TilemapLayerData } from './components';
export { TilemapAPI, Tilemaps, initTilemapAPI, shutdownTilemapAPI } from './tilemapAPI';
+export { TilemapLiveSync, type ApplyTilesetRefs } from './tilemapLiveSync';
export { TilemapPlugin, tilemapPlugin } from './tilemapPlugin';
export {
parseTmjJson, parseTmjWithExternals, loadTiledMap, loadTiledCollisionObjects,
diff --git a/sdk/src/tilemap/tilemapLiveSync.ts b/sdk/src/tilemap/tilemapLiveSync.ts
new file mode 100644
index 000000000..d49e6f194
--- /dev/null
+++ b/sdk/src/tilemap/tilemapLiveSync.ts
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tilemapLiveSync.ts
+ * @brief Editor→runtime live channel for a TilemapLayer's `.estileset` ref list.
+ *
+ * `tilesetAssets` is out-of-band — NOT a C++ ABI field — so the editor's reconciler
+ * drops it when it projects a component change to the World, and the scene codec's
+ * `importData` (which owns `tilesetRefs_`) only runs on a FULL scene load. That
+ * leaves no path for "the editor added a tileset to this layer" to reach the running
+ * tilemap plugin, so the sync would keep rendering from the stale ref list.
+ *
+ * This singleton is that path: the active {@link TilemapPlugin} binds its ref-apply
+ * in `build()` (and clears it in `cleanup()`); the editor pushes a ref-list change
+ * through {@link TilemapLiveSync.setLayerTilesets}, the plugin updates `tilesetRefs_`
+ * and clears `liveResolved_`, and the next sync re-resolves the multi-slot render
+ * table + animations + collision LIVE. It is the exact analog of
+ * `TilemapAPI.importChunks` for painted tiles — an out-of-band field pushed straight
+ * to the runtime, bypassing the reconciler. Unbound (no runtime) = a no-op.
+ */
+
+/** Apply a layer's `.estileset` refs to the running plugin (empty = clear). */
+export type ApplyTilesetRefs = (entity: number, refs: readonly string[]) => void;
+
+let apply: ApplyTilesetRefs | null = null;
+
+export const TilemapLiveSync = {
+ /** The active TilemapPlugin registers its ref-apply (build) / clears it (cleanup). */
+ _bind(fn: ApplyTilesetRefs | null): void {
+ apply = fn;
+ },
+ /** Push a layer's `.estileset` refs to the runtime so the next sync re-resolves. */
+ setLayerTilesets(entity: number, refs: readonly string[]): void {
+ apply?.(entity, refs);
+ },
+};
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 9cd6d678c..63a6563a2 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -6,6 +6,7 @@ import { Transform, TilemapLayer, Sprite, Canvas, RuntimeOnly, type TilemapLayer
import { Schedule } from '../system';
import type { SystemDef } from '../system';
import { initTilemapAPI, shutdownTilemapAPI, TilemapAPI } from './tilemapAPI';
+import { TilemapLiveSync } from './tilemapLiveSync';
import { Tilemap } from './components';
import { registerSceneComponentCodec } from '../scene';
import { getTilemapSource, getResolvedTileset } from './tilesetCache';
@@ -64,6 +65,19 @@ export class TilemapPlugin implements Plugin {
const tilesetRefs = this.tilesetRefs_;
const liveResolved = this.liveResolved_;
const requestedTilesetLoads = this.requestedTilesetLoads_;
+
+ // The single writer of a layer's `.estileset` ref list: point the render table
+ // at `refs` and mark it for re-resolve next sync. Shared by the scene codec
+ // (full load) AND the editor's live push (TilemapLiveSync) so both routes carry
+ // the SAME meaning — no second source of truth for what tilesets a layer uses.
+ const applyTilesetRefs = (entity: number, refs: readonly string[]): void => {
+ const clean = refs.filter((r): r is string => typeof r === 'string' && r !== '');
+ if (clean.length > 0) tilesetRefs.set(entity, clean.slice());
+ else tilesetRefs.delete(entity);
+ liveResolved.delete(entity);
+ };
+ TilemapLiveSync._bind(applyTilesetRefs);
+
registerSceneComponentCodec('TilemapLayer', {
exportData: (entity, data) => {
const blob = TilemapAPI.exportChunks(entity);
@@ -97,18 +111,10 @@ export class TilemapPlugin implements Plugin {
// 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);
- }
- liveResolved.delete(entity);
+ const refs = Array.isArray(list)
+ ? list.filter((r): r is string => typeof r === 'string' && r !== '')
+ : (typeof single === 'string' && single !== '' ? [single] : []);
+ applyTilesetRefs(entity, refs);
},
});
@@ -494,6 +500,7 @@ export class TilemapPlugin implements Plugin {
cleanup(): void {
this.resetLayers();
+ TilemapLiveSync._bind(null);
shutdownTilemapAPI();
}
}
diff --git a/sdk/tests/tilemap-live-sync.test.ts b/sdk/tests/tilemap-live-sync.test.ts
new file mode 100644
index 000000000..de1ad1a35
--- /dev/null
+++ b/sdk/tests/tilemap-live-sync.test.ts
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file TilemapLiveSync forwarding contract — the editor→runtime channel for a
+ * layer's `.estileset` ref list. The plugin binds its ref-apply in build()
+ * and clears it in cleanup(); the editor pushes ref-list changes through
+ * setLayerTilesets. Guards that pushes reach the bound plugin, that an
+ * unbound channel is inert (no runtime), and that cleanup stops delivery.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { TilemapLiveSync } from '../src/tilemap/tilemapLiveSync';
+
+describe('TilemapLiveSync', () => {
+ beforeEach(() => TilemapLiveSync._bind(null));
+ afterEach(() => TilemapLiveSync._bind(null));
+
+ it('forwards setLayerTilesets to the bound apply fn', () => {
+ const calls: Array<{ entity: number; refs: string[] }> = [];
+ TilemapLiveSync._bind((entity, refs) => calls.push({ entity, refs: [...refs] }));
+ TilemapLiveSync.setLayerTilesets(7, ['@uuid:a', '@uuid:b']);
+ expect(calls).toEqual([{ entity: 7, refs: ['@uuid:a', '@uuid:b'] }]);
+ });
+
+ it('is a no-op when unbound (no runtime plugin has built)', () => {
+ expect(() => TilemapLiveSync.setLayerTilesets(1, ['@uuid:x'])).not.toThrow();
+ });
+
+ it('an empty list still forwards (clears a layer to zero tilesets)', () => {
+ let seen: readonly string[] | null = null;
+ TilemapLiveSync._bind((_e, refs) => { seen = refs; });
+ TilemapLiveSync.setLayerTilesets(3, []);
+ expect(seen).toEqual([]);
+ });
+
+ it('cleanup (unbind) stops delivery — a later push is inert', () => {
+ let count = 0;
+ TilemapLiveSync._bind(() => { count++; });
+ TilemapLiveSync.setLayerTilesets(1, ['@uuid:a']);
+ TilemapLiveSync._bind(null); // plugin.cleanup()
+ TilemapLiveSync.setLayerTilesets(1, ['@uuid:a']);
+ expect(count).toBe(1);
+ });
+
+ it('rebinding points delivery at the newest plugin (world rebuild)', () => {
+ const a: number[] = [];
+ const b: number[] = [];
+ TilemapLiveSync._bind((e) => a.push(e));
+ TilemapLiveSync._bind((e) => b.push(e)); // a second build() replaces the binding
+ TilemapLiveSync.setLayerTilesets(5, ['@uuid:a']);
+ expect(a).toEqual([]);
+ expect(b).toEqual([5]);
+ });
+});