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(editor): tilemap paint feel — live rect/line preview, block eraser, stroke rollback
yhhf8a2312fd9ed
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 795077c22..8559ef5a1 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -984,6 +984,19 @@ export class SceneCommandsImpl {if (s) this.commitTilePaint_(s.sourceId, s.before);}+ /**+ * Discard the open paint stroke (Esc / pointercancel). The live edits only touched+ * the C++ tilemap ({@link paintTileLive} never writes the model), so re-import the+ * pre-stroke blob to revert the viewport — no model write, no undo step.+ */+ cancelTilePaint(): void {+ const s = this.tilePaint;+ this.tilePaint = null;+ if (!s) return;+ const rt = this.model.runtimeFor(s.sourceId);+ if (rt !== undefined) TilemapAPI.importChunks(rt, s.before);+ }+// 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/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 77bd613eb..438f8a013 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -28,6 +28,7 @@ import { cursorTile } from '@/tools/tileTools';import { GIZMO, type GizmoAxis } from '@/tools/gizmo';import { selectionPivot, gizmoScreenAngleRad } from '@/tools/transformTools';import { Marquee } from '@/tools/marquee';+import { TilePaintPreview } from '@/tools/tilePreview';// A React pointer event → the tool-facing PointerInput (no DOM coupling in tools).const toInput = (e: ReactPointerEvent): PointerInput => ({@@ -383,6 +384,11 @@ export function Viewport() {const marqueeRef = useRef<HTMLDivElement>(null);const tileSelRef = useRef<HTMLDivElement>(null);const tilePreviewRef = useRef<HTMLDivElement>(null);+ // Gesture-paint preview (rect fill / line cells): a container whose ghost-cell+ // children are pooled + positioned imperatively in the rAF (rect/line defer their+ // commit to release, so this shows the shape mid-drag).+ const tilePaintRef = useRef<HTMLDivElement>(null);+ const paintPoolRef = useRef<HTMLDivElement[]>([]);const hoverTileRef = useRef<{ x: number; y: number } | null>(null);// Camera pan (middle/right drag) is built-in navigation, separate from tools.const panRef = useRef<{ px: number; py: number } | null>(null);@@ -564,16 +570,21 @@ export function Viewport() {ts.style.opacity = '0';}- // Brush footprint preview: a ghost rect at the hovered tile sized to the active- // stamp (1×1 for erase/bucket/terrain), so painting isn't blind.+ // Brush footprint preview: a ghost rect at the hovered tile. brush/erase size it+ // to the active stamp (they lay/erase its w×h); the other tools mark a single+ // cell. Hidden for rect/line while their gesture preview is drawing the shape.+ const dragging = TilePaintPreview.get() != null;const pv = tilePreviewRef.current;if (pv) {- const FOOT: Record<string, boolean> = { brush: true, erase: true, bucket: true, terrain: true };+ const stampSized = paint.tool === 'brush' || paint.tool === 'erase';+ const SINGLE: Record<string, boolean> = { bucket: true, terrain: true, rect: true, line: true };const hov = hoverTileRef.current;- const showFoot = paint.tool != null && FOOT[paint.tool] && hov && cs?.cellSize && origin;+ const gesturing = dragging && (paint.tool === 'rect' || paint.tool === 'line');+ const showFoot = paint.tool != null && (stampSized || SINGLE[paint.tool])+ && !gesturing && hov && cs?.cellSize && origin;if (showFoot && hov && cs?.cellSize && origin) {- const fw = paint.tool === 'brush' ? paint.stamp.w : 1;- const fh = paint.tool === 'brush' ? paint.stamp.h : 1;+ const fw = stampSized ? paint.stamp.w : 1;+ const fh = stampSized ? paint.stamp.h : 1;const tl = ViewportController.worldToClient(origin.x + hov.x * cs.cellSize.x, origin.y - hov.y * cs.cellSize.y);const br = ViewportController.worldToClient(origin.x + (hov.x + fw) * cs.cellSize.x, origin.y - (hov.y + fh) * cs.cellSize.y);if (tl && br) {@@ -588,6 +599,45 @@ export function Viewport() {pv.style.opacity = '0';}}++ // Gesture-paint preview: rect fill covers the whole region (one ghost cell),+ // line ghosts each tile it crosses. Pooled child divs — grow on demand, hide+ // the unused tail — positioned like the footprint above.+ const pp = tilePaintRef.current;+ if (pp) {+ const shape = TilePaintPreview.get();+ const pool = paintPoolRef.current;+ let used = 0;+ if (shape && cs?.cellSize && origin) {+ const cw = cs.cellSize.x;+ const ch = cs.cellSize.y;+ const place = (tx: number, ty: number, w: number, h: number): void => {+ const tl = ViewportController.worldToClient(origin.x + tx * cw, origin.y - ty * ch);+ const br = ViewportController.worldToClient(origin.x + (tx + w) * cw, origin.y - (ty + h) * ch);+ if (!tl || !br) return;+ let cell = pool[used];+ if (!cell) {+ cell = document.createElement('div');+ cell.className = 'viewport__tilepaint-cell';+ pp.appendChild(cell);+ pool[used] = cell;+ }+ cell.style.transform = `translate(${tl.x}px, ${tl.y}px)`;+ cell.style.width = `${br.x - tl.x}px`;+ cell.style.height = `${br.y - tl.y}px`;+ cell.style.display = 'block';+ used++;+ };+ if (shape.kind === 'rect') {+ const x0 = Math.min(shape.x0, shape.x1);+ const y0 = Math.min(shape.y0, shape.y1);+ place(x0, y0, Math.abs(shape.x1 - shape.x0) + 1, Math.abs(shape.y1 - shape.y0) + 1);+ } else {+ for (const c of shape.cells) place(c.x, c.y, 1, 1);+ }+ }+ for (let i = used; i < pool.length; i++) pool[i].style.display = 'none';+ }}// Scene-camera gizmos — only in edit mode (in play the viewport IS the@@ -847,6 +897,20 @@ export function Viewport() {t.onPointerUp(toInput(e), toolCtx);};+ // pointercancel (OS/gesture interruption) aborts the stroke instead of committing —+ // the tool rolls back its live edits, matching Esc.+ const cancelDrag = (e: ReactPointerEvent) => {+ if (panRef.current) {+ stageRef.current?.releasePointerCapture(e.pointerId);+ panRef.current = null;+ return;+ }+ const t = activeToolRef.current;+ if (!t) return;+ activeToolRef.current = null;+ t.cancel?.(toolCtx);+ };+// Drag an asset from the Content Browser into the scene → place it at the drop// point (one undoable step): a `.esprefab` instantiates the prefab; an image// spawns a Sprite entity sized to the texture.@@ -970,7 +1034,7 @@ export function Viewport() {onPointerDown={onPointerDown}onPointerMove={onPointerMove}onPointerUp={endDrag}- onPointerCancel={endDrag}+ onPointerCancel={cancelDrag}onPointerLeave={() => { StatsStore.clearCursor(); hoverTileRef.current = null; }}onContextMenu={(e) => e.preventDefault()}onDragOver={onDragOver}@@ -1174,6 +1238,7 @@ export function Viewport() {<div ref={marqueeRef} className="viewport__marquee" aria-hidden="true" /><div ref={tileSelRef} className="viewport__tilesel" aria-hidden="true" /><div ref={tilePreviewRef} className="viewport__tilepreview" aria-hidden="true" />+ <div ref={tilePaintRef} className="viewport__tilepaint" aria-hidden="true" /><div ref={gizmoRef} className="viewport__gizmo" aria-hidden="true"><GizmoOverlay tool={tool} active={activeGizmoAxis} />diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.cssindex 72a7d9a1d..bd2e18f5d 100644--- a/desktop/src/theme/app.css+++ b/desktop/src/theme/app.css@@ -627,6 +627,24 @@box-shadow: inset 0 0 0 1px rgba(14, 15, 18, 0.5);will-change: transform, width, height, opacity;}+/* Gesture-paint preview (rect fill / line cells) container — the ghost cells are+ pooled child divs the rAF positions; the container itself is inert. */+.viewport__tilepaint {+ position: absolute;+ top: 0;+ left: 0;+ z-index: 2;+ pointer-events: none;+}+.viewport__tilepaint-cell {+ position: absolute;+ top: 0;+ left: 0;+ display: none;+ border: 1px solid rgba(90, 200, 250, 0.7);+ background: rgba(90, 200, 250, 0.22);+ will-change: transform, width, height;+}.viewport__stage.has-grid {background-image:linear-gradient(var(--line-soft) 1px, transparent 1px),diff --git a/desktop/src/tools/tilePreview.ts b/desktop/src/tools/tilePreview.tsnew file mode 100644index 000000000..c935db827--- /dev/null+++ b/desktop/src/tools/tilePreview.ts@@ -0,0 +1,29 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file tilePreview.ts+ * @brief The in-progress gesture-paint preview (rect fill region / line cells, in+ * TILE coords), shared from the rect/line tools to the Viewport overlay. A+ * plain module ref read by the overlay's per-frame rAF (like {@link Marquee}+ * and the tile-brush hover) — the rect/line tools defer their commit to+ * release, so this is what shows the shape mid-drag. No React churn.+ */++/** What a deferred paint gesture will affect, in the layer's tile grid. */+export type TilePreviewShape =+ | { kind: 'rect'; x0: number; y0: number; x1: number; y1: number }+ | { kind: 'line'; cells: { x: number; y: number }[] };++let shape: TilePreviewShape | null = null;++export const TilePaintPreview = {+ set(s: TilePreviewShape | null): void {+ shape = s;+ },+ clear(): void {+ shape = null;+ },+ get(): TilePreviewShape | null {+ return shape;+ },+};diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.tsindex fe0eb0dce..e6ec73485 100644--- a/desktop/src/tools/tileTools.ts+++ b/desktop/src/tools/tileTools.ts@@ -20,6 +20,7 @@ import { SceneModel } from '@/engine/SceneModel';import { Toasts } from '@/store/Toasts';import { useSelection } from '@/store/selectionStore';import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';+import { TilePaintPreview } from './tilePreview';import type { EditorTool, PointerInput } from './EditorTool';// Cursor (client px) → tile grid coords on a TilemapLayer entity: client→world via@@ -55,6 +56,26 @@ function tiledCell(stamp: TileStamp, x: number, y: number): number {return stamp.cells[mod(y, stamp.h) * stamp.w + mod(x, stamp.w)];}+/** The tile coords a Bresenham line from (x0,y0) to (x1,y1) passes through (inclusive). */+export function lineCells(x0: number, y0: number, x1: number, y1: number): { x: number; y: number }[] {+ const cells: { x: number; y: number }[] = [];+ let x = x0;+ let y = y0;+ const dx = Math.abs(x1 - x0);+ const dy = -Math.abs(y1 - y0);+ const sx = x0 < x1 ? 1 : -1;+ const sy = y0 < y1 ? 1 : -1;+ let err = dx + dy;+ for (;;) {+ cells.push({ x, y });+ if (x === x1 && y === y1) break;+ const e2 = 2 * err;+ if (e2 >= dy) { err += dy; x += sx; }+ if (e2 <= dx) { err += dx; y += sy; }+ }+ return cells;+}+// ── 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.@@ -98,8 +119,10 @@ function makeStrokeTool<C>(spec: StrokeSpec<C>): EditorTool {},cancel() {if (!active) return;- // No mid-stroke tile rollback yet; commit what is painted (matches pointercancel).- spec.end(active.ctx);+ // Discard the live drag: restore the pre-stroke chunk blob, no model write / no+ // undo step. brush/erase/terrain all open the stroke via beginTilePaint, so one+ // shared cancel covers them (their per-stroke ctx is dropped with `active`).+ SceneCommands.cancelTilePaint();active = null;},};@@ -117,7 +140,14 @@ const brushTool = makeStrokeTool<number>({const eraseTool = makeStrokeTool<number>({id: 'tilemap.erase',begin: (selId) => { SceneCommands.beginTilePaint(selId); return selId; },- onCell: (selId, x, y) => SceneCommands.paintTileLive(selId, x, y, 0),+ // Erase the active brush's footprint (its w×h), so a multi-tile stamp erases a+ // block — the eraser size matches the brush the palette shows.+ onCell: (selId, x, y) => {+ const s = activeStamp();+ for (let dy = 0; dy < s.h; dy++) {+ for (let dx = 0; dx < s.w; dx++) SceneCommands.paintTileLive(selId, x + dx, y + dy, 0);+ }+ },end: () => SceneCommands.endTilePaint(),});@@ -183,15 +213,20 @@ function makeRectTool(): EditorTool {const tile = cursorTile(p.clientX, p.clientY, selId);if (!tile) return false;stroke = { sourceId: selId, startX: tile.x, startY: tile.y };+ TilePaintPreview.set({ kind: 'rect', x0: tile.x, y0: tile.y, x1: tile.x, y1: tile.y });ctx.capture(p.pointerId);return true;},- onPointerMove() {- // Rect previews on release (no live fill).+ onPointerMove(p) {+ if (!stroke) return;+ const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);+ if (!tile) return;+ TilePaintPreview.set({ kind: 'rect', x0: stroke.startX, y0: stroke.startY, x1: tile.x, y1: tile.y });},onPointerUp(p, ctx) {if (!stroke) return;ctx.release(p.pointerId);+ TilePaintPreview.clear();const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);if (tile) {const x0 = Math.min(stroke.startX, tile.x);@@ -211,7 +246,7 @@ function makeRectTool(): EditorTool {}stroke = null;},- cancel() { stroke = null; },+ cancel() { stroke = null; TilePaintPreview.clear(); },};}@@ -226,36 +261,32 @@ function makeLineTool(): EditorTool {const tile = cursorTile(p.clientX, p.clientY, selId);if (!tile) return false;stroke = { sourceId: selId, startX: tile.x, startY: tile.y };+ TilePaintPreview.set({ kind: 'line', cells: [{ x: tile.x, y: tile.y }] });ctx.capture(p.pointerId);return true;},- onPointerMove() {},+ onPointerMove(p) {+ if (!stroke) return;+ const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);+ if (!tile) return;+ TilePaintPreview.set({ kind: 'line', cells: lineCells(stroke.startX, stroke.startY, tile.x, tile.y) });+ },onPointerUp(p, ctx) {if (!stroke) return;ctx.release(p.pointerId);+ TilePaintPreview.clear();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; }+ for (const c of lineCells(stroke.startX, stroke.startY, tile.x, tile.y)) {+ for (const e of stampEdits(stamp, c.x, c.y)) edits.push(e);}if (edits.length > 0) SceneCommands.paintTiles(stroke.sourceId, edits);}stroke = null;},- cancel() { stroke = null; },+ cancel() { stroke = null; TilePaintPreview.clear(); },};}diff --git a/desktop/tests/tile-line.test.ts b/desktop/tests/tile-line.test.tsnew file mode 100644index 000000000..6bc3472b8--- /dev/null+++ b/desktop/tests/tile-line.test.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Bresenham tile-line enumeration — the line tool's committed tiles AND its+ * live drag preview both walk this, so a regression would desync what the+ * preview shows from what gets painted. Pins the endpoints, contiguity, and+ * direction symmetry.+ */+import { describe, it, expect } from 'vitest';+import { lineCells } from '@/tools/tileTools';++const key = (c: { x: number; y: number }) => `${c.x},${c.y}`;++describe('lineCells (Bresenham)', () => {+ it('a zero-length line is the single start cell', () => {+ expect(lineCells(3, 4, 3, 4)).toEqual([{ x: 3, y: 4 }]);+ });++ it('a horizontal line spans every column, inclusive', () => {+ expect(lineCells(0, 2, 3, 2)).toEqual([+ { x: 0, y: 2 }, { x: 1, y: 2 }, { x: 2, y: 2 }, { x: 3, y: 2 },+ ]);+ });++ it('a vertical line spans every row, inclusive', () => {+ expect(lineCells(5, 0, 5, 3)).toEqual([+ { x: 5, y: 0 }, { x: 5, y: 1 }, { x: 5, y: 2 }, { x: 5, y: 3 },+ ]);+ });++ it('a 45° diagonal steps one cell per axis', () => {+ expect(lineCells(0, 0, 3, 3)).toEqual([+ { x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 2 }, { x: 3, y: 3 },+ ]);+ });++ it('always includes both endpoints and stays 8-connected', () => {+ const cells = lineCells(0, 0, 6, 2); // shallow slope+ expect(cells[0]).toEqual({ x: 0, y: 0 });+ expect(cells.at(-1)).toEqual({ x: 6, y: 2 });+ for (let i = 1; i < cells.length; i++) {+ expect(Math.abs(cells[i].x - cells[i - 1].x)).toBeLessThanOrEqual(1);+ expect(Math.abs(cells[i].y - cells[i - 1].y)).toBeLessThanOrEqual(1);+ }+ });++ it('reversing the endpoints keeps the length and swaps the endpoints', () => {+ // Bresenham may pick different mid cells each way; both are valid rasterizations.+ // The preview and the commit both walk start→end, so they never disagree.+ const fwd = lineCells(1, 1, 5, 3);+ const rev = lineCells(5, 3, 1, 1);+ expect(rev.length).toBe(fwd.length);+ expect(rev[0]).toEqual({ x: 5, y: 3 });+ expect(rev.at(-1)).toEqual({ x: 1, y: 1 });+ });+});