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): Tileset editor + .estileset authoring (REARCH_TILEMAP T2b)

esenginee302d7e2c0b6
diff --git a/desktop/src/components/icons.tsx b/desktop/src/components/icons.tsx
index 599520856..c25252b08 100644
--- a/desktop/src/components/icons.tsx
+++ b/desktop/src/components/icons.tsx
@@ -60,6 +60,8 @@ const ASSET_ICON: Record<AssetType, { icon: LucideIcon; tint: string }> = {
material: { icon: Blend, tint: '#c0917a' },
script: { icon: FileCode2, tint: '#93a3bf' },
animation: { icon: Clapperboard, tint: '#9bb39a' },
+ tileset: { icon: Grid3x3, tint: '#9b8fc0' },
+ tilemap: { icon: Grid3x3, tint: '#7fa6c4' },
file: { icon: File, tint: 'var(--text-dim)' },
};
diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsx
index f6b9d8740..c3e4e453e 100644
--- a/desktop/src/layout/DockLayout.tsx
+++ b/desktop/src/layout/DockLayout.tsx
@@ -15,6 +15,7 @@ import { ContentBrowser } from '@/panels/ContentBrowser';
import { OutputLog } from '@/panels/OutputLog';
import { GamePanel } from '@/panels/GamePanel';
import { Sequencer } from '@/panels/Sequencer';
+import { TilesetEditor } from '@/panels/TilesetEditor';
import { dockApi } from '@/layout/dockApi';
// Each dock panel is a thin wrapper so dockview owns mount/unmount.
@@ -25,6 +26,7 @@ const components: Record<string, FC<IDockviewPanelProps>> = {
content: () => <ContentBrowser />,
log: () => <OutputLog />,
sequencer: () => <Sequencer />,
+ tileset: () => <TilesetEditor />,
// The "Game" view (isolated play realm) — added on Play, removed on Stop.
game: () => <GamePanel />,
};
@@ -33,7 +35,7 @@ const components: Record<string, FC<IDockviewPanelProps>> = {
// Details, and Content Browser + Output Log as sibling tabs along the bottom
// (resize/close via dockview). The Content Drawer (Ctrl+Space) is a separate
// quick-access overlay on top.
-const LAYOUT_KEY = 'estella.editor.layout.v5';
+const LAYOUT_KEY = 'estella.editor.layout.v6';
function buildDefaultLayout(api: DockviewReadyEvent['api']) {
// Viewport is the anchor; the right column stacks Outliner over Details.
@@ -85,6 +87,18 @@ function ensureSequencer(api: DockviewReadyEvent['api']) {
});
}
+// Same idea for the Tileset editor — a bottom-dock tab added to fresh + restored layouts.
+function ensureTileset(api: DockviewReadyEvent['api']) {
+ if (api.getPanel('tileset')) return;
+ const ref = api.getPanel('content') ? 'content' : api.getPanel('sequencer') ? 'sequencer' : undefined;
+ api.addPanel({
+ id: 'tileset',
+ component: 'tileset',
+ title: 'Tileset',
+ position: ref ? { referencePanel: ref, direction: 'within' } : undefined,
+ });
+}
+
// A collapse/expand chevron in every dock group's header (the design's `.pcol`).
// Collapses the group to its tab bar by height; hidden on the Viewport/Game group
// (the center stage isn't an accordion). State follows the live group height, so
@@ -131,6 +145,7 @@ export function DockLayout() {
// Ensure the Sequencer tab exists, then keep the Content Browser fronted so
// adding it doesn't steal the bottom dock's active tab on load.
ensureSequencer(api);
+ ensureTileset(api);
api.getPanel('content')?.api.setActive();
// Persist the dock arrangement so it survives reloads — a real editor habit.
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index e6be7fbce..c6456c3c2 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -22,6 +22,7 @@ import './theme/log.css';
import './theme/viewport.css';
import './theme/content.css';
import './theme/sequencer.css';
+import './theme/tileset.css';
import './theme/chrome.css';
import './theme/menus.css';
import './theme/settings.css';
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index 17b770717..87cf83b44 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -11,6 +11,7 @@ import { Toasts } from '@/store/Toasts';
import { useSelection } from '@/store/selectionStore';
import { IMAGE_RE, assetTypeOf as assetType, TYPE_CODE } from '@/project/assetMeta';
import { openAnimationClip } from '@/timeline/openClip';
+import { openTileset, createTilesetFromTexture } from '@/tileset/openTileset';
import { fsRefresh } from '@/project/fsWatch';
import type { DirEntry } from '@/project/format';
import type { AssetType } from '@/types';
@@ -304,6 +305,8 @@ export function ContentBrowser() {
void ProjectStore.openScene(path);
} else if (assetType(name) === 'animation') {
void openAnimationClip(path);
+ } else if (assetType(name) === 'tileset') {
+ void openTileset(path);
}
};
@@ -451,11 +454,15 @@ export function ContentBrowser() {
}
const { path, entry } = ctx.target;
const isScene = !entry.isDir && assetType(entry.name) === 'scene';
+ const isTexture = !entry.isDir && (assetType(entry.name) === 'texture' || assetType(entry.name) === 'sprite');
const ref = entry.isDir ? null : ProjectStore.assetRef(path);
return [
...(entry.isDir || isScene
? [{ label: 'Open', onClick: () => onOpen(path, entry.isDir, entry.name) }]
: []),
+ ...(isTexture
+ ? [{ label: 'Create Tileset', onClick: () => void createTilesetFromTexture(path) }]
+ : []),
{ label: 'Rename', onClick: () => setRenaming(path) },
{ label: 'Duplicate', onClick: () => void duplicate(path) },
{ sep: true },
diff --git a/desktop/src/panels/TilesetEditor.tsx b/desktop/src/panels/TilesetEditor.tsx
new file mode 100644
index 000000000..b37aec2ea
--- /dev/null
+++ b/desktop/src/panels/TilesetEditor.tsx
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file TilesetEditor.tsx
+ * @brief The .estileset editor panel (docs/REARCH_TILEMAP.md T2) — the tileset's
+ * atlas with a grid overlay; click/drag tiles to toggle box collision (the
+ * collision authority every tilemap derives from). Subscribes to the reactive
+ * TilesetDocument; mutations go through TilesetCommands (one undo step each).
+ *
+ * Scope: grid geometry + per-tile box collision. Per-tile polygon shapes, animation and
+ * terrain rules slot onto the same asset later (the schema already carries them).
+ */
+
+import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { Save } from 'lucide-react';
+import type { TilesetAsset } from 'esengine';
+import { TilesetDocument } from '@/tileset/TilesetDocument';
+import { TilesetCommands } from '@/tileset/TilesetCommands';
+import { ProjectStore } from '@/project/ProjectStore';
+
+function colsFor(width: number, tileW: number, margin: number, spacing: number): number {
+ const stride = tileW + spacing;
+ return stride > 0 ? Math.max(1, Math.floor((width - margin + spacing) / stride)) : 1;
+}
+function rowsFor(height: number, tileH: number, margin: number, spacing: number): number {
+ const stride = tileH + spacing;
+ return stride > 0 ? Math.max(0, Math.floor((height - margin + spacing) / stride)) : 0;
+}
+
+/** A grid-geometry number field that commits on blur/Enter (one undo step per edit). */
+function GridField(props: { label: string; value: number; min?: number; onCommit: (n: number) => void }) {
+ const [text, setText] = useState(String(props.value));
+ useEffect(() => setText(String(props.value)), [props.value]);
+ const commit = () => {
+ const n = Number(text);
+ if (Number.isFinite(n) && n !== props.value) props.onCommit(Math.max(props.min ?? 0, Math.floor(n)));
+ else setText(String(props.value));
+ };
+ return (
+ <label className="ts-field">
+ <span>{props.label}</span>
+ <input
+ type="number" value={text} min={props.min ?? 0}
+ onChange={(e) => setText(e.target.value)}
+ onBlur={commit}
+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
+ />
+ </label>
+ );
+}
+
+export function TilesetEditor() {
+ useSyncExternalStore(TilesetDocument.subscribe, TilesetDocument.getRevision);
+ const asset = TilesetDocument.asset;
+ const meta = TilesetDocument.meta;
+
+ const info = asset ? ProjectStore.assetInfo(asset.texture) : null;
+ const texUrl = info ? `estella://project/${info.path}` : null;
+
+ const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);
+ const [zoom, setZoom] = useState(2);
+ // Live paint stroke: which tiles + the target on/off state, committed as one undo step.
+ const [drag, setDrag] = useState<{ ids: Set<number>; on: boolean } | null>(null);
+ const dragRef = useRef(drag);
+ dragRef.current = drag;
+
+ useEffect(() => setNatural(null), [texUrl]);
+
+ if (!asset) {
+ return (
+ <div className="ts-empty">
+ <p>没有打开的瓦片集</p>
+ <p className="ts-hint">在内容浏览器里双击 .estileset,或右键纹理 → 新建瓦片集</p>
+ </div>
+ );
+ }
+
+ const { tileWidth: tw, tileHeight: th, margin: mg, spacing: sp } = asset;
+ const cols = natural ? colsFor(natural.w, tw, mg, sp) : asset.columns;
+ const rows = natural ? rowsFor(natural.h, th, mg, sp) : 0;
+
+ const isSolid = (id: number): boolean =>
+ drag?.ids.has(id) ? drag.on : asset.tiles[id]?.collision !== undefined;
+
+ const commitDrag = () => {
+ const d = dragRef.current;
+ if (d) TilesetCommands.paintCollision([...d.ids], d.on);
+ setDrag(null);
+ };
+
+ // Grid edits recompute columns from the atlas so the asset stays consistent.
+ const editGrid = (patch: Partial<Pick<TilesetAsset, 'tileWidth' | 'tileHeight' | 'margin' | 'spacing'>>) => {
+ const next = { tileWidth: tw, tileHeight: th, margin: mg, spacing: sp, ...patch };
+ const columns = natural ? colsFor(natural.w, next.tileWidth, next.margin, next.spacing) : asset.columns;
+ TilesetCommands.setGrid({ ...patch, columns });
+ };
+
+ const cells = [];
+ if (texUrl && natural) {
+ for (let row = 0; row < rows; row++) {
+ for (let col = 0; col < cols; col++) {
+ const id = row * cols + col + 1;
+ const left = (mg + col * (tw + sp)) * zoom;
+ const top = (mg + row * (th + sp)) * zoom;
+ cells.push(
+ <div
+ key={id}
+ className={'ts-cell' + (isSolid(id) ? ' is-solid' : '')}
+ style={{ left, top, width: tw * zoom, height: th * zoom }}
+ title={`#${id}`}
+ onPointerDown={(e) => {
+ e.preventDefault();
+ setDrag({ ids: new Set([id]), on: !isSolid(id) });
+ }}
+ onPointerEnter={() => {
+ if (dragRef.current) {
+ const ids = new Set(dragRef.current.ids);
+ ids.add(id);
+ setDrag({ ids, on: dragRef.current.on });
+ }
+ }}
+ />,
+ );
+ }
+ }
+ }
+
+ const solidCount = Object.values(asset.tiles).filter((t) => t.collision).length;
+
+ return (
+ <div className="ts-editor">
+ <div className="ts-toolbar">
+ <GridField label="Tile W" value={tw} min={1} onCommit={(n) => editGrid({ tileWidth: n })} />
+ <GridField label="Tile H" value={th} min={1} onCommit={(n) => editGrid({ tileHeight: n })} />
+ <GridField label="Margin" value={mg} onCommit={(n) => editGrid({ margin: n })} />
+ <GridField label="Spacing" value={sp} onCommit={(n) => editGrid({ spacing: n })} />
+ <span className="ts-sep" />
+ <label className="ts-field">
+ <span>Zoom</span>
+ <input type="range" min={1} max={8} step={1} value={zoom}
+ onChange={(e) => setZoom(Number(e.target.value))} />
+ </label>
+ <span className="ts-grow" />
+ <span className="ts-stat">{cols}×{rows} · {solidCount} solid</span>
+ <button type="button" className="ts-save" onClick={() => void TilesetCommands.save()} disabled={!meta.dirty}>
+ <Save size={13} /> 保存{meta.dirty ? ' •' : ''}
+ </button>
+ </div>
+
+ <div className="ts-canvas" onPointerUp={commitDrag} onPointerLeave={commitDrag}>
+ {!texUrl ? (
+ <div className="ts-warn">纹理未找到(引用 {String(asset.texture) || '空'})</div>
+ ) : (
+ <div className="ts-stage" style={{ width: (natural?.w ?? 0) * zoom, height: (natural?.h ?? 0) * zoom }}>
+ <img
+ className="ts-img" src={texUrl} alt="" draggable={false}
+ onLoad={(e) => setNatural({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })}
+ />
+ {cells}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/desktop/src/project/assetMeta.ts b/desktop/src/project/assetMeta.ts
index c72dbd6a1..9a458bc8b 100644
--- a/desktop/src/project/assetMeta.ts
+++ b/desktop/src/project/assetMeta.ts
@@ -22,6 +22,8 @@ export function assetTypeOf(name: string): AssetType {
if (ext === 'esmat') return 'material';
// Unified animation clip (.esanim) + legacy multi-track timeline (.estimeline).
if (ext === 'esanim' || ext === 'estimeline') return 'animation';
+ if (ext === 'estileset') return 'tileset';
+ if (ext === 'estilemap') return 'tilemap';
return 'file';
}
@@ -38,6 +40,8 @@ export const TYPE_CODE: Record<AssetType, string> = {
audio: 'AUD',
script: 'TS',
animation: 'ANM',
+ tileset: 'TST',
+ tilemap: 'TMP',
};
export const baseName = (p: string) => (p.includes('/') ? p.slice(p.lastIndexOf('/') + 1) : p);
diff --git a/desktop/src/theme/tileset.css b/desktop/src/theme/tileset.css
new file mode 100644
index 000000000..830623889
--- /dev/null
+++ b/desktop/src/theme/tileset.css
@@ -0,0 +1,105 @@
+/* SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0 */
+/* SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team */
+/* The .estileset editor panel (docs/REARCH_TILEMAP.md T2). */
+
+.ts-editor {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ background: var(--srf-1, #16181c);
+ color: var(--text, #d6d9de);
+ font-size: 12px;
+}
+
+.ts-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 10px;
+ border-bottom: 1px solid var(--line, #2a2d33);
+ background: var(--srf-2, #1b1e23);
+ flex: 0 0 auto;
+}
+
+.ts-field {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ color: var(--text-dim, #9aa0aa);
+}
+.ts-field span { user-select: none; }
+.ts-field input[type='number'] {
+ width: 46px;
+ background: var(--inset, #0f1115);
+ border: 1px solid var(--line, #2a2d33);
+ border-radius: 3px;
+ color: var(--text, #d6d9de);
+ padding: 2px 4px;
+ font: inherit;
+}
+.ts-field input[type='range'] { width: 90px; }
+
+.ts-sep { width: 1px; align-self: stretch; background: var(--line, #2a2d33); margin: 0 2px; }
+.ts-grow { flex: 1 1 auto; }
+.ts-stat { color: var(--text-faint, #6b717c); font-variant-numeric: tabular-nums; }
+
+.ts-save {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ background: var(--star, #4c8fd6);
+ color: var(--on-accent, #fff);
+ border: none;
+ border-radius: 3px;
+ padding: 4px 9px;
+ cursor: pointer;
+ font: inherit;
+}
+.ts-save:disabled { background: var(--control, #2a2d33); color: var(--text-faint, #6b717c); cursor: default; }
+
+.ts-canvas {
+ flex: 1 1 auto;
+ overflow: auto;
+ padding: 16px;
+ /* A checkerboard so transparent atlas regions read clearly. */
+ background:
+ linear-gradient(45deg, var(--srf-0, #101216) 25%, transparent 25%) 0 0 / 16px 16px,
+ linear-gradient(-45deg, var(--srf-0, #101216) 25%, transparent 25%) 0 8px / 16px 16px,
+ linear-gradient(45deg, transparent 75%, var(--srf-0, #101216) 75%) 8px -8px / 16px 16px,
+ linear-gradient(-45deg, transparent 75%, var(--srf-0, #101216) 75%) -8px 0 / 16px 16px,
+ var(--srf-1, #16181c);
+}
+
+.ts-stage { position: relative; }
+.ts-img {
+ display: block;
+ width: 100%;
+ height: 100%;
+ image-rendering: pixelated;
+ user-select: none;
+}
+
+.ts-cell {
+ position: absolute;
+ box-sizing: border-box;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ cursor: pointer;
+}
+.ts-cell:hover { border-color: var(--star, #4c8fd6); background: rgba(76, 143, 214, 0.12); }
+.ts-cell.is-solid {
+ background: rgba(240, 100, 90, 0.34);
+ border-color: rgba(240, 100, 90, 0.85);
+}
+.ts-cell.is-solid:hover { background: rgba(240, 100, 90, 0.5); }
+
+.ts-empty,
+.ts-warn {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ gap: 6px;
+ color: var(--text-faint, #6b717c);
+}
+.ts-hint { font-size: 11px; }
diff --git a/desktop/src/tileset/TilesetCommands.ts b/desktop/src/tileset/TilesetCommands.ts
new file mode 100644
index 000000000..7f113b1cb
--- /dev/null
+++ b/desktop/src/tileset/TilesetCommands.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file TilesetCommands.ts
+ * @brief Undoable mutations on the open .estileset (docs/REARCH_TILEMAP.md T2).
+ * Each routes through TilesetDocument.edit → one EditorHistory snapshot step;
+ * the panel never mutates the asset directly.
+ */
+
+import { serializeTileset } from 'esengine';
+import type { TilesetAsset } from 'esengine';
+import { TilesetDocument } from './TilesetDocument';
+import { Toasts } from '@/store/Toasts';
+
+type GridPatch = Partial<Pick<TilesetAsset, 'tileWidth' | 'tileHeight' | 'margin' | 'spacing' | 'columns'>>;
+
+/** Drop a tile entry that no longer carries any metadata, keeping the map sparse. */
+function pruneEmpty(asset: TilesetAsset, id: number): void {
+ const t = asset.tiles[id];
+ if (t && !t.collision && !t.properties && !t.animation) delete asset.tiles[id];
+}
+
+export const TilesetCommands = {
+ /** Edit the atlas grid geometry (tile size / margin / spacing / columns). */
+ setGrid(patch: GridPatch): void {
+ TilesetDocument.edit('Edit Tile Grid', (a) => {
+ for (const k of Object.keys(patch) as (keyof GridPatch)[]) {
+ const v = patch[k];
+ if (typeof v === 'number' && Number.isFinite(v) && v >= 0) a[k] = Math.floor(v);
+ }
+ // tile size / columns must stay positive.
+ if (a.tileWidth < 1) a.tileWidth = 1;
+ if (a.tileHeight < 1) a.tileHeight = 1;
+ if (a.columns < 1) a.columns = 1;
+ });
+ },
+
+ /** Set box collision on/off for a set of tiles as ONE undo step (a paint stroke). */
+ paintCollision(tileIds: number[], on: boolean): void {
+ if (tileIds.length === 0) return;
+ TilesetDocument.edit(on ? 'Add Tile Collision' : 'Remove Tile Collision', (a) => {
+ for (const id of tileIds) {
+ if (id <= 0) continue;
+ if (on) a.tiles[id] = { ...(a.tiles[id] ?? {}), collision: { type: 'box' } };
+ else if (a.tiles[id]?.collision) {
+ delete a.tiles[id].collision;
+ pruneEmpty(a, id);
+ }
+ }
+ });
+ },
+
+ /** Persist the open tileset to its file. */
+ async save(): Promise<void> {
+ const asset = TilesetDocument.asset;
+ const path = TilesetDocument.filePath;
+ if (!asset || !path) return;
+ try {
+ await window.estella.fs.write(path, JSON.stringify(serializeTileset(asset), null, 2) + '\n');
+ TilesetDocument.markSaved();
+ Toasts.push('已保存瓦片集', 'info');
+ } catch (e) {
+ Toasts.push(`保存瓦片集失败:${String(e)}`, 'error');
+ }
+ },
+};
diff --git a/desktop/src/tileset/TilesetDocument.ts b/desktop/src/tileset/TilesetDocument.ts
new file mode 100644
index 000000000..0a8e8d0ba
--- /dev/null
+++ b/desktop/src/tileset/TilesetDocument.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file TilesetDocument.ts
+ * @brief The open .estileset as a reactive editor document — the second
+ * {@link AssetDocument} (after the Sequencer's TimelineDocument), and the
+ * rule-of-three that confirmed the base is generic (docs/REARCH_TILEMAP.md T2).
+ *
+ * A tileset is a pure asset (unlike a timeline it binds to no scene entity), so this
+ * subclass adds almost nothing over the generic reactive + snapshot-undo core — just
+ * typed open/close + a `meta` getter for the panel chrome.
+ */
+
+import { parseTileset, type TilesetAsset } from 'esengine';
+import { AssetDocument } from '@/document/AssetDocument';
+
+export interface TilesetDocMeta {
+ filePath: string | null;
+ dirty: boolean;
+}
+
+export class TilesetDocumentImpl extends AssetDocument<TilesetAsset> {
+ get meta(): TilesetDocMeta {
+ return { filePath: this.filePath, dirty: this.dirty };
+ }
+
+ /** Open an already-parsed tileset asset. */
+ open(asset: TilesetAsset, filePath: string | null): void {
+ this.openAsset(asset, filePath);
+ }
+
+ /** Open from raw .estileset JSON (normalized by the SDK parser). */
+ openJson(raw: unknown, filePath: string | null): void {
+ this.open(parseTileset(raw), filePath);
+ }
+
+ close(): void {
+ this.closeAsset();
+ }
+}
+
+/** The app's default tileset document (the one the Tileset editor panel drives). */
+export const TilesetDocument = new TilesetDocumentImpl();
diff --git a/desktop/src/tileset/openTileset.ts b/desktop/src/tileset/openTileset.ts
new file mode 100644
index 000000000..fceb4e734
--- /dev/null
+++ b/desktop/src/tileset/openTileset.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file openTileset.ts
+ * @brief Open / create a .estileset from the Content Browser (docs/REARCH_TILEMAP.md T2).
+ * Mirrors openClip.ts (open) and ProjectStore.createPrefabFromEntity (create + .meta
+ * + registry re-scan).
+ */
+
+import { createTileset as createTilesetAsset, serializeTileset } from 'esengine';
+import { TilesetDocument } from './TilesetDocument';
+import { ProjectStore } from '@/project/ProjectStore';
+import { dockApi } from '@/layout/dockApi';
+import { baseName } from '@/project/assetMeta';
+import { Toasts } from '@/store/Toasts';
+
+/** Open an existing .estileset into the Tileset editor and reveal the panel. */
+export async function openTileset(path: string): Promise<void> {
+ try {
+ const text = await window.estella.fs.read(path);
+ TilesetDocument.openJson(JSON.parse(text), path);
+ dockApi.revealAndExpand('tileset');
+ } catch (e) {
+ Toasts.push(`无法打开瓦片集:${String(e)}`, 'error');
+ }
+}
+
+/** Create a .estileset next to a texture (referencing it), then open it. */
+export async function createTilesetFromTexture(texturePath: string): Promise<void> {
+ const ref = ProjectStore.assetRef(texturePath);
+ if (!ref) {
+ Toasts.push('该纹理未被项目追踪,无法创建瓦片集', 'error');
+ return;
+ }
+ const dir = texturePath.includes('/') ? texturePath.slice(0, texturePath.lastIndexOf('/') + 1) : '';
+ const base = baseName(texturePath).replace(/\.[^.]+$/, '') || 'Tileset';
+ let rel = `${dir}${base}.estileset`;
+ for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${dir}${base}-${n}.estileset`;
+
+ const asset = createTilesetAsset(ref, 16, 16, 1);
+ const uuid = crypto.randomUUID();
+ try {
+ await window.estella.fs.write(rel, JSON.stringify(serializeTileset(asset), null, 2) + '\n');
+ await window.estella.fs.write(
+ rel + '.meta',
+ JSON.stringify({ uuid, version: '1.0', type: 'tileset', importer: { autoMigrate: true } }, null, 2) + '\n',
+ );
+ } catch (e) {
+ Toasts.push(`创建瓦片集失败:${String(e)}`, 'error');
+ return;
+ }
+ await ProjectStore.refreshAssets(); // re-scan so the new tileset is tracked
+ Toasts.push(`已创建瓦片集:${rel.split('/').pop()}`, 'info');
+ await openTileset(rel);
+}
diff --git a/desktop/src/types.ts b/desktop/src/types.ts
index b32bd47ee..3bb92ca3b 100644
--- a/desktop/src/types.ts
+++ b/desktop/src/types.ts
@@ -72,6 +72,8 @@ export type AssetType =
| 'material'
| 'script'
| 'animation'
+ | 'tileset'
+ | 'tilemap'
| 'file';
export interface AssetItem {
diff --git a/desktop/tests/tileset-commands.test.ts b/desktop/tests/tileset-commands.test.ts
new file mode 100644
index 000000000..adac0796f
--- /dev/null
+++ b/desktop/tests/tileset-commands.test.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, beforeEach } from 'vitest';
+import type { TilesetAsset } from 'esengine';
+import { TilesetDocument } from '@/tileset/TilesetDocument';
+import { TilesetCommands } from '@/tileset/TilesetCommands';
+import { EditorHistory } from '@/engine/EditorHistory';
+
+function freshTileset(): TilesetAsset {
+ return {
+ version: '1', texture: '@uuid:t', tileWidth: 16, tileHeight: 16,
+ columns: 4, margin: 0, spacing: 0, tiles: {},
+ };
+}
+
+const tiles = () => TilesetDocument.asset!.tiles;
+
+describe('TilesetCommands', () => {
+ beforeEach(() => {
+ EditorHistory.clear();
+ TilesetDocument.open(freshTileset(), 'a.estileset');
+ });
+
+ it('paintCollision adds box collision and is undoable', () => {
+ TilesetCommands.paintCollision([5], true);
+ expect(tiles()[5].collision).toEqual({ type: 'box' });
+ EditorHistory.undo();
+ expect(tiles()[5]).toBeUndefined();
+ });
+
+ it('paints a whole stroke as one undo step', () => {
+ TilesetCommands.paintCollision([5, 6, 7], true);
+ expect(Object.keys(tiles())).toEqual(['5', '6', '7']);
+ EditorHistory.undo();
+ expect(Object.keys(tiles())).toEqual([]); // one step undid all three
+ });
+
+ it('removing collision prunes an otherwise-empty tile but keeps tiles with other metadata', () => {
+ TilesetCommands.paintCollision([5, 6], true);
+ // Give tile 6 a non-collision property so it must survive collision removal.
+ TilesetDocument.replaceAsset({
+ ...TilesetDocument.asset!,
+ tiles: { ...tiles(), 6: { collision: { type: 'box' }, properties: { kind: 'wall' } } },
+ });
+ TilesetCommands.paintCollision([5, 6], false);
+ expect(tiles()[5]).toBeUndefined(); // pruned (no metadata left)
+ expect(tiles()[6]).toEqual({ properties: { kind: 'wall' } }); // kept (still has properties)
+ });
+
+ it('setGrid edits geometry and is undoable', () => {
+ TilesetCommands.setGrid({ tileWidth: 32, columns: 8 });
+ expect(TilesetDocument.asset!.tileWidth).toBe(32);
+ expect(TilesetDocument.asset!.columns).toBe(8);
+ EditorHistory.undo();
+ expect(TilesetDocument.asset!.tileWidth).toBe(16);
+ });
+});