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): unify GUI primitives + tilemap/UI-editing polish

yhh15c5364a3330
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index f5e517733..0fece1eea 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -270,7 +270,11 @@ for (const m of EDITOR_MODES) {
}
modeStore.setMode(m.id);
for (const p of m.panels ?? []) {
- dockApi.openSidePanel(p.id, p.component, p.title, p.side ?? 'left', p.width ?? 300);
+ if (p.tabWith) {
+ dockApi.openTabbedPanel(p.id, p.component, p.title, p.tabWith, p.side ?? 'left', p.width ?? 300);
+ } else {
+ dockApi.openSidePanel(p.id, p.component, p.title, p.side ?? 'left', p.width ?? 300);
+ }
}
// A mode with a design frame (UI) is entered to work against the authored screen;
// the free editor camera never adopts the design aspect, so frame it on entry so
diff --git a/desktop/src/components/NewTilesetDialog.tsx b/desktop/src/components/NewTilesetDialog.tsx
new file mode 100644
index 000000000..0bf78e303
--- /dev/null
+++ b/desktop/src/components/NewTilesetDialog.tsx
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NewTilesetDialog — pick the tile grid (size / margin / spacing) when turning a
+ * texture into a `.estileset`, with a live grid overlay on the image, instead of
+ * the old blind 16×16 default that forced you to notice and hand-fix the grid in
+ * the editor. Seeds a good tile-size guess, warns when the sheet isn't evenly
+ * divided, and reports the resulting column/row/tile count. (Tiled's New-Tileset.)
+ */
+import { useEffect, useRef, useState } from 'react';
+import { Modal } from '@/components/Modal';
+import { Button } from '@/components/Button';
+import { GridField } from '@/components/GridField';
+import { colsFor, rowsFor } from '@/tools/tileMath';
+import { t } from '@/i18n';
+
+export interface TilesetGrid {
+ tileWidth: number;
+ tileHeight: number;
+ margin: number;
+ spacing: number;
+ columns: number;
+}
+
+/** The largest common tile size that divides both image dimensions evenly — the usual
+ * sheet grid. Falls back to 16 when nothing common divides (an odd or trimmed sheet). */
+function guessTileSize(w: number, h: number): number {
+ for (const s of [32, 16, 24, 48, 64, 8]) if (w % s === 0 && h % s === 0) return s;
+ return 16;
+}
+
+const PREVIEW_MAX = 420;
+
+export function NewTilesetDialog({ textureUrl, onCancel, onConfirm }: {
+ textureUrl: string;
+ onCancel: () => void;
+ onConfirm: (grid: TilesetGrid) => void;
+}) {
+ const [nat, setNat] = useState<{ w: number; h: number } | null>(null);
+ const [tw, setTw] = useState(16);
+ const [th, setTh] = useState(16);
+ const [mg, setMg] = useState(0);
+ const [sp, setSp] = useState(0);
+ const imgRef = useRef<HTMLImageElement | null>(null);
+
+ // Seed the tile size from a good guess so the grid usually lands right on open.
+ const adopt = (w: number, h: number) => {
+ setNat({ w, h });
+ const g = guessTileSize(w, h);
+ setTw(g);
+ setTh(g);
+ };
+ useEffect(() => {
+ const img = imgRef.current;
+ if (img && img.complete && img.naturalWidth > 0) adopt(img.naturalWidth, img.naturalHeight);
+ }, [textureUrl]);
+
+ const cols = nat ? colsFor(nat.w, tw, mg, sp) : 0;
+ const rows = nat ? rowsFor(nat.h, th, mg, sp) : 0;
+ const stride = (n: number, tile: number) => (n - mg + sp) % (tile + sp);
+ const uneven = nat != null && cols > 0 && rows > 0 && (stride(nat.w, tw) !== 0 || stride(nat.h, th) !== 0);
+
+ const scale = nat ? Math.min(1, PREVIEW_MAX / nat.w, (PREVIEW_MAX * 0.75) / nat.h) : 1;
+ const cells: { x: number; y: number }[] = [];
+ if (nat && cols > 0 && rows > 0 && cols * rows <= 4096) {
+ for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) cells.push({ x: mg + c * (tw + sp), y: mg + r * (th + sp) });
+ }
+
+ return (
+ <Modal
+ title={t('tile.newTilesetTitle')}
+ onClose={onCancel}
+ width={480}
+ footer={(
+ <>
+ <Button onClick={onCancel}>{t('ui.cancel')}</Button>
+ <Button
+ variant="primary"
+ disabled={!nat}
+ onClick={() => onConfirm({ tileWidth: tw, tileHeight: th, margin: mg, spacing: sp, columns: Math.max(1, cols) })}
+ >
+ {t('tile.newTilesetCreate')}
+ </Button>
+ </>
+ )}
+ >
+ <div className="nts">
+ <div className="nts-preview" style={{ width: (nat?.w ?? 0) * scale, height: (nat?.h ?? 0) * scale }}>
+ <img
+ ref={imgRef}
+ className="nts-img"
+ src={textureUrl}
+ alt=""
+ draggable={false}
+ onLoad={(e) => adopt(e.currentTarget.naturalWidth, e.currentTarget.naturalHeight)}
+ />
+ {nat && cells.length > 0 && (
+ <svg className="nts-grid" width={nat.w * scale} height={nat.h * scale} viewBox={`0 0 ${nat.w} ${nat.h}`} preserveAspectRatio="none">
+ {cells.map((cell, i) => (
+ <rect key={i} x={cell.x} y={cell.y} width={tw} height={th} vectorEffect="non-scaling-stroke" />
+ ))}
+ </svg>
+ )}
+ </div>
+ <div className="nts-fields">
+ <GridField label={t('tile.field.tileW')} value={tw} min={1} onCommit={setTw} />
+ <GridField label={t('tile.field.tileH')} value={th} min={1} onCommit={setTh} />
+ <GridField label={t('tile.field.margin')} value={mg} onCommit={setMg} />
+ <GridField label={t('tile.field.spacing')} value={sp} onCommit={setSp} />
+ </div>
+ <div className="nts-stat">
+ {nat ? t('tile.newTilesetCount', { cols, rows, count: cols * rows }) : t('tile.newTilesetLoading')}
+ {uneven && <span className="nts-warn">{t('tile.newTilesetUneven')}</span>}
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/desktop/src/components/ZoomControl.tsx b/desktop/src/components/ZoomControl.tsx
new file mode 100644
index 000000000..4569e66e8
--- /dev/null
+++ b/desktop/src/components/ZoomControl.tsx
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ZoomControl.tsx
+ * @brief The shared atlas/canvas zoom stepper — − / % / + with an optional fit
+ * button — behind every panel that magnifies a fixed-size surface (the
+ * Tilemap palette, the Tileset editor). One recipe instead of a per-panel
+ * button group vs. range-slider split, so every zoomed view steps, clamps,
+ * and reads out the same way. Buttons reuse {@link IconButton}.
+ */
+import { ZoomIn, ZoomOut, Maximize2 } from 'lucide-react';
+import { IconButton } from './IconButton';
+import { t } from '@/i18n';
+
+const clamp = (n: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, n));
+
+export function ZoomControl({
+ zoom,
+ min = 0.25,
+ max = 8,
+ factor = 1.25,
+ onZoom,
+ onFit,
+ fitTitle,
+ className,
+}: {
+ zoom: number;
+ min?: number;
+ max?: number;
+ /** Multiplicative step per − / + press (default 1.25×). */
+ factor?: number;
+ onZoom: (z: number) => void;
+ /** Fit-to-view handler; omit to hide the fit button. */
+ onFit?: () => void;
+ /** Override the fit button's tooltip (default "Fit to view"). */
+ fitTitle?: string;
+ className?: string;
+}) {
+ return (
+ <span className={`zoomctl${className ? ` ${className}` : ''}`}>
+ <IconButton size="sm" title={t('ui.zoomOut')} disabled={zoom <= min} onClick={() => onZoom(clamp(zoom / factor, min, max))}>
+ <ZoomOut size={13} />
+ </IconButton>
+ <span className="zoomctl-pct">{Math.round(zoom * 100)}%</span>
+ <IconButton size="sm" title={t('ui.zoomIn')} disabled={zoom >= max} onClick={() => onZoom(clamp(zoom * factor, min, max))}>
+ <ZoomIn size={13} />
+ </IconButton>
+ {onFit && (
+ <IconButton size="sm" title={fitTitle ?? t('ui.zoomFit')} onClick={onFit}>
+ <Maximize2 size={13} />
+ </IconButton>
+ )}
+ </span>
+ );
+}
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 6ab944e46..34f4b52eb 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -447,6 +447,46 @@ export class SceneCommandsImpl {
this.setField(sourceId, 'Transform', 'position', 'vec3', [local.x, local.y, pos?.z ?? 0]);
}
+ /**
+ * Centre a freshly-added UINode in its Canvas, out of the flow. A flow (Relative) widget
+ * lands wherever its parent's layout puts it — for a plain Canvas that's the corner, tiny
+ * and easy to miss ("I added a button and nothing happened"). Flipping to Absolute + a
+ * centre anchor drops it in the middle where the user is looking (the Unity/Figma "add UI
+ * at the centre" default), draggable from there. Reuses {@link setUINodeAnchor} (auto
+ * margins centre without needing a resolved layout box, so it's relayout-timing safe).
+ * A no-op for a non-UINode (e.g. adding the Canvas itself).
+ */
+ centerUINodeInCanvas(sourceId: EntityId): void {
+ if (this.modelFieldValue(sourceId, 'UINode', 'position') === undefined) return;
+ this.setUINodeAnchor([sourceId], { h: AnchorAxis.Center, v: AnchorAxis.Center });
+ }
+
+ /**
+ * Drop a freshly-added UINode at a world point (its top-left), out of the flow — the
+ * viewport-drop sibling of {@link centerUINodeInCanvas}, so a dragged widget lands under
+ * the cursor instead of collapsing to the Canvas corner. Only needs the PARENT's resolved
+ * box (available — the Canvas is already laid out), not the new node's, so it's
+ * relayout-timing safe. Falls back to centring when the parent has no live box. One undo
+ * step; a no-op for a non-UINode.
+ */
+ placeUINodeAtWorld(sourceId: EntityId, worldX: number, worldY: number): void {
+ if (this.modelFieldValue(sourceId, 'UINode', 'position') === undefined) return;
+ const parentSrc = this.model.entityBySource(sourceId)?.parent;
+ const parentRt = parentSrc != null ? this.model.runtimeFor(parentSrc) : undefined;
+ const parent = parentRt !== undefined ? ViewportController.uiEntityWorldOBB(parentRt) : null;
+ if (!parent) { this.centerUINodeInCanvas(sourceId); return; }
+ // Layout space is y-down: insetLeft from the parent's left edge, insetTop from its top.
+ const left = Math.round(worldX - (parent.cx - parent.hw));
+ const top = Math.round((parent.cy + parent.hh) - worldY);
+ this.beginGesture('Place Widget');
+ this.setField(sourceId, 'UINode', 'position', 'enum', UIPositionType.Absolute);
+ this.setField(sourceId, 'UINode', 'insetLeft', 'dimension', { value: left, unit: DimensionUnit.Px });
+ this.setField(sourceId, 'UINode', 'insetTop', 'dimension', { value: top, unit: DimensionUnit.Px });
+ this.setField(sourceId, 'UINode', 'insetRight', 'dimension', { value: 0, unit: DimensionUnit.Auto });
+ this.setField(sourceId, 'UINode', 'insetBottom', 'dimension', { value: 0, unit: DimensionUnit.Auto });
+ this.endGesture();
+ }
+
/**
* A UINode's on-screen position is LAYOUT-owned: Yoga writes the resolved
* placement into `Transform.position` on every relayout, so a Transform write
@@ -1386,6 +1426,20 @@ export class SceneCommandsImpl {
this.history.record('Set Tilesets', () => apply(next), () => apply(cur));
}
+ /**
+ * Remove a tileset from a layer, remapping already-painted cells so surviving tiles keep
+ * their identity: `edits` (from {@link planTilesetRemoval}) clear the removed tileset's
+ * cells and shift later tilesets' ids down to the new firstId layout, and `newRefs` drops
+ * the tileset from the list — ALL as one undo step. Without the remap, dropping a non-last
+ * tileset would silently corrupt every later tileset's painted tiles.
+ */
+ removeLayerTileset(sourceId: EntityId, newRefs: string[], edits: TilePaint[]): void {
+ this.history.group('Remove Tileset', () => {
+ if (edits.length > 0) this.paintTiles(sourceId, edits);
+ this.setLayerTilesets(sourceId, newRefs);
+ });
+ }
+
// 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/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
index f070aa7cc..b96015065 100644
--- a/desktop/src/engine/entitySources.ts
+++ b/desktop/src/engine/entitySources.ts
@@ -341,6 +341,14 @@ export async function createFromSource(source: EntitySource, ctx: CreateContext)
position: ctx.position,
linkPrefabRef: source.linkPrefabRef?.(ctx),
});
+ // A UI widget's on-screen spot is layout-owned (a flow node collapses to the Canvas
+ // corner, tiny and easy to miss), so `create`'s Transform.position is a no-op for it.
+ // Lift it out of flow through ONE placement path shared by the palette click and the
+ // viewport drop: dropped at a point → land there; clicked with no point → centre it.
+ if (id != null && source.placement === 'under-canvas') {
+ if (ctx.position) SceneCommands.placeUINodeAtWorld(id, ctx.position.x, ctx.position.y);
+ else SceneCommands.centerUINodeInCanvas(id);
+ }
if (id != null) source.afterCreate?.(ctx, id);
// Built-in widget prefabs bake the default dark palette; re-resolve the fresh
// ThemeStyle tags against the ACTIVE tokens so a themed project's palette drops
diff --git a/desktop/src/i18n/messages/common.ts b/desktop/src/i18n/messages/common.ts
index 4129c6683..f7ae29058 100644
--- a/desktop/src/i18n/messages/common.ts
+++ b/desktop/src/i18n/messages/common.ts
@@ -20,6 +20,9 @@ export const commonMessages = defineMessages({
'ui.download': { en: 'Download', zh: '下载' },
'ui.reloadNow': { en: 'Reload now', zh: '立即重新加载' },
'ui.dismiss': { en: 'Dismiss', zh: '关闭' },
+ 'ui.zoomIn': { en: 'Zoom in', zh: '放大' },
+ 'ui.zoomOut': { en: 'Zoom out', zh: '缩小' },
+ 'ui.zoomFit': { en: 'Fit to view', zh: '适配视图' },
// — Panel crash fallback (components/ErrorBoundary.tsx) —
'ui.crashTitle': { en: '{label} hit an error', zh: '{label} 出错了' },
diff --git a/desktop/src/i18n/messages/flipbook.ts b/desktop/src/i18n/messages/flipbook.ts
index 09226b830..a87460bc1 100644
--- a/desktop/src/i18n/messages/flipbook.ts
+++ b/desktop/src/i18n/messages/flipbook.ts
@@ -23,7 +23,6 @@ export const flipbookMessages = defineMessages({
'fb.field.margin': { en: 'Margin', zh: '边距' },
'fb.field.spacing': { en: 'Spacing', zh: '间距' },
'fb.field.fps': { en: 'FPS', zh: '帧率' },
- 'fb.field.zoom': { en: 'Zoom', zh: '缩放' },
'fb.loop': { en: 'Loop', zh: '循环' },
'fb.fps': { en: 'FPS', zh: '帧率' },
'fb.frameCount': { en: '{count} frames', zh: '{count} 帧' },
diff --git a/desktop/src/i18n/messages/tile.ts b/desktop/src/i18n/messages/tile.ts
index 2c8956410..61c788eff 100644
--- a/desktop/src/i18n/messages/tile.ts
+++ b/desktop/src/i18n/messages/tile.ts
@@ -54,11 +54,14 @@ export const tileMessages = defineMessages({
'tile.tilesetGid': { en: '{path} (gid {gid}+)', zh: '{path}(gid {gid}+)' },
'tile.addTileset': { en: 'Add tileset', zh: '添加瓦片集' },
'tile.removeTileset': { en: 'Remove tileset', zh: '移除瓦片集' },
+ 'tile.removeTilesetTitle': { en: 'Remove tileset?', zh: '移除瓦片集?' },
+ 'tile.removeTilesetBody': {
+ en: '{count} painted tile(s) use "{name}" and will be erased. Tiles from other tilesets are preserved.',
+ zh: '有 {count} 个已绘制的瓦片使用“{name}”,将被清除。其他瓦片集的瓦片会保留。',
+ },
'tile.noTilesetsToAdd': { en: 'No tilesets to add', zh: '没有可添加的瓦片集' },
- // — Painter palette + zoom bar —
- 'tile.zoomIn': { en: 'Zoom in', zh: '放大' },
- 'tile.zoomOut': { en: 'Zoom out', zh: '缩小' },
+ // — Painter palette + zoom bar (− / % / + / fit use the shared ui.zoom* labels) —
'tile.fitWidth': { en: 'Fit width', zh: '适配宽度' },
'tile.paletteAria': { en: 'Tile palette', zh: '瓦片调色板' },
'tile.noPalette': {
@@ -88,7 +91,15 @@ export const tileMessages = defineMessages({
'tile.field.tileH': { en: 'Tile H', zh: '瓦片高' },
'tile.field.margin': { en: 'Margin', zh: '边距' },
'tile.field.spacing': { en: 'Spacing', zh: '间距' },
- 'tile.field.zoom': { en: 'Zoom', zh: '缩放' },
+ // — New-tileset dialog (pick the grid instead of a blind 16×16) —
+ 'tile.newTilesetTitle': { en: 'New tileset — slice the grid', zh: '新建瓦片集 — 切分网格' },
+ 'tile.newTilesetCreate': { en: 'Create tileset', zh: '创建瓦片集' },
+ 'tile.newTilesetLoading': { en: 'Loading image…', zh: '正在加载图片…' },
+ 'tile.newTilesetCount': { en: '{cols} × {rows} · {count} tiles', zh: '{cols} × {rows} · {count} 个瓦片' },
+ 'tile.newTilesetUneven': {
+ en: ' ⚠ the sheet isn’t evenly divided — the last row/column is clipped',
+ zh: ' ⚠ 图集未被整除 — 最后一行/列会被截断',
+ },
'tile.mode.aria': { en: 'Edit mode', zh: '编辑模式' },
'tile.mode.collision': { en: 'Collision', zh: '碰撞' },
'tile.mode.terrain': { en: 'Terrain', zh: '地形' },
diff --git a/desktop/src/layout/dockApi.ts b/desktop/src/layout/dockApi.ts
index 1af8b69c3..636a59ca4 100644
--- a/desktop/src/layout/dockApi.ts
+++ b/desktop/src/layout/dockApi.ts
@@ -135,6 +135,19 @@ export const dockApi = {
}
api.getPanel(id)?.api.setActive();
},
+ /** Open a panel as a TAB within another panel's group (e.g. a mode companion behind the
+ * widget palette), so it doesn't claim its own column. Falls back to a side column when
+ * the reference panel isn't open. Does not steal focus — the reference tab stays active. */
+ openTabbedPanel(id: string, component: string, title: string, referenceId: string, fallbackDir: 'left' | 'right' = 'left', width = 300) {
+ if (!api) return;
+ const ref = api.getPanel(referenceId);
+ if (!ref) { this.openSidePanel(id, component, title, fallbackDir, width); return; }
+ if (!api.getPanel(id)) {
+ api.addPanel({ id, component, title, position: { referencePanel: referenceId, direction: 'within' } });
+ }
+ // Keep the reference tab (the primary companion) foremost so the mode opens showing it.
+ ref.api.setActive();
+ },
/** Open (or reveal) the Game view as a tab beside the Viewport — used on Play. */
openGame() {
if (!api) return;
diff --git a/desktop/src/mode/editorModes.ts b/desktop/src/mode/editorModes.ts
index dda4344f1..5fd069014 100644
--- a/desktop/src/mode/editorModes.ts
+++ b/desktop/src/mode/editorModes.ts
@@ -29,6 +29,10 @@ export interface ModePanel {
title: string;
side?: 'left' | 'right';
width?: number;
+ /** Dock as a TAB in another mode-panel's group (by id) instead of its own column —
+ * keeps a companion (e.g. Controllers) one click away without eating a second column
+ * of viewport width. Falls back to `side` if that panel isn't open. */
+ tabWith?: string;
}
export interface EditorModeDef {
@@ -61,7 +65,10 @@ const uiMode: EditorModeDef = {
toolset: 'transform',
panels: [
{ id: 'ui-widgets', component: 'uiWidgets', title: t('panel.uiWidgets'), side: 'left', width: 240 },
- { id: 'controllers', component: 'controllers', title: t('panel.controllers'), side: 'left', width: 260 },
+ // The Controllers panel is node-scoped and reached occasionally — tab it behind the
+ // widget palette (one left column, two tabs) so entering UI mode doesn't eat a second
+ // column of the viewport you're laying out in.
+ { id: 'controllers', component: 'controllers', title: t('panel.controllers'), tabWith: 'ui-widgets', side: 'left', width: 240 },
],
overlays: { designFrame: true, safeArea: true, letterbox: true },
suggestFor: (s) => s.hasComponent('Canvas') || s.hasComponent('UINode'),
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index ddc08617d..f29ab1c18 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -18,6 +18,7 @@ import { ASSET_OPEN } from '@/project/assetOpen';
import { syncAssetPaths } from '@/project/assetPathSync';
import { findAssetUsages, type AssetUsage } from '@/project/assetUsages';
import { FindUsagesDialog } from '@/components/FindUsagesDialog';
+import { NewTilesetDialog } from '@/components/NewTilesetDialog';
import { parseAssetQuery, filterAndSortAssets, type AssetSort } from '@/project/assetFilter';
import { createTilesetFromTexture } from '@/tileset/openTileset';
import { createFlipbookFromTexture } from '@/flipbook/openFlipbook';
@@ -541,6 +542,7 @@ export function ContentBrowser() {
// unsaved in-memory scene — a ref added since the last save would break too).
const [confirmDel, setConfirmDel] = useState<{ paths: string[]; names: string[]; usages: AssetUsage[] } | null>(null);
const [usagesPath, setUsagesPath] = useState<string | null>(null);
+ const [newTilesetFor, setNewTilesetFor] = useState<string | null>(null);
// Confirm deletion of one OR many assets (multi-select) behind a SINGLE dialog —
// aggregating each one's references so nothing gets deleted out from under a scene.
const remove = async (paths: string[]) => {
@@ -1029,7 +1031,7 @@ export function ContentBrowser() {
...(isTexture
? [
{ label: t('cb.menuCreateSpriteAnim'), onClick: () => void createFlipbookFromTexture(path) },
- { label: t('cb.menuCreateTileset'), onClick: () => void createTilesetFromTexture(path) },
+ { label: t('cb.menuCreateTileset'), onClick: () => setNewTilesetFor(path) },
]
: []),
...(isTileset
@@ -1350,6 +1352,13 @@ export function ContentBrowser() {
{!ctx && tip.card}
{ctx && <ContextMenu x={ctx.x} y={ctx.y} items={ctxItems} onClose={() => setCtx(null)} />}
{usagesPath && <FindUsagesDialog path={usagesPath} onClose={() => setUsagesPath(null)} />}
+ {newTilesetFor && (
+ <NewTilesetDialog
+ textureUrl={`estella://project/${newTilesetFor}`}
+ onCancel={() => setNewTilesetFor(null)}
+ onConfirm={(grid) => { void createTilesetFromTexture(newTilesetFor, grid); setNewTilesetFor(null); }}
+ />
+ )}
{confirmDel && (
<ConfirmDialog
title={t('cb.deleteTitle')}
diff --git a/desktop/src/panels/FlipbookEditor.tsx b/desktop/src/panels/FlipbookEditor.tsx
index 4f16e88e4..88db932ed 100644
--- a/desktop/src/panels/FlipbookEditor.tsx
+++ b/desktop/src/panels/FlipbookEditor.tsx
@@ -20,6 +20,7 @@ import {
} from 'esengine';
import { EmptyState } from '@/components/EmptyState';
import { GridField } from '@/components/GridField';
+import { ZoomControl } from '@/components/ZoomControl';
import { Transport } from '@/components/Transport';
import { SaveButton } from '@/components/SaveButton';
import { AnimClipDocument } from '@/flipbook/AnimClipDocument';
@@ -57,6 +58,15 @@ export function FlipbookEditor() {
const texUrl = info ? `estella://project/${info.path}` : null;
const [zoom, setZoom] = useState(2);
+ // Fit the whole sheet page into the scroll viewport (both axes).
+ const canvasRef = useRef<HTMLDivElement>(null);
+ const fitZoom = () => {
+ const c = canvasRef.current;
+ if (!c || !sheet || sheet.pageWidth <= 0 || sheet.pageHeight <= 0) return;
+ const pad = 24;
+ const z = Math.min((c.clientWidth - pad) / sheet.pageWidth, (c.clientHeight - pad) / sheet.pageHeight);
+ setZoom(Math.max(0.1, Math.min(8, z)));
+ };
// Live append stroke: ordered cells picked in one pointer gesture, one undo step.
const [stroke, setStroke] = useState<number[] | null>(null);
const strokeRef = useRef(stroke);
@@ -191,11 +201,7 @@ export function FlipbookEditor() {
<span className="fb-sep" />
</>
)}
- <label className="fb-field">
- <span>{t('fb.field.zoom')}</span>
- <input type="range" min={1} max={8} step={1} value={zoom}
- onChange={(e) => setZoom(Number(e.target.value))} />
- </label>
+ <ZoomControl zoom={zoom} min={0.1} onZoom={setZoom} onFit={fitZoom} />
<span className="fb-grow" />
<span className="fb-stat">
{sheet ? `${cols}×${rows} · ` : ''}{t('fb.frameCount', { count: asset.frames.length })}
@@ -356,7 +362,7 @@ export function FlipbookEditor() {
)}
{sheet && (
- <div className="fb-canvas" onPointerUp={commitStroke} onPointerLeave={commitStroke}>
+ <div ref={canvasRef} className="fb-canvas" onPointerUp={commitStroke} onPointerLeave={commitStroke}>
{!texUrl ? (
<div className="fb-warn">{t('fb.texNotFound', { ref: String(sheet.texture) || t('fb.refEmpty') })}</div>
) : (
diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsx
index 5d4da19d4..d7f6eba48 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -25,6 +25,7 @@ import type { EntityId } from '@/types';
import { createFromSource, type EntitySource } from '@/engine/entitySources';
import { CreatePopover } from '@/components/CreatePopover';
import { Segmented } from '@/components/Segmented';
+import { IconButton } from '@/components/IconButton';
// Must match .row height in outliner.css — the fixed row size the virtual list windows by.
const ROW_H = 24;
@@ -700,9 +701,8 @@ export function Outliner() {
<>
<div className="phead">
<SearchField placeholder={t('out.searchPlaceholder')} value={query} onChange={setQuery} />
- <button
- type="button"
- className={`pbtn${sortMode !== 'manual' ? ' on' : ''}`}
+ <IconButton
+ active={sortMode !== 'manual'}
title={t('out.sortLabel', { mode: SORT_MODE_LABEL[sortMode] })}
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
@@ -710,13 +710,13 @@ export function Outliner() {
}}
>
<ArrowDownUp size={14} strokeWidth={2} />
- </button>
- <button type="button" className="pbtn" title={t('out.newFolderTip')} onClick={() => newFolder('', null)}>
+ </IconButton>
+ <IconButton title={t('out.newFolderTip')} onClick={() => newFolder('', null)}>
<FolderPlus size={15} strokeWidth={2} />
- </button>
- <button type="button" className="pbtn" title={t('out.addEntityTip')} onClick={() => setCreateFor({ parent: null })}>
+ </IconButton>
+ <IconButton title={t('out.addEntityTip')} onClick={() => setCreateFor({ parent: null })}>
<Plus size={15} strokeWidth={2} />
- </button>
+ </IconButton>
</div>
{sceneCount > 0 && (
<div
diff --git a/desktop/src/panels/OutputLog.tsx b/desktop/src/panels/OutputLog.tsx
index 4432feebe..35a9873d4 100644
--- a/desktop/src/panels/OutputLog.tsx
+++ b/desktop/src/panels/OutputLog.tsx
@@ -14,6 +14,7 @@ import { LogStore, type LogLevel, type LogEntry } from '@/store/LogStore';
import { ContextMenu, type MenuItem } from '@/components/Menu';
import { usePanelWindow } from '@/components/PanelWindow';
import { SearchField } from '@/components/SearchField';
+import { IconButton } from '@/components/IconButton';
import { Toasts } from '@/store/Toasts';
import { t } from '@/i18n';
@@ -234,9 +235,8 @@ export function OutputLog() {
<Chip id="error" label={t('log.errors')} count={counts.error} />
</div>
<SearchField className="log-search" iconSize={12} placeholder={t('log.filterPlaceholder')} value={query} onChange={setQuery} />
- <button
- type="button"
- className={`pbtn${hidden.size > 0 ? ' on' : ''}`}
+ <IconButton
+ active={hidden.size > 0}
title={t('log.categories')}
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
@@ -244,21 +244,20 @@ export function OutputLog() {
}}
>
<ListFilter size={14} strokeWidth={1.85} />
- </button>
- <button
- type="button"
- className={`pbtn${showTime ? ' on' : ''}`}
+ </IconButton>
+ <IconButton
+ active={showTime}
title={t('log.showTimestamps')}
onClick={() => setShowTime((s) => !s)}
>
<Clock size={14} strokeWidth={1.85} />
- </button>
- <button type="button" className="pbtn" title={t('log.scrollToBottom')} onClick={scrollToBottom}>
+ </IconButton>
+ <IconButton title={t('log.scrollToBottom')} onClick={scrollToBottom}>
<ArrowDownToLine size={14} strokeWidth={1.85} />
- </button>
- <button type="button" className="pbtn" title={t('log.clearLog')} onClick={() => LogStore.clear()}>
+ </IconButton>
+ <IconButton title={t('log.clearLog')} onClick={() => LogStore.clear()}>
<Trash2 size={14} strokeWidth={1.85} />
- </button>
+ </IconButton>
</div>
<div ref={bodyRef} className="log-body" onScroll={onScroll} onContextMenu={onContextMenu}>
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index fa319d337..18cf574ad 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -13,9 +13,9 @@ import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
import {
Brush, Eraser, Square, Circle, Slash, PaintBucket, BoxSelect, Pipette,
FlipHorizontal, FlipVertical, RotateCw, Mountain, Plus, X, MousePointer2, Dices,
- ZoomIn, ZoomOut, Maximize2, Eye, EyeOff, Lock, Unlock, Bookmark,
+ Eye, EyeOff, Lock, Unlock, Bookmark,
} from 'lucide-react';
-import { encodeTile, type TilesetAsset, type TileStamp } from 'esengine';
+import { encodeTile, TilemapAPI, type TilesetAsset, type TileStamp } from 'esengine';
import { useTilemapPaint, type PaintTool, type PaletteTileset, type AtlasInfo } from '@/store/tilemapPaintStore';
import { useSelection } from '@/store/selectionStore';
import { SceneModel } from '@/engine/SceneModel';
@@ -23,7 +23,7 @@ import { SceneCommands } from '@/engine/SceneCommands';
import { ProjectStore } from '@/project/ProjectStore';
import { TILE_TOOL_KEY, exitTilePaint } from '@/tools/tileMode';
import { MOD_LABEL } from '@/commands/keybinding';
-import { usePanelWindow } from '@/components/PanelWindow';
+import { usePopover, Popover } from '@/components/Popover';
import { buildStampGhost } from '@/tools/tileStampGhost';
import { colsFor, rowsFor, TERRAIN_COLORS } from '@/tools/tileMath';
import { loadTilesetForPalette } from '@/tileset/loadTileset';
@@ -32,9 +32,12 @@ import { TilesetDocument } from '@/tileset/TilesetDocument';
import { useTilesetView } from '@/tileset/tilesetView';
import { createTilemapFromTileset } from '@/tilemap/createTilemap';
import { layerTilesetRefs } from '@/tilemap/layerTilesetModel';
+import { planTilesetRemovalFromBlob } from '@/tilemap/tilesetRemoval';
+import { confirm } from '@/components/confirm';
import { AnimPreview, tileThumbStyle, type TileAtlas } from '@/tools/tileThumb';
import { parseStampLibrary, serializeStampLibrary, stampLibraryKey, addStamp, removeStampAt, type SavedStamp } from '@/tools/stampLibrary';
import { IconButton } from '@/components/IconButton';
+import { ZoomControl } from '@/components/ZoomControl';
import { ContextMenu } from '@/components/Menu';
import { t } from '@/i18n';
@@ -96,14 +99,13 @@ export function TilemapPainter() {
setTilesets, setActiveTileset, setTilesetAsset, setStamp, setBrushTile, setTool, setTerrainSet, setWangColor,
setActiveAtlas, flipH, flipV, rotateCW, randomBrush, toggleRandomBrush,
} = useTilemapPaint();
- const win = usePanelWindow();
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);
+ const addPop = usePopover();
const [layerCtx, setLayerCtx] = useState<{ x: number; y: number; id: number } | null>(null);
const [renamingLayer, setRenamingLayer] = useState<number | null>(null);
const layerDragFrom = useRef<number | null>(null);
@@ -217,23 +219,6 @@ export function TilemapPainter() {
if (pal && natural && natural.w > 0) setZoom(clamp((pal.clientWidth - 16) / natural.w, 0.25, 8));
};
- // Dismiss the add-tileset menu on any outside click (the menu + its opener stop
- // their own pointerdown so those don't self-close it) — and on Escape, like
- // every other transient surface.
- useEffect(() => {
- if (!addOpen) return;
- const close = () => setAddOpen(false);
- const onKey = (e: KeyboardEvent) => {
- if (e.key === 'Escape') setAddOpen(false);
- };
- win.addEventListener('pointerdown', close);
- win.addEventListener('keydown', onKey);
- return () => {
- win.removeEventListener('pointerdown', close);
- win.removeEventListener('keydown', onKey);
- };
- }, [addOpen, win]);
-
// Re-render the layer strip on any model change (add/remove/rename/hide/lock).
const [, bumpModel] = useState(0);
useEffect(() => SceneModel.subscribe(() => bumpModel((v) => v + 1)), []);
@@ -351,16 +336,35 @@ export function TilemapPainter() {
const addTileset = (ref: string) => {
if (selectedId == null) return;
SceneCommands.setLayerTilesets(selectedId, [...layerTilesetRefs(selectedId), ref]);
- setAddOpen(false);
+ addPop.close();
setReloadKey((k) => k + 1);
};
- const removeTilesetAt = (i: number) => {
+ // Removing a tileset shifts every LATER tileset's global id range (firstId is a running
+ // sum over list order), so painted cells must be remapped in the same undo step or they
+ // silently corrupt. Cells of the removed tileset are erased — confirm when that loses work.
+ const removeTilesetAt = async (i: number) => {
if (selectedId == null) return;
- SceneCommands.setLayerTilesets(selectedId, layerTilesetRefs(selectedId).filter((_, j) => j !== i));
+ const newRefs = layerTilesetRefs(selectedId).filter((_, j) => j !== i);
+ const base = tilesets[i]?.firstId ?? 1;
+ const span = i + 1 < tilesets.length ? tilesets[i + 1].firstId - base : Infinity;
+ const rt = SceneModel.runtimeFor(selectedId);
+ const blob = rt != null ? TilemapAPI.exportChunks(rt) : '';
+ const { edits, cleared } = planTilesetRemovalFromBlob(blob, base, span);
+ if (cleared > 0) {
+ const name = tilesets[i]?.path.split(/[\\/]/).pop()?.replace(/\.estileset$/, '') ?? '';
+ const ok = await confirm({
+ title: t('tile.removeTilesetTitle'),
+ body: t('tile.removeTilesetBody', { count: cleared, name }),
+ confirmLabel: t('tile.removeTileset'),
+ danger: true,
+ });
+ if (!ok) return;
+ }
+ SceneCommands.removeLayerTileset(selectedId, newRefs, edits);
setReloadKey((k) => k + 1);
};
// The project's .estileset assets not already on this layer (populated on open).
- const addable = addOpen
+ const addable = addPop.isOpen
? ProjectStore.listAssets('tileset').filter((a) => !layerTilesetRefs(selectedId).includes(a.ref))
: [];
@@ -599,28 +603,34 @@ export function TilemapPainter() {
{ts.path.split(/[\\/]/).pop()?.replace(/\.estileset$/, '') ?? t('tile.tilesetN', { n: i + 1 })}
</button>
{tilesets.length > 1 && (
- <button type="button" className="tp-tsx" title={t('tile.removeTileset')} onClick={() => removeTilesetAt(i)}>
+ <button type="button" className="tp-tsx" title={t('tile.removeTileset')} onClick={() => void removeTilesetAt(i)}>
<X size={11} />
</button>
)}
</span>
))}
- <div className="tp-tsadd-wrap" onPointerDown={(e) => e.stopPropagation()}>
- <button type="button" className="tp-tsadd" title={t('tile.addTileset')} onClick={() => setAddOpen((o) => !o)}>
+ <div className="tp-tsadd-wrap">
+ <button
+ type="button" className="tp-tsadd" title={t('tile.addTileset')}
+ aria-haspopup="menu" aria-expanded={addPop.isOpen}
+ onClick={(e) => (addPop.isOpen ? addPop.close() : addPop.open(e.currentTarget))}
+ >
<Plus size={13} />
</button>
- {addOpen && (
- <div className="tp-tsmenu">
- {addable.length === 0 ? (
- <div className="empty-line empty-line--sm">{t('tile.noTilesetsToAdd')}</div>
- ) : (
- addable.map((a) => (
- <button key={a.ref} type="button" className="tp-tsmenu-item" onClick={() => addTileset(a.ref)}>
- {a.name.replace(/\.estileset$/, '')}
- </button>
- ))
- )}
- </div>
+ {addPop.isOpen && addPop.anchor && (
+ <Popover anchor={addPop.anchor} width="auto" onClose={addPop.close}>
+ <div className="tp-tsmenu-list" role="menu">
+ {addable.length === 0 ? (
+ <div className="empty-line empty-line--sm">{t('tile.noTilesetsToAdd')}</div>
+ ) : (
+ addable.map((a) => (
+ <button key={a.ref} type="button" role="menuitem" className="tp-tsmenu-item" onClick={() => addTileset(a.ref)}>
+ {a.name.replace(/\.estileset$/, '')}
+ </button>
+ ))
+ )}
+ </div>
+ </Popover>
)}
</div>
</div>
@@ -685,16 +695,7 @@ export function TilemapPainter() {
{stamp.w}×{stamp.h}
</span>
<span className="tp-grow" />
- <button type="button" className="tp-zbtn" title={t('tile.zoomOut')} onClick={() => setZoom((z) => clamp(z / 1.25, 0.25, 8))}>
- <ZoomOut size={13} />
- </button>
- <span className="tp-zpct">{Math.round(zoom * 100)}%</span>
- <button type="button" className="tp-zbtn" title={t('tile.zoomIn')} onClick={() => setZoom((z) => clamp(z * 1.25, 0.25, 8))}>
- <ZoomIn size={13} />
- </button>
- <button type="button" className="tp-zbtn" title={t('tile.fitWidth')} onClick={fitZoom}>
- <Maximize2 size={13} />
- </button>
+ <ZoomControl zoom={zoom} onZoom={setZoom} onFit={fitZoom} fitTitle={t('tile.fitWidth')} />
</div>
)}
<div
diff --git a/desktop/src/panels/TilesetEditor.tsx b/desktop/src/panels/TilesetEditor.tsx
index b172a94cd..d8511d5fd 100644
--- a/desktop/src/panels/TilesetEditor.tsx
+++ b/desktop/src/panels/TilesetEditor.tsx
@@ -25,6 +25,7 @@ import {
} from 'esengine';
import { Segmented } from '@/components/Segmented';
import { Select } from '@/components/Select';
+import { ZoomControl } from '@/components/ZoomControl';
import { usePanelWindow } from '@/components/PanelWindow';
import { GridField } from '@/components/GridField';
import { SaveButton } from '@/components/SaveButton';
@@ -175,6 +176,16 @@ export function TilesetEditor() {
const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);
const [zoom, setZoom] = useState(2);
+ // Fit the whole atlas into the scroll viewport (both axes) — lets a large sheet be
+ // seen at once, which the old 1×-floor range slider couldn't do.
+ const canvasRef = useRef<HTMLDivElement>(null);
+ const fitZoom = () => {
+ const c = canvasRef.current;
+ if (!c || !natural || natural.w <= 0 || natural.h <= 0) return;
+ const pad = 24;
+ const z = Math.min((c.clientWidth - pad) / natural.w, (c.clientHeight - pad) / natural.h);
+ setZoom(Math.max(0.1, Math.min(8, z)));
+ };
const mode = useTilesetView((s) => s.mode);
const setMode = useTilesetView((s) => s.setMode);
const [animTile, setAnimTile] = useState<number | null>(null);
@@ -572,11 +583,7 @@ export function TilesetEditor() {
/>
)}
<span className="ts-sep" />
- <label className="ts-field">
- <span>{t('tile.field.zoom')}</span>
- <input type="range" min={1} max={8} step={1} value={zoom}
- onChange={(e) => setZoom(Number(e.target.value))} />
- </label>
+ <ZoomControl zoom={zoom} min={0.1} onZoom={setZoom} onFit={fitZoom} />
<span className="ts-grow" />
<span className="ts-stat">
{cols}×{rows}{mode === 'collision' ? ` · ${t('tile.solidCount', { count: solidCount })}` : ''}
@@ -851,6 +858,7 @@ export function TilesetEditor() {
)}
<div
+ ref={canvasRef}
className={'ts-canvas' + (mode === 'terrain' ? ' is-terrain' : '')}
onPointerUp={commitDrag} onPointerLeave={commitDrag}
>
diff --git a/desktop/src/panels/UIWidgetsPanel.tsx b/desktop/src/panels/UIWidgetsPanel.tsx
index 3af0b3692..ace42c1b3 100644
--- a/desktop/src/panels/UIWidgetsPanel.tsx
+++ b/desktop/src/panels/UIWidgetsPanel.tsx
@@ -15,6 +15,8 @@ import { useSelection } from '@/store/selectionStore';
const UI_SOURCES = ENTITY_SOURCES.filter((s) => s.category === 'UI');
export function UIWidgetsPanel() {
+ // A clicked widget passes no drop point, so createFromSource centres it in the Canvas
+ // (the shared UI-placement path also handles the viewport drop's drop-point landing).
const add = (s: EntitySource) => {
void createFromSource(s, { parent: null }).then((id) => {
if (id != null) useSelection.getState().select(id);
diff --git a/desktop/src/theme/controls.css b/desktop/src/theme/controls.css
index 02f4c741d..fcd651252 100644
--- a/desktop/src/theme/controls.css
+++ b/desktop/src/theme/controls.css
@@ -67,20 +67,7 @@
padding: 0 8px;
border-bottom: 1px solid var(--border);
}
-.pbtn {
- width: 24px;
- height: 24px;
- display: grid;
- place-items: center;
- color: var(--text-mute);
- border-radius: var(--r-sm);
- flex-shrink: 0;
- transition: color var(--t-fast), background var(--t-fast);
-}
-.pbtn:hover { color: var(--text); background: var(--srf-4); }
-.pbtn:active { background: var(--srf-5); }
-.pbtn:disabled { opacity: 0.4; cursor: default; }
-.pbtn.on { color: var(--acc); }
+/* (.pbtn retired — panel-header glyph buttons now use <IconButton>, .icon-btn below.) */
.pbody { flex: 1; min-height: 0; overflow-y: auto; overflow-x: hidden; }
/* Shared dirty-aware Save button for asset-editor toolbars (components/SaveButton.tsx).
@@ -130,6 +117,11 @@
.icon-btn--outline:hover:not(:disabled) { color: var(--text); border-color: var(--text-mute); background: var(--srf-4); }
.icon-btn--outline.on { border-color: var(--acc); }
+/* — Zoom stepper (components/ZoomControl.tsx): − / % / + / fit for any magnified
+ fixed-size surface (tilemap palette, tileset atlas). — */
+.zoomctl { display: inline-flex; align-items: center; gap: 2px; flex: 0 0 auto; }
+.zoomctl-pct { min-width: 42px; text-align: center; color: var(--text-faint); font-variant-numeric: tabular-nums; font-size: var(--fs-xs); }
+
/* — Input well (components/NumField.tsx + the inspector's dropdown trigger):
a bordered inset the actual control sits in, focus ring on the well. — */
.field { height: 22px; flex: 1; min-width: 0; display: flex; align-items: center; background: var(--inset); border: 1px solid var(--border); border-radius: var(--r-sm); transition: border-color var(--t-fast), box-shadow var(--t-fast); }
diff --git a/desktop/src/theme/log.css b/desktop/src/theme/log.css
index c89a4927e..1675810cf 100644
--- a/desktop/src/theme/log.css
+++ b/desktop/src/theme/log.css
@@ -40,9 +40,6 @@
.log-row.error .ls { color: var(--error); }
.log-row .lm { color: var(--text-dim); }
-/* Active state for the header toggles (categories / timestamps). */
-.pbtn.on { color: var(--acc-hi); background: var(--srf-4); }
-
/* Category filter popover (built on the .ctx context-menu shell). */
.log-cats { max-height: 340px; overflow-y: auto; min-width: 184px; }
.log-cats .lc-head { display: flex; gap: 6px; padding: 2px 4px 4px; }
diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.css
index 1472720e4..1e26c484e 100644
--- a/desktop/src/theme/tilemap.css
+++ b/desktop/src/theme/tilemap.css
@@ -290,19 +290,13 @@
cursor: pointer;
}
.tp-tsadd:hover { color: var(--text); border-color: var(--star); }
-.tp-tsmenu {
- position: absolute;
- top: calc(100% + 4px);
- left: 0;
- z-index: 20;
+/* Item list inside the shared Popover shell (which supplies bg/border/shadow/clamp). */
+.tp-tsmenu-list {
+ display: flex;
+ flex-direction: column;
min-width: 140px;
max-height: 240px;
overflow-y: auto;
- padding: 4px;
- background: var(--srf-2);
- border: 1px solid var(--line);
- border-radius: var(--r-md);
- box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
}
.tp-tsmenu-item {
display: block;
diff --git a/desktop/src/theme/tileset.css b/desktop/src/theme/tileset.css
index ba0e052a1..c190cd5c0 100644
--- a/desktop/src/theme/tileset.css
+++ b/desktop/src/theme/tileset.css
@@ -2,6 +2,23 @@
/* SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team */
/* The .estileset editor panel (docs/REARCH_TILEMAP.md T2). */
+/* — New-tileset dialog: image + live grid overlay + slice fields. — */
+.nts { display: flex; flex-direction: column; gap: 12px; align-items: center; }
+.nts-preview {
+ position: relative;
+ max-width: 100%;
+ background: var(--srf-0) repeating-conic-gradient(var(--srf-2) 0 25%, transparent 0 50%) 0 0 / 16px 16px;
+ border: 1px solid var(--line);
+ border-radius: var(--r-sm);
+ overflow: hidden;
+}
+.nts-img { display: block; width: 100%; height: 100%; image-rendering: pixelated; }
+.nts-grid { position: absolute; inset: 0; pointer-events: none; }
+.nts-grid rect { fill: none; stroke: var(--star); stroke-opacity: 0.85; stroke-width: 1; }
+.nts-fields { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; width: 100%; }
+.nts-stat { font-size: var(--fs-sm); color: var(--text-dim); font-variant-numeric: tabular-nums; text-align: center; }
+.nts-warn { color: var(--warn, var(--star)); }
+
.ts-editor {
display: flex;
flex-direction: column;
diff --git a/desktop/src/tilemap/tilesetRemoval.ts b/desktop/src/tilemap/tilesetRemoval.ts
new file mode 100644
index 000000000..dda9210ea
--- /dev/null
+++ b/desktop/src/tilemap/tilesetRemoval.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tilesetRemoval.ts
+ * @brief Remap a TilemapLayer's painted cells when a tileset is removed from its
+ * multi-tileset list. Painted cells store ABSOLUTE global ids and a tileset's
+ * firstId is a running sum over list order, so dropping a non-last tileset
+ * shifts every later tileset's id range — silently corrupting already-painted
+ * tiles unless the stored ids are remapped in the same step. This is the pure
+ * math behind {@link SceneCommands.removeLayerTileset}: cells of the removed
+ * tileset clear, cells of later tilesets shift down to track the new layout,
+ * flip flags preserved.
+ */
+import { decodeTilemapChunks, CHUNK_SIZE, TILE_ID_MASK, TILE_FLAGS_MASK, type DecodedChunk } from 'esengine';
+import type { TilePaint } from '@/engine/SceneCommands';
+
+/**
+ * Remap one raw cell (13-bit id + 3 flip bits) for removing a tileset that occupies the
+ * global id range [base, base+span): cells below `base` are unchanged; cells IN the range
+ * clear to 0 (their tiles no longer exist); cells above shift their id down by `span`
+ * (flip flags kept). `span = Infinity` for the LAST tileset — its cells clear and nothing
+ * shifts (there is no later range to pull down).
+ */
+export function remapCellForRemoval(raw: number, base: number, span: number): number {
+ const id = raw & TILE_ID_MASK;
+ if (id === 0 || id < base) return raw;
+ if (id < base + span) return 0; // belongs to the removed tileset — gone
+ return ((id - span) & TILE_ID_MASK) | (raw & TILE_FLAGS_MASK);
+}
+
+/**
+ * The tile edits (world coords) removing the tileset requires, and how many painted cells
+ * it erases (belonged to the removed tileset). Pure over the layer's decoded chunk blob.
+ */
+export function planTilesetRemoval(
+ chunks: DecodedChunk[], base: number, span: number,
+): { edits: TilePaint[]; cleared: number } {
+ const edits: TilePaint[] = [];
+ let cleared = 0;
+ for (const ch of chunks) {
+ for (let t = 0; t < ch.tiles.length; t++) {
+ const raw = ch.tiles[t];
+ if (raw === 0) continue;
+ const next = remapCellForRemoval(raw, base, span);
+ if (next === raw) continue;
+ edits.push({ x: ch.x * CHUNK_SIZE + (t % CHUNK_SIZE), y: ch.y * CHUNK_SIZE + Math.floor(t / CHUNK_SIZE), tileId: next });
+ if (next === 0) cleared++;
+ }
+ }
+ return { edits, cleared };
+}
+
+/** Convenience: plan a removal straight from the `tilemap_exportChunks` blob. */
+export function planTilesetRemovalFromBlob(blob: string, base: number, span: number): { edits: TilePaint[]; cleared: number } {
+ return planTilesetRemoval(decodeTilemapChunks(blob), base, span);
+}
diff --git a/desktop/src/tileset/openTileset.ts b/desktop/src/tileset/openTileset.ts
index 5dcc55fa1..e8b77c80a 100644
--- a/desktop/src/tileset/openTileset.ts
+++ b/desktop/src/tileset/openTileset.ts
@@ -33,8 +33,18 @@ export async function openTileset(path: string): Promise<void> {
}
}
-/** Create a .estileset next to a texture (referencing it), then open it. */
-export async function createTilesetFromTexture(texturePath: string): Promise<void> {
+/** The tile grid a new .estileset is sliced with (from NewTilesetDialog). */
+export interface TilesetGridInit {
+ tileWidth: number;
+ tileHeight: number;
+ margin: number;
+ spacing: number;
+ columns: number;
+}
+
+/** Create a .estileset next to a texture (referencing it), then open it. `grid` is the
+ * slice chosen in the New-Tileset dialog; omitted falls back to a plain 16×16 grid. */
+export async function createTilesetFromTexture(texturePath: string, grid?: TilesetGridInit): Promise<void> {
const ref = ProjectStore.assetRef(texturePath);
if (!ref) {
Toasts.push(t('tile.toast.texUntracked'), 'error');
@@ -45,7 +55,10 @@ export async function createTilesetFromTexture(texturePath: string): Promise<voi
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 g = grid ?? { tileWidth: 16, tileHeight: 16, margin: 0, spacing: 0, columns: 1 };
+ const asset = createTilesetAsset(ref, g.tileWidth, g.tileHeight, g.columns);
+ asset.margin = g.margin;
+ asset.spacing = g.spacing;
const uuid = crypto.randomUUID();
try {
await window.estella.fs.write(rel, JSON.stringify(serializeTileset(asset), null, 2) + '\n');
diff --git a/desktop/tests/tileset-removal.test.ts b/desktop/tests/tileset-removal.test.ts
new file mode 100644
index 000000000..d06d358e1
--- /dev/null
+++ b/desktop/tests/tileset-removal.test.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { TILE_FLIP_H, CHUNK_SIZE, type DecodedChunk } from 'esengine';
+import { remapCellForRemoval, planTilesetRemoval } from '@/tilemap/tilesetRemoval';
+
+// A tileset occupying global ids [5, 9) (span 4): removing it should erase 5..8 and pull
+// everything ≥ 9 down by 4, so surviving tiles keep their identity in the new layout.
+describe('remapCellForRemoval', () => {
+ it('leaves cells below the removed range untouched', () => {
+ expect(remapCellForRemoval(3, 5, 4)).toBe(3);
+ expect(remapCellForRemoval(0, 5, 4)).toBe(0); // empty stays empty
+ });
+ it('clears cells that belong to the removed tileset', () => {
+ expect(remapCellForRemoval(5, 5, 4)).toBe(0);
+ expect(remapCellForRemoval(8, 5, 4)).toBe(0);
+ });
+ it('shifts cells above the removed range down by span', () => {
+ expect(remapCellForRemoval(9, 5, 4)).toBe(5);
+ expect(remapCellForRemoval(12, 5, 4)).toBe(8);
+ });
+ it('preserves flip flags when shifting', () => {
+ expect(remapCellForRemoval(9 | TILE_FLIP_H, 5, 4)).toBe(5 | TILE_FLIP_H);
+ });
+ it('treats the last tileset (span Infinity) as clear-only', () => {
+ expect(remapCellForRemoval(4, 5, Infinity)).toBe(4);
+ expect(remapCellForRemoval(5, 5, Infinity)).toBe(0);
+ expect(remapCellForRemoval(200, 5, Infinity)).toBe(0);
+ });
+});
+
+/** A one-chunk blob with the given (localIndex → raw) cells at chunk grid (cx, cy). */
+function chunk(cx: number, cy: number, cells: Record<number, number>): DecodedChunk {
+ const tiles = new Uint16Array(CHUNK_SIZE * CHUNK_SIZE);
+ for (const [k, v] of Object.entries(cells)) tiles[Number(k)] = v;
+ return { x: cx, y: cy, tiles };
+}
+
+describe('planTilesetRemoval', () => {
+ it('emits only the changed cells, in world coords, and counts erasures', () => {
+ // idx0 (0,0)=3 below → no edit; idx1 (1,0)=6 in range → clear; idx2 (2,0)=10 above → 6;
+ // idx17 (1,1)=9|flipH above → 5|flipH.
+ const { edits, cleared } = planTilesetRemoval(
+ [chunk(0, 0, { 0: 3, 1: 6, 2: 10, 17: 9 | TILE_FLIP_H })], 5, 4,
+ );
+ expect(cleared).toBe(1);
+ expect(edits).toContainEqual({ x: 1, y: 0, tileId: 0 });
+ expect(edits).toContainEqual({ x: 2, y: 0, tileId: 6 });
+ expect(edits).toContainEqual({ x: 1, y: 1, tileId: 5 | TILE_FLIP_H });
+ expect(edits).not.toContainEqual({ x: 0, y: 0, tileId: 3 }); // unchanged → not emitted
+ expect(edits).toHaveLength(3);
+ });
+
+ it('maps chunk grid coords to world tile coords', () => {
+ const { edits } = planTilesetRemoval([chunk(1, -1, { 0: 9 })], 5, 4);
+ expect(edits).toEqual([{ x: CHUNK_SIZE, y: -CHUNK_SIZE, tileId: 5 }]);
+ });
+
+ it('is a no-op when nothing references the removed range', () => {
+ const { edits, cleared } = planTilesetRemoval([chunk(0, 0, { 0: 1, 1: 2 })], 5, 4);
+ expect(edits).toHaveLength(0);
+ expect(cleared).toBe(0);
+ });
+});
diff --git a/desktop/tests/ui-widget-canvas.test.ts b/desktop/tests/ui-widget-canvas.test.ts
index 15fb5e5df..a29161a98 100644
--- a/desktop/tests/ui-widget-canvas.test.ts
+++ b/desktop/tests/ui-widget-canvas.test.ts
@@ -16,6 +16,10 @@ vi.mock('@/engine/SceneCommands', () => ({
rec.calls.push({ name: prefab.name, parent: opts.parent });
return 100 + rec.calls.length; // a fresh id per create
},
+ // The shared UI-placement step (centre on click / at the drop point) runs after
+ // create; this test only asserts Canvas hosting, so stub it out.
+ centerUINodeInCanvas: () => {},
+ placeUINodeAtWorld: () => {},
},
}));