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.

fix(tilemap): align paint tools' preview with what they paint + fix multi-tileset bugs

yhh5997ecb7c3a2
diff --git a/desktop/src/i18n/messages/tile.ts b/desktop/src/i18n/messages/tile.ts
index 0333a852d..c9c078da9 100644
--- a/desktop/src/i18n/messages/tile.ts
+++ b/desktop/src/i18n/messages/tile.ts
@@ -43,6 +43,7 @@ export const tileMessages = defineMessages({
// — Painter tileset tabs —
'tile.tilesetN': { en: 'Tileset {n}', zh: '瓦片集 {n}' },
+ 'tile.tilesetGid': { en: '{path} (gid {gid}+)', zh: '{path}(gid {gid}+)' },
'tile.addTileset': { en: 'Add tileset', zh: '添加瓦片集' },
'tile.removeTileset': { en: 'Remove tileset', zh: '移除瓦片集' },
'tile.noTilesetsToAdd': { en: 'No tilesets to add', zh: '没有可添加的瓦片集' },
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index e91bc5a3a..1bd6ebb79 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -100,7 +100,7 @@ function BrushThumbnail({ stamp, atlas }: { stamp: TileStamp; atlas: AtlasInfo |
export function TilemapPainter() {
const {
tilesetPath, tilesets, activeTileset, stamp, tool, terrainSet,
- setTilesets, setActiveTileset, setTilesetAsset, setStamp, setTool, setTerrainSet,
+ setTilesets, setActiveTileset, setTilesetAsset, setStamp, setBrushTile, setTool, setTerrainSet,
setActiveAtlas, flipH, flipV, rotateCW, randomBrush, toggleRandomBrush,
} = useTilemapPaint();
const selectedId = useSelection((s) => s.selectedId);
@@ -150,6 +150,10 @@ export function TilemapPainter() {
return () => { alive = false; };
}, [selectedId, setTilesets, reloadKey]);
+ // A tile selection (the select-tool marquee) is layer-scoped: drop it when the active
+ // layer changes so a stale marquee can't drive copy/cut/delete on the wrong layer.
+ useEffect(() => { useTilemapPaint.getState().setSelection(null); }, [selectedId]);
+
const [asset, setAsset] = useState<TilesetAsset | null>(null);
useEffect(() => {
let alive = true;
@@ -509,9 +513,11 @@ export function TilemapPainter() {
<span
key={ts.path}
className={'tp-tschip' + (i === activeTileset ? ' is-active' : '')}
- title={`${ts.path} (gid ${ts.firstId}+)`}
+ title={t('tile.tilesetGid', { path: ts.path, gid: ts.firstId })}
>
- <button type="button" className="tp-tsbtn" onClick={() => setActiveTileset(i)}>
+ {/* Switching tabs resets the brush to the new tileset's first tile so the
+ stamp + thumbnail can't linger on the previous tileset's (now blank) gids. */}
+ <button type="button" className="tp-tsbtn" onClick={() => { setActiveTileset(i); setBrushTile(ts.firstId); }}>
{ts.path.split(/[\\/]/).pop()?.replace(/\.estileset$/, '') ?? t('tile.tilesetN', { n: i + 1 })}
</button>
{tilesets.length > 1 && (
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index de072e9ed..f00458dde 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -966,7 +966,7 @@ export function Viewport() {
// Hidden for rect/line while their gesture preview draws the shape.
const dragging = TilePaintPreview.get() != null;
const hov = hoverTileRef.current;
- const gesturing = dragging && (paint.tool === 'rect' || paint.tool === 'line');
+ const gesturing = dragging && (paint.tool === 'rect' || paint.tool === 'line' || paint.tool === 'ellipse');
// Random brush lays ONE sampled tile per cell, so its footprint is 1×1 — only a
// pattern brush (or erase, which clears the whole w×h) previews at the stamp size.
const stampSized = paint.tool === 'erase' || (paint.tool === 'brush' && !paint.randomBrush);
diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.ts
index bede238b6..1a188bda0 100644
--- a/desktop/src/store/tilemapPaintStore.ts
+++ b/desktop/src/store/tilemapPaintStore.ts
@@ -108,10 +108,13 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({
activeTileset: 0,
tilesetPath: tilesets[0]?.path ?? null,
tilesetAsset: tilesets[0]?.asset ?? null,
+ // A different tileset's terrain sets don't map across — reset so the terrain
+ // tool can't silently no-op on a stale, now-out-of-range index.
+ terrainSet: 0,
}),
setActiveTileset: (index) => set((s) => {
const ts = s.tilesets[index];
- return ts ? { activeTileset: index, tilesetPath: ts.path, tilesetAsset: ts.asset } : {};
+ return ts ? { activeTileset: index, tilesetPath: ts.path, tilesetAsset: ts.asset, terrainSet: 0 } : {};
}),
setTileset: (tilesetPath) => set({ tilesetPath }),
setTilesetAsset: (tilesetAsset) => set({ tilesetAsset }),
diff --git a/desktop/src/tools/tileClipboard.ts b/desktop/src/tools/tileClipboard.ts
index 041307a0f..e4ed9fc9a 100644
--- a/desktop/src/tools/tileClipboard.ts
+++ b/desktop/src/tools/tileClipboard.ts
@@ -64,8 +64,10 @@ export function cutSelection(): void {
/** Paste = make the clipboard the active brush + switch to the brush tool to place it. */
export function pasteClipboard(): void {
- const { clipboard, setStamp, setTool } = useTilemapPaint.getState();
- if (!clipboard) return;
- setStamp(clipboard);
- setTool('brush');
+ const st = useTilemapPaint.getState();
+ if (!st.clipboard) return;
+ st.setStamp(st.clipboard);
+ st.setTool('brush');
+ // Paste places the copied pattern verbatim — random scatter would defeat that.
+ if (st.randomBrush) st.toggleRandomBrush();
}
diff --git a/desktop/src/tools/tileMode.ts b/desktop/src/tools/tileMode.ts
index 3b8c519f2..c3cd59d4b 100644
--- a/desktop/src/tools/tileMode.ts
+++ b/desktop/src/tools/tileMode.ts
@@ -11,7 +11,7 @@
* switching the transform tool to Scale).
*
* Modality: a tilemap being SELECTED is the tile context. Non-colliding letters
- * (B/U/L/G/M/I/T, plus E for erase) enter a paint tool from there. The letters that
+ * (B/U/O/L/G/M/I/T, plus E for erase) enter a paint tool from there. The letters that
* collide with the transform tools (Q/W/E/R) are consumed for painting ONLY while a
* paint tool is active, and Q/W then double as the explicit exit back to
* select/move — so there is never a hidden "painting yet the toolbar says Scale" state.
diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.ts
index b011c0086..8f9533c23 100644
--- a/desktop/src/tools/tileTools.ts
+++ b/desktop/src/tools/tileTools.ts
@@ -214,13 +214,18 @@ interface TerrainCtx {
set: number;
indices: TerrainIndices;
assigned: Map<string, number>;
+ // firstId − 1 of the active tileset. buildTerrainIndices keys by tileset-LOCAL id,
+ // but cells store GLOBAL gids, so read a cell as gid − base and write local + base
+ // (base is 0 for a single-tileset layer, so this is a no-op there).
+ base: number;
}
function terrainAt(s: TerrainCtx, x: number, y: number): number | null {
const key = `${x},${y}`;
if (s.assigned.has(key)) return s.assigned.get(key)!;
- const id = tileIdOf(TilemapAPI.getTile(s.rt, x, y));
- return s.indices.tileTerrain.get(id) ?? null;
+ const gid = tileIdOf(TilemapAPI.getTile(s.rt, x, y));
+ if (gid === 0) return null;
+ return s.indices.tileTerrain.get(gid - s.base) ?? null;
}
function recomputeTerrain(s: TerrainCtx, x: number, y: number): void {
@@ -229,8 +234,8 @@ function recomputeTerrain(s: TerrainCtx, x: number, y: number): void {
const index = s.indices.sets.get(set);
if (!index) return;
const neighbors = TERRAIN_NEIGHBORS.map((n) => terrainAt(s, x + n.dx, y + n.dy) === set);
- const tileId = resolveAutotile(index, neighbors);
- if (tileId > 0) SceneCommands.paintTileLive(s.sourceId, x, y, encodeTile(tileId));
+ const local = resolveAutotile(index, neighbors);
+ if (local > 0) SceneCommands.paintTileLive(s.sourceId, x, y, encodeTile(local + s.base));
}
/** Join (x,y) to the active terrain, then re-resolve it and its 8 neighbours. */
@@ -250,7 +255,8 @@ const terrainTool = makeStrokeTool<TerrainCtx>({
const indices = buildTerrainIndices(asset);
if (!indices.sets.has(ps.terrainSet)) return null; // active terrain has no tiles yet
SceneCommands.beginTilePaint(selId);
- return { sourceId: selId, rt, set: ps.terrainSet, indices, assigned: new Map() };
+ const base = (ps.tilesets[ps.activeTileset]?.firstId ?? 1) - 1;
+ return { sourceId: selId, rt, set: ps.terrainSet, indices, assigned: new Map(), base };
},
onCell: (s, x, y) => { if (!s.assigned.has(`${x},${y}`)) stampTerrain(s, x, y); },
end: () => SceneCommands.endTilePaint(),
@@ -333,10 +339,14 @@ function makeLineTool(): EditorTool {
TilePaintPreview.clear();
const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
if (tile) {
- const stamp = activeStamp();
+ // One tiled cell per line cell (like rect/ellipse), so the thin-line preview
+ // matches what lands — not the whole w×h footprint stamped at every point.
+ const pick = cellPicker(activeStamp());
const edits: TilePaint[] = [];
for (const c of lineCells(stroke.startX, stroke.startY, tile.x, tile.y)) {
- for (const e of brushEdits(stamp, c.x, c.y)) edits.push(e);
+ const raw = pick(c.x, c.y);
+ if (tileIdOf(raw) === 0) continue;
+ edits.push({ x: c.x, y: c.y, tileId: raw });
}
if (edits.length > 0) SceneCommands.paintTiles(stroke.sourceId, edits);
}
@@ -481,7 +491,19 @@ const eyedropperTool: EditorTool = {
if (!tile) return false;
const rt = SceneModel.runtimeFor(selId);
const raw = rt != null ? TilemapAPI.getTile(rt, tile.x, tile.y) : 0;
- if (tileIdOf(raw) > 0) useTilemapPaint.getState().setStamp(singleStamp(raw));
+ const gid = tileIdOf(raw);
+ if (gid > 0) {
+ const ps = useTilemapPaint.getState();
+ // On a multi-tileset layer, switch the palette to the tileset that owns the
+ // picked gid (tilesets are in ascending firstId order) so its atlas resolves
+ // the brush ghost — otherwise the hover preview goes blank.
+ let owner = ps.activeTileset;
+ for (let i = 0; i < ps.tilesets.length; i++) {
+ if (ps.tilesets[i].firstId <= gid) owner = i; else break;
+ }
+ if (owner !== ps.activeTileset) ps.setActiveTileset(owner);
+ ps.setStamp(singleStamp(raw));
+ }
return false; // no ongoing stroke
},
onPointerMove() {},
diff --git a/desktop/tests/tilemap-paint-store.test.ts b/desktop/tests/tilemap-paint-store.test.ts
index 746303073..5a4d1fe74 100644
--- a/desktop/tests/tilemap-paint-store.test.ts
+++ b/desktop/tests/tilemap-paint-store.test.ts
@@ -6,16 +6,22 @@
* separately) — the painter + viewport tools read `stamp` straight off this store.
*/
import { describe, it, expect, beforeEach } from 'vitest';
-import { tileIdOf, tileFlagsOf } from 'esengine';
-import { useTilemapPaint } from '@/store/tilemapPaintStore';
+import { tileIdOf, tileFlagsOf, type TilesetAsset } from 'esengine';
+import { useTilemapPaint, type PaletteTileset } from '@/store/tilemapPaintStore';
import { pasteClipboard } from '@/tools/tileClipboard';
+const fakeTileset = (path: string, firstId: number): PaletteTileset =>
+ ({ path, asset: {} as TilesetAsset, firstId });
+
describe('tilemap paint store', () => {
beforeEach(() => {
useTilemapPaint.getState().setBrushTile(1);
useTilemapPaint.getState().setSelection(null);
useTilemapPaint.getState().setClipboard(null);
useTilemapPaint.getState().setTool(null);
+ useTilemapPaint.getState().setTilesets([]);
+ useTilemapPaint.getState().setTerrainSet(0);
+ if (useTilemapPaint.getState().randomBrush) useTilemapPaint.getState().toggleRandomBrush();
});
it('setBrushTile makes a 1×1 stamp of that id with no flags', () => {
@@ -71,4 +77,24 @@ describe('tilemap paint store', () => {
pasteClipboard();
expect(useTilemapPaint.getState().tool).toBe('select'); // unchanged
});
+
+ it('paste turns off random mode so the copied pattern lands verbatim', () => {
+ useTilemapPaint.getState().setClipboard({ w: 2, h: 2, cells: [1, 2, 3, 4] });
+ useTilemapPaint.getState().toggleRandomBrush();
+ expect(useTilemapPaint.getState().randomBrush).toBe(true);
+ pasteClipboard();
+ expect(useTilemapPaint.getState().randomBrush).toBe(false);
+ expect(useTilemapPaint.getState().stamp).toEqual({ w: 2, h: 2, cells: [1, 2, 3, 4] });
+ });
+
+ it('switching tileset resets terrainSet (a stale index silently no-ops the terrain tool)', () => {
+ useTilemapPaint.getState().setTilesets([fakeTileset('a.estileset', 1), fakeTileset('b.estileset', 100)]);
+ useTilemapPaint.getState().setTerrainSet(3);
+ useTilemapPaint.getState().setActiveTileset(1);
+ expect(useTilemapPaint.getState().terrainSet).toBe(0);
+ // A fresh palette load resets it too.
+ useTilemapPaint.getState().setTerrainSet(2);
+ useTilemapPaint.getState().setTilesets([fakeTileset('c.estileset', 1)]);
+ expect(useTilemapPaint.getState().terrainSet).toBe(0);
+ });
});