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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(tilemap): select tool + copy / cut / paste / delete
esengineb0016c906d22
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsxindex 0c2543174..bfc9ab2ee 100644--- a/desktop/src/panels/TilemapPainter.tsx+++ b/desktop/src/panels/TilemapPainter.tsx@@ -11,7 +11,7 @@import { useEffect, useRef, useState } from 'react';import {- Brush, Eraser, Square, Slash, PaintBucket, Pipette,+ Brush, Eraser, Square, Slash, PaintBucket, BoxSelect, Pipette,FlipHorizontal, FlipVertical, RotateCw, Mountain,} from 'lucide-react';import { parseTileset, encodeTile, type TilesetAsset } from 'esengine';@@ -19,6 +19,7 @@ import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';import { useSelection } from '@/store/selectionStore';import { SceneModel } from '@/engine/SceneModel';import { ProjectStore } from '@/project/ProjectStore';+import { copySelection, cutSelection, deleteSelection, pasteClipboard } from '@/tools/tileClipboard';function colsFor(width: number, tileW: number, margin: number, spacing: number): number {const stride = tileW + spacing;@@ -35,6 +36,7 @@ const TOOLS: { id: PaintTool; icon: typeof Brush; label: string }[] = [{ id: 'rect', icon: Square, label: '矩形' },{ id: 'line', icon: Slash, label: '直线' },{ id: 'bucket', icon: PaintBucket, label: '油漆桶' },+ { id: 'select', icon: BoxSelect, label: '选区 (复制/剪切/粘贴 ⌘C/X/V)' },{ id: 'eyedropper', icon: Pipette, label: '吸管' },{ id: 'terrain', icon: Mountain, label: '地形' },];@@ -92,15 +94,24 @@ export function TilemapPainter() {const [sel, setSel] = useState<SelRect | null>(null);const dragAnchor = useRef<{ c: number; r: number } | null>(null);- // H/V/R transform the active stamp — only while a paint tool is active, so they don't- // shadow the transform-tool shortcuts when not painting.+ // Paint-mode keys (only while a paint tool is active, so they don't shadow the+ // transform-tool shortcuts): select-tool clipboard (⌘/Ctrl C/X/V, Delete) and the+ // stamp transforms H/V/R.useEffect(() => {const onKey = (e: KeyboardEvent) => {const st = useTilemapPaint.getState();- if (!st.tool || e.metaKey || e.ctrlKey || e.altKey) return;+ if (!st.tool) return;const t = e.target as HTMLElement | null;if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;+ const mod = e.metaKey || e.ctrlKey;const k = e.key.toLowerCase();+ if (st.tool === 'select') {+ if (mod && k === 'c') { copySelection(); e.preventDefault(); return; }+ if (mod && k === 'x') { cutSelection(); e.preventDefault(); return; }+ if (e.key === 'Delete' || e.key === 'Backspace') { deleteSelection(); e.preventDefault(); return; }+ }+ if (mod && k === 'v') { pasteClipboard(); e.preventDefault(); return; }+ if (mod || e.altKey) return;if (k === 'h') { st.flipH(); e.preventDefault(); }else if (k === 'v') { st.flipV(); e.preventDefault(); }else if (k === 'r') { st.rotateCW(); e.preventDefault(); }diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 2d201ba74..542d4dc39 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -8,6 +8,7 @@ import {} from 'lucide-react';import { useEditorStore } from '@/store/editorStore';import { useSelection } from '@/store/selectionStore';+import { useTilemapPaint } from '@/store/tilemapPaintStore';import { commands } from '@/commands';import { EngineHost } from '@/engine/EngineHost';import { PlayRealm } from '@/engine/PlayRealm';@@ -196,6 +197,7 @@ export function Viewport() {const playHostRef = useRef<HTMLDivElement>(null);const gizmoRef = useRef<HTMLDivElement>(null);const selectionRef = useRef<HTMLDivElement>(null);+ const tileSelRef = useRef<HTMLDivElement>(null);// Camera pan (middle/right drag) is built-in navigation, separate from tools.const panRef = useRef<{ px: number; py: number } | null>(null);// The tool that owns the in-progress left-button stroke (move/up route to it).@@ -303,6 +305,37 @@ export function Viewport() {sel.style.opacity = '0';}+ // Tile-select marquee: an axis-aligned rect over the selected TilemapLayer's+ // chosen tile range, in screen space (its world corners projected each frame).+ const ts = tileSelRef.current;+ if (ts) {+ const paint = useTilemapPaint.getState();+ const tsel = paint.tool === 'select' ? paint.selection : null;+ const layer = ready && sid != null+ ? SceneModel.entityBySource(sid)?.components.find((c) => c.type === 'TilemapLayer')+ : undefined;+ const cs = layer?.data as { cellSize?: { x: number; y: number } } | undefined;+ const origin = ready && rt != null ? ViewportController.getEntityXY(rt) : null;+ if (tsel && cs?.cellSize && origin) {+ const x0 = Math.min(tsel.x0, tsel.x1);+ const y0 = Math.min(tsel.y0, tsel.y1);+ const x1 = Math.max(tsel.x0, tsel.x1);+ const y1 = Math.max(tsel.y0, tsel.y1);+ const tl = ViewportController.worldToClient(origin.x + x0 * cs.cellSize.x, origin.y - y0 * cs.cellSize.y);+ const br = ViewportController.worldToClient(origin.x + (x1 + 1) * cs.cellSize.x, origin.y - (y1 + 1) * cs.cellSize.y);+ if (tl && br) {+ ts.style.transform = `translate(${tl.x}px, ${tl.y}px)`;+ ts.style.width = `${br.x - tl.x}px`;+ ts.style.height = `${br.y - tl.y}px`;+ ts.style.opacity = '1';+ } else {+ ts.style.opacity = '0';+ }+ } else {+ ts.style.opacity = '0';+ }+ }+// Scene-camera gizmos — only in edit mode (in play the viewport IS the// game camera), and only when gizmos are on.const camsOn = ready && showG && !useEditorStore.getState().isPlaying;@@ -584,6 +617,7 @@ export function Viewport() {)}<div ref={selectionRef} className="viewport__selection" aria-hidden="true" />+ <div ref={tileSelRef} className="viewport__tilesel" aria-hidden="true" /><div ref={gizmoRef} className="viewport__gizmo" aria-hidden="true"><GizmoGlyph tool={tool} />diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.tsindex 4302a1fa9..345cfc39d 100644--- a/desktop/src/store/tilemapPaintStore.ts+++ b/desktop/src/store/tilemapPaintStore.ts@@ -14,7 +14,15 @@ import {singleStamp, flipStampH, flipStampV, rotateStampCW, encodeTile,} from 'esengine';-export type PaintTool = 'brush' | 'erase' | 'rect' | 'line' | 'bucket' | 'eyedropper' | 'terrain';+export type PaintTool = 'brush' | 'erase' | 'rect' | 'line' | 'bucket' | 'select' | 'eyedropper' | 'terrain';++/** A rectangular tile-grid selection (inclusive corners, unordered). */+export interface TileRect {+ x0: number;+ y0: number;+ x1: number;+ y1: number;+}interface TilemapPaintState {/** Active `.estileset` palette (project-relative path), or null. */@@ -25,11 +33,17 @@ interface TilemapPaintState {stamp: TileStamp;/** The active terrain set index (for the terrain tool). */terrainSet: number;+ /** The select tool's current marquee (tile coords), or null. */+ selection: TileRect | null;+ /** The copy/cut buffer — a stamp lifted from a selection; pasted via the brush. */+ clipboard: TileStamp | null;/** The active tool; null = not painting (the Viewport selects normally). */tool: PaintTool | null;setTileset(path: string | null): void;setTilesetAsset(asset: TilesetAsset | null): void;setStamp(stamp: TileStamp): void;+ setSelection(selection: TileRect | null): void;+ setClipboard(clipboard: TileStamp | null): void;/** Set a 1×1 brush of one tile id (palette single-click; loses any flip flags). */setBrushTile(tileId: number): void;setTerrainSet(set: number): void;@@ -44,10 +58,14 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({tilesetAsset: null,stamp: singleStamp(encodeTile(1)),terrainSet: 0,+ selection: null,+ clipboard: null,tool: null,setTileset: (tilesetPath) => set({ tilesetPath }),setTilesetAsset: (tilesetAsset) => set({ tilesetAsset }),setStamp: (stamp) => set({ stamp }),+ setSelection: (selection) => set({ selection }),+ setClipboard: (clipboard) => set({ clipboard }),setBrushTile: (tileId) => set({ stamp: singleStamp(encodeTile(tileId)) }),setTerrainSet: (terrainSet) => set({ terrainSet }),flipH: () => set((s) => ({ stamp: flipStampH(s.stamp) })),diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.cssindex fcd49c3f7..f03787818 100644--- a/desktop/src/theme/app.css+++ b/desktop/src/theme/app.css@@ -583,6 +583,17 @@inset 0 0 0 1px rgba(14, 15, 18, 0.4);will-change: transform, width, height, opacity;}+.viewport__tilesel {+ position: absolute;+ top: 0;+ left: 0;+ z-index: 1;+ opacity: 0;+ pointer-events: none;+ border: 1px dashed #5ac8fa;+ background: rgba(90, 200, 250, 0.12);+ will-change: transform, width, height, opacity;+}.viewport__stage.has-grid {background-image:linear-gradient(var(--line-soft) 1px, transparent 1px),diff --git a/desktop/src/tools/tileClipboard.ts b/desktop/src/tools/tileClipboard.tsnew file mode 100644index 000000000..041307a0f--- /dev/null+++ b/desktop/src/tools/tileClipboard.ts@@ -0,0 +1,71 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file tileClipboard.ts+ * @brief Copy / cut / delete / paste for the tilemap select tool. A selection is lifted+ * into a {@link TileStamp} (raw cells, flip flags preserved), so paste just makes+ * it the active brush and switches to the brush tool — reusing the stamp paint+ * path. Copy/cut/delete read & write the selected region on the selected layer.+ */+import { TilemapAPI, type TileStamp } from 'esengine';+import { SceneCommands, type TilePaint } from '@/engine/SceneCommands';+import { SceneModel } from '@/engine/SceneModel';+import { useSelection } from '@/store/selectionStore';+import { useTilemapPaint, type TileRect } from '@/store/tilemapPaintStore';++/** The selected layer's source id + its live runtime entity, or null. */+function activeLayer(): { sourceId: number; rt: number } | null {+ const sourceId = useSelection.getState().selectedId;+ if (sourceId == null) return null;+ const rt = SceneModel.runtimeFor(sourceId);+ return rt == null ? null : { sourceId, rt };+}++const order = (r: TileRect) => ({+ x0: Math.min(r.x0, r.x1), y0: Math.min(r.y0, r.y1),+ x1: Math.max(r.x0, r.x1), y1: Math.max(r.y0, r.y1),+});++/** Lift the current selection into a stamp (raw cells incl. flip flags). */+export function readSelectionStamp(): TileStamp | null {+ const sel = useTilemapPaint.getState().selection;+ const layer = activeLayer();+ if (!sel || !layer) return null;+ const { x0, y0, x1, y1 } = order(sel);+ const cells: number[] = [];+ for (let y = y0; y <= y1; y++) {+ for (let x = x0; x <= x1; x++) cells.push(TilemapAPI.getTile(layer.rt, x, y));+ }+ return { w: x1 - x0 + 1, h: y1 - y0 + 1, cells };+}++export function copySelection(): void {+ const stamp = readSelectionStamp();+ if (stamp) useTilemapPaint.getState().setClipboard(stamp);+}++/** Clear every cell in the selection as one undo step. */+export function deleteSelection(): void {+ const sel = useTilemapPaint.getState().selection;+ const layer = activeLayer();+ if (!sel || !layer) return;+ const { x0, y0, x1, y1 } = order(sel);+ const edits: TilePaint[] = [];+ for (let y = y0; y <= y1; y++) {+ for (let x = x0; x <= x1; x++) edits.push({ x, y, tileId: 0 });+ }+ if (edits.length > 0) SceneCommands.paintTiles(layer.sourceId, edits);+}++export function cutSelection(): void {+ copySelection();+ deleteSelection();+}++/** 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');+}diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.tsindex ed6397fee..141d57590 100644--- a/desktop/src/tools/tileTools.ts+++ b/desktop/src/tools/tileTools.ts@@ -304,6 +304,41 @@ const bucketTool: EditorTool = {onPointerUp() {},};+/** Select: drag a marquee over the layer to define a tile-rect selection (copy/cut/paste). */+function makeSelectTool(): EditorTool {+ let anchor: { x: number; y: number } | null = null;+ let sourceId: number | null = null;+ return {+ id: 'tilemap.select',+ onPointerDown(p, ctx) {+ const selId = selectedTilemap();+ if (selId == null) return false;+ const tile = cursorTile(p.clientX, p.clientY, selId);+ if (!tile) return false;+ anchor = tile;+ sourceId = selId;+ useTilemapPaint.getState().setSelection({ x0: tile.x, y0: tile.y, x1: tile.x, y1: tile.y });+ ctx.capture(p.pointerId);+ return true;+ },+ onPointerMove(p) {+ if (!anchor || sourceId == null) return;+ const tile = cursorTile(p.clientX, p.clientY, sourceId);+ if (!tile) return;+ useTilemapPaint.getState().setSelection({ x0: anchor.x, y0: anchor.y, x1: tile.x, y1: tile.y });+ },+ onPointerUp(p, ctx) {+ ctx.release(p.pointerId);+ anchor = null;+ sourceId = null;+ },+ cancel() {+ anchor = null;+ sourceId = null;+ },+ };+}+/** Eyedropper: one-shot — read the raw cell (id + flip flags) under the cursor into the brush. */const eyedropperTool: EditorTool = {id: 'tilemap.eyedropper',@@ -328,6 +363,7 @@ export const TILE_TOOLS: Record<PaintTool, EditorTool> = {rect: makeRectTool(),line: makeLineTool(),bucket: bucketTool,+ select: makeSelectTool(),eyedropper: eyedropperTool,terrain: terrainTool,};diff --git a/desktop/tests/editor-tools.test.ts b/desktop/tests/editor-tools.test.tsindex 31b3ffed8..eb9d50b10 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', 'line', 'bucket', 'eyedropper', 'terrain'] as const) {+ for (const k of ['brush', 'erase', 'rect', 'line', 'bucket', 'select', 'eyedropper', 'terrain'] as const) {expect(TILE_TOOLS[k]).toBeDefined();expect(implementsContract(TILE_TOOLS[k])).toBe(true);}diff --git a/desktop/tests/tilemap-paint-store.test.ts b/desktop/tests/tilemap-paint-store.test.tsindex 04d9db57b..746303073 100644--- a/desktop/tests/tilemap-paint-store.test.ts+++ b/desktop/tests/tilemap-paint-store.test.ts@@ -8,10 +8,14 @@import { describe, it, expect, beforeEach } from 'vitest';import { tileIdOf, tileFlagsOf } from 'esengine';import { useTilemapPaint } from '@/store/tilemapPaintStore';+import { pasteClipboard } from '@/tools/tileClipboard';describe('tilemap paint store', () => {beforeEach(() => {useTilemapPaint.getState().setBrushTile(1);+ useTilemapPaint.getState().setSelection(null);+ useTilemapPaint.getState().setClipboard(null);+ useTilemapPaint.getState().setTool(null);});it('setBrushTile makes a 1×1 stamp of that id with no flags', () => {@@ -46,4 +50,25 @@ describe('tilemap paint store', () => {useTilemapPaint.getState().rotateCW();expect(useTilemapPaint.getState().stamp).toEqual({ w: 2, h: 1, cells: [1, 2] });});++ it('selection + clipboard set/clear', () => {+ useTilemapPaint.getState().setSelection({ x0: 1, y0: 2, x1: 4, y1: 5 });+ expect(useTilemapPaint.getState().selection).toEqual({ x0: 1, y0: 2, x1: 4, y1: 5 });+ useTilemapPaint.getState().setSelection(null);+ expect(useTilemapPaint.getState().selection).toBeNull();+ });++ it('paste makes the clipboard the active brush and switches to the brush tool', () => {+ useTilemapPaint.getState().setTool('select');+ useTilemapPaint.getState().setClipboard({ w: 2, h: 2, cells: [1, 2, 3, 4] });+ pasteClipboard();+ expect(useTilemapPaint.getState().stamp).toEqual({ w: 2, h: 2, cells: [1, 2, 3, 4] });+ expect(useTilemapPaint.getState().tool).toBe('brush');+ });++ it('paste with an empty clipboard is a no-op', () => {+ useTilemapPaint.getState().setTool('select');+ pasteClipboard();+ expect(useTilemapPaint.getState().tool).toBe('select'); // unchanged+ });});