Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(tilemap): bucket + line tools; unify the drag-stroke driver

esengine0ecae4e03b07
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index bbdde14b9..0c2543174 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -10,7 +10,10 @@
*/
import { useEffect, useRef, useState } from 'react';
-import { Brush, Eraser, Square, Pipette, FlipHorizontal, FlipVertical, RotateCw, Mountain } from 'lucide-react';
+import {
+ Brush, Eraser, Square, Slash, PaintBucket, Pipette,
+ FlipHorizontal, FlipVertical, RotateCw, Mountain,
+} from 'lucide-react';
import { parseTileset, encodeTile, type TilesetAsset } from 'esengine';
import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';
import { useSelection } from '@/store/selectionStore';
@@ -30,6 +33,8 @@ const TOOLS: { id: PaintTool; icon: typeof Brush; label: string }[] = [
{ id: 'brush', icon: Brush, label: '画笔' },
{ id: 'erase', icon: Eraser, label: '擦除' },
{ id: 'rect', icon: Square, label: '矩形' },
+ { id: 'line', icon: Slash, label: '直线' },
+ { id: 'bucket', icon: PaintBucket, label: '油漆桶' },
{ id: 'eyedropper', icon: Pipette, label: '吸管' },
{ id: 'terrain', icon: Mountain, label: '地形' },
];
diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.ts
index 2226c8d35..4302a1fa9 100644
--- a/desktop/src/store/tilemapPaintStore.ts
+++ b/desktop/src/store/tilemapPaintStore.ts
@@ -14,7 +14,7 @@ import {
singleStamp, flipStampH, flipStampV, rotateStampCW, encodeTile,
} from 'esengine';
-export type PaintTool = 'brush' | 'erase' | 'rect' | 'eyedropper' | 'terrain';
+export type PaintTool = 'brush' | 'erase' | 'rect' | 'line' | 'bucket' | 'eyedropper' | 'terrain';
interface TilemapPaintState {
/** Active `.estileset` palette (project-relative path), or null. */
diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.ts
index 7829591c4..ed6397fee 100644
--- a/desktop/src/tools/tileTools.ts
+++ b/desktop/src/tools/tileTools.ts
@@ -2,11 +2,13 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file tileTools.ts
- * @brief The tilemap paint tools — brush / erase / rect / eyedropper. Active only
- * when a TilemapLayer is selected (the host resolves that); each operates on the
- * selected layer via SceneCommands' tile-paint stroke API. The brush is a
- * {@link TileStamp}, so a single click stamps a 1×1 tile and a palette marquee
- * stamps a whole pattern (with per-cell flip/rotate flags preserved).
+ * @brief The tilemap paint tools — brush / erase / rect / line / bucket / eyedropper /
+ * terrain. Active only when a TilemapLayer is selected (the host resolves that);
+ * each operates on the selected layer via SceneCommands' tile-paint stroke API.
+ * The brush is a {@link TileStamp}, so a single click stamps a 1×1 tile and a
+ * palette marquee stamps a whole pattern (with per-cell flip/rotate flags).
+ * Drag tools (brush/erase/terrain) share one stroke driver; gesture tools
+ * (rect/line/bucket) commit once on release.
*/
import {
TilemapAPI, tileIdOf, encodeTile, singleStamp, type TileStamp,
@@ -15,6 +17,7 @@ import {
import { ViewportController } from '@/engine/ViewportController';
import { SceneCommands, type TilePaint } from '@/engine/SceneCommands';
import { SceneModel } from '@/engine/SceneModel';
+import { Toasts } from '@/store/Toasts';
import { useSelection } from '@/store/selectionStore';
import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';
import type { EditorTool, PointerInput } from './EditorTool';
@@ -32,6 +35,7 @@ function cursorTile(clientX: number, clientY: number, sourceId: number): { x: nu
const selectedTilemap = (): number | null => useSelection.getState().selectedId;
const activeStamp = (): TileStamp => useTilemapPaint.getState().stamp;
+const mod = (n: number, m: number): number => ((n % m) + m) % m;
/** Edits for the non-empty cells of `stamp` anchored (top-left) at tile (ox, oy). */
function stampEdits(stamp: TileStamp, ox: number, oy: number): TilePaint[] {
@@ -46,90 +50,128 @@ function stampEdits(stamp: TileStamp, ox: number, oy: number): TilePaint[] {
return edits;
}
-/** Brush: stamps the active pattern as a live stroke (one undo step). */
-function makeBrushTool(): EditorTool {
- let stroke: { sourceId: number; last: string } | null = null;
- const stampAt = (id: number, ox: number, oy: number) => {
- for (const e of stampEdits(activeStamp(), ox, oy)) {
- SceneCommands.paintTileLive(id, e.x, e.y, e.tileId);
- }
- };
+/** The stamp cell to lay at world tile (x, y) when tiling the pattern continuously. */
+function tiledCell(stamp: TileStamp, x: number, y: number): number {
+ return stamp.cells[mod(y, stamp.h) * stamp.w + mod(x, stamp.w)];
+}
+
+// ── Shared drag-stroke driver ────────────────────────────────────────────────
+// begin() opens a per-stroke context (null aborts); onCell() runs once per newly
+// entered tile during press+drag; end() commits. Used by brush/erase/terrain.
+interface StrokeSpec<C> {
+ id: string;
+ begin(sourceId: number): C | null;
+ onCell(ctx: C, x: number, y: number): void;
+ end(ctx: C): void;
+}
+
+function makeStrokeTool<C>(spec: StrokeSpec<C>): EditorTool {
+ let active: { ctx: C; sourceId: number; last: string } | null = null;
return {
- id: 'tilemap.brush',
+ id: spec.id,
onPointerDown(p, ctx) {
const selId = selectedTilemap();
if (selId == null) return false;
const tile = cursorTile(p.clientX, p.clientY, selId);
if (!tile) return false;
- SceneCommands.beginTilePaint(selId);
- stampAt(selId, tile.x, tile.y);
- stroke = { sourceId: selId, last: `${tile.x},${tile.y}` };
+ const c = spec.begin(selId);
+ if (c == null) return false;
+ spec.onCell(c, tile.x, tile.y);
+ active = { ctx: c, sourceId: selId, last: `${tile.x},${tile.y}` };
ctx.capture(p.pointerId);
return true;
},
onPointerMove(p) {
- if (!stroke) return;
- const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ if (!active) return;
+ const tile = cursorTile(p.clientX, p.clientY, active.sourceId);
if (!tile) return;
const key = `${tile.x},${tile.y}`;
- if (key === stroke.last) return;
- stampAt(stroke.sourceId, tile.x, tile.y);
- stroke.last = key;
+ if (key === active.last) return;
+ spec.onCell(active.ctx, tile.x, tile.y);
+ active.last = key;
},
onPointerUp(p, ctx) {
- if (!stroke) return;
+ if (!active) return;
ctx.release(p.pointerId);
- SceneCommands.endTilePaint();
- stroke = null;
+ spec.end(active.ctx);
+ active = null;
},
cancel() {
- if (!stroke) return;
+ if (!active) return;
// No mid-stroke tile rollback yet; commit what is painted (matches pointercancel).
- SceneCommands.endTilePaint();
- stroke = null;
+ spec.end(active.ctx);
+ active = null;
},
};
}
-/** Erase: clears the cell under the cursor — a live stroke, one undo step. */
-function makeEraseTool(): EditorTool {
- let stroke: { sourceId: number; last: string } | null = null;
- return {
- id: 'tilemap.erase',
- onPointerDown(p, ctx) {
- const selId = selectedTilemap();
- if (selId == null) return false;
- const tile = cursorTile(p.clientX, p.clientY, selId);
- if (!tile) return false;
- SceneCommands.beginTilePaint(selId);
- SceneCommands.paintTileLive(selId, tile.x, tile.y, 0);
- stroke = { sourceId: selId, last: `${tile.x},${tile.y}` };
- ctx.capture(p.pointerId);
- return true;
- },
- onPointerMove(p) {
- if (!stroke) return;
- const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
- if (!tile) return;
- const key = `${tile.x},${tile.y}`;
- if (key === stroke.last) return;
- SceneCommands.paintTileLive(stroke.sourceId, tile.x, tile.y, 0);
- stroke.last = key;
- },
- onPointerUp(p, ctx) {
- if (!stroke) return;
- ctx.release(p.pointerId);
- SceneCommands.endTilePaint();
- stroke = null;
- },
- cancel() {
- if (!stroke) return;
- SceneCommands.endTilePaint();
- stroke = null;
- },
- };
+const brushTool = makeStrokeTool<number>({
+ id: 'tilemap.brush',
+ begin: (selId) => { SceneCommands.beginTilePaint(selId); return selId; },
+ onCell: (selId, x, y) => {
+ for (const e of stampEdits(activeStamp(), x, y)) SceneCommands.paintTileLive(selId, e.x, e.y, e.tileId);
+ },
+ end: () => SceneCommands.endTilePaint(),
+});
+
+const eraseTool = makeStrokeTool<number>({
+ id: 'tilemap.erase',
+ begin: (selId) => { SceneCommands.beginTilePaint(selId); return selId; },
+ onCell: (selId, x, y) => SceneCommands.paintTileLive(selId, x, y, 0),
+ end: () => SceneCommands.endTilePaint(),
+});
+
+// ── Terrain (autotile) brush ─────────────────────────────────────────────────
+interface TerrainCtx {
+ sourceId: number;
+ rt: number;
+ set: number;
+ indices: TerrainIndices;
+ assigned: Map<string, 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;
}
+function recomputeTerrain(s: TerrainCtx, x: number, y: number): void {
+ const set = terrainAt(s, x, y);
+ if (set == null) return;
+ 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));
+}
+
+/** Join (x,y) to the active terrain, then re-resolve it and its 8 neighbours. */
+function stampTerrain(s: TerrainCtx, x: number, y: number): void {
+ s.assigned.set(`${x},${y}`, s.set);
+ recomputeTerrain(s, x, y);
+ for (const n of TERRAIN_NEIGHBORS) recomputeTerrain(s, x + n.dx, y + n.dy);
+}
+
+const terrainTool = makeStrokeTool<TerrainCtx>({
+ id: 'tilemap.terrain',
+ begin: (selId) => {
+ const rt = SceneModel.runtimeFor(selId);
+ const ps = useTilemapPaint.getState();
+ const asset = ps.tilesetAsset;
+ if (rt == null || !asset) return null;
+ 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() };
+ },
+ onCell: (s, x, y) => { if (!s.assigned.has(`${x},${y}`)) stampTerrain(s, x, y); },
+ end: () => SceneCommands.endTilePaint(),
+});
+
+// ── Gesture tools (commit once on release / click) ───────────────────────────
+
/** Rect fill: drag a rectangle, tile the active stamp across it on release (one step). */
function makeRectTool(): EditorTool {
let stroke: { sourceId: number; startX: number; startY: number } | null = null;
@@ -145,7 +187,7 @@ function makeRectTool(): EditorTool {
return true;
},
onPointerMove() {
- // Rect previews on release (no live fill) — matches the prior behavior.
+ // Rect previews on release (no live fill).
},
onPointerUp(p, ctx) {
if (!stroke) return;
@@ -160,7 +202,7 @@ function makeRectTool(): EditorTool {
const edits: TilePaint[] = [];
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
- const raw = stamp.cells[((y - y0) % stamp.h) * stamp.w + ((x - x0) % stamp.w)];
+ const raw = tiledCell(stamp, x - x0, y - y0);
if (tileIdOf(raw) === 0) continue;
edits.push({ x, y, tileId: raw });
}
@@ -169,85 +211,99 @@ function makeRectTool(): EditorTool {
}
stroke = null;
},
- cancel() {
- stroke = null;
- },
+ cancel() { stroke = null; },
};
}
-/**
- * Terrain brush: paint a logical terrain and autotile. Each painted cell joins the active
- * terrain; the cell and its 8 neighbours are re-resolved against the tileset's terrain
- * rules, so the right edge/corner tile is chosen automatically. A cell's terrain is the
- * in-stroke assignment if painted, else reverse-derived from its current tile.
- */
-function makeTerrainTool(): EditorTool {
- let stroke:
- | { sourceId: number; rt: number; set: number; indices: TerrainIndices; assigned: Map<string, number> }
- | null = null;
-
- const terrainAt = (s: NonNullable<typeof stroke>, 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 recompute = (s: NonNullable<typeof stroke>, x: number, y: number) => {
- const set = terrainAt(s, x, y);
- if (set == null) return;
- 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 stampTerrain = (s: NonNullable<typeof stroke>, x: number, y: number) => {
- s.assigned.set(`${x},${y}`, s.set);
- recompute(s, x, y);
- for (const n of TERRAIN_NEIGHBORS) recompute(s, x + n.dx, y + n.dy);
- };
-
+/** Line: drag from press to release, stamp the brush along the Bresenham line (one step). */
+function makeLineTool(): EditorTool {
+ let stroke: { sourceId: number; startX: number; startY: number } | null = null;
return {
- id: 'tilemap.terrain',
+ id: 'tilemap.line',
onPointerDown(p, ctx) {
const selId = selectedTilemap();
if (selId == null) return false;
- const rt = SceneModel.runtimeFor(selId);
- const ps = useTilemapPaint.getState();
- const asset = ps.tilesetAsset;
- if (rt == null || !asset) return false;
const tile = cursorTile(p.clientX, p.clientY, selId);
if (!tile) return false;
- const indices = buildTerrainIndices(asset);
- if (!indices.sets.has(ps.terrainSet)) return false; // active terrain has no tiles yet
- SceneCommands.beginTilePaint(selId);
- stroke = { sourceId: selId, rt, set: ps.terrainSet, indices, assigned: new Map() };
- stampTerrain(stroke, tile.x, tile.y);
+ stroke = { sourceId: selId, startX: tile.x, startY: tile.y };
ctx.capture(p.pointerId);
return true;
},
- onPointerMove(p) {
- if (!stroke) return;
- const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
- if (!tile || stroke.assigned.has(`${tile.x},${tile.y}`)) return;
- stampTerrain(stroke, tile.x, tile.y);
- },
+ onPointerMove() {},
onPointerUp(p, ctx) {
if (!stroke) return;
ctx.release(p.pointerId);
- SceneCommands.endTilePaint();
- stroke = null;
- },
- cancel() {
- if (!stroke) return;
- SceneCommands.endTilePaint();
+ const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ if (tile) {
+ const stamp = activeStamp();
+ const edits: TilePaint[] = [];
+ let x = stroke.startX;
+ let y = stroke.startY;
+ const dx = Math.abs(tile.x - x);
+ const dy = -Math.abs(tile.y - y);
+ const sx = x < tile.x ? 1 : -1;
+ const sy = y < tile.y ? 1 : -1;
+ let err = dx + dy;
+ for (;;) {
+ for (const e of stampEdits(stamp, x, y)) edits.push(e);
+ if (x === tile.x && y === tile.y) break;
+ const e2 = 2 * err;
+ if (e2 >= dy) { err += dy; x += sx; }
+ if (e2 <= dx) { err += dx; y += sy; }
+ }
+ if (edits.length > 0) SceneCommands.paintTiles(stroke.sourceId, edits);
+ }
stroke = null;
},
+ cancel() { stroke = null; },
};
}
+// Bound the flood fill so an empty-target fill on an infinite layer can't run away.
+const BUCKET_CAP = 16384;
+
+/** Bucket: flood-fill the contiguous same-id region from the cursor, tiling the stamp. */
+const bucketTool: EditorTool = {
+ id: 'tilemap.bucket',
+ onPointerDown(p) {
+ const selId = selectedTilemap();
+ if (selId == null) return false;
+ const rt = SceneModel.runtimeFor(selId);
+ const tile = cursorTile(p.clientX, p.clientY, selId);
+ if (rt == null || !tile) return false;
+ const stamp = activeStamp();
+ const target = tileIdOf(TilemapAPI.getTile(rt, tile.x, tile.y));
+ // A 1×1 brush of the target id would fill in place — nothing to do.
+ if (stamp.w === 1 && stamp.h === 1 && tileIdOf(stamp.cells[0]) === target) return false;
+
+ const visited = new Set<string>([`${tile.x},${tile.y}`]);
+ const queue: [number, number][] = [[tile.x, tile.y]];
+ const edits: TilePaint[] = [];
+ let capped = false;
+ const NEI: [number, number][] = [[1, 0], [-1, 0], [0, 1], [0, -1]];
+ while (queue.length > 0) {
+ const [x, y] = queue.shift()!;
+ const raw = tiledCell(stamp, x, y);
+ if (tileIdOf(raw) !== 0) edits.push({ x, y, tileId: raw });
+ if (visited.size >= BUCKET_CAP) { capped = true; break; }
+ for (const [dx, dy] of NEI) {
+ const nx = x + dx;
+ const ny = y + dy;
+ const k = `${nx},${ny}`;
+ if (visited.has(k)) continue;
+ if (tileIdOf(TilemapAPI.getTile(rt, nx, ny)) !== target) continue;
+ visited.add(k);
+ queue.push([nx, ny]);
+ }
+ }
+ if (edits.length > 0) SceneCommands.paintTiles(selId, edits);
+ if (capped) Toasts.push(`油漆桶到达 ${BUCKET_CAP} 格上限,已部分填充`, 'warn');
+ return false; // one-shot, no drag
+ },
+ onPointerMove() {},
+ onPointerUp() {},
+};
+
/** Eyedropper: one-shot — read the raw cell (id + flip flags) under the cursor into the brush. */
const eyedropperTool: EditorTool = {
id: 'tilemap.eyedropper',
@@ -265,13 +321,15 @@ const eyedropperTool: EditorTool = {
onPointerUp() {},
};
-/** Tile tools keyed by PaintTool (brush/erase/rect/eyedropper). */
+/** Tile tools keyed by PaintTool. */
export const TILE_TOOLS: Record<PaintTool, EditorTool> = {
- brush: makeBrushTool(),
- erase: makeEraseTool(),
+ brush: brushTool,
+ erase: eraseTool,
rect: makeRectTool(),
+ line: makeLineTool(),
+ bucket: bucketTool,
eyedropper: eyedropperTool,
- terrain: makeTerrainTool(),
+ terrain: terrainTool,
};
export type { PointerInput };
diff --git a/desktop/tests/editor-tools.test.ts b/desktop/tests/editor-tools.test.ts
index 3b2679ae2..31b3ffed8 100644
--- a/desktop/tests/editor-tools.test.ts
+++ b/desktop/tests/editor-tools.test.ts
@@ -24,7 +24,7 @@ describe('editor tool registry', () => {
});
it('has the tile tools keyed by PaintTool', () => {
- for (const k of ['brush', 'erase', 'rect', 'eyedropper', 'terrain'] as const) {
+ for (const k of ['brush', 'erase', 'rect', 'line', 'bucket', 'eyedropper', 'terrain'] as const) {
expect(TILE_TOOLS[k]).toBeDefined();
expect(implementsContract(TILE_TOOLS[k])).toBe(true);
}