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): random brush - scatter variation from the stamp

yhh8ea175096618
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index ae8b3f097..3c274ad6d 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -12,7 +12,7 @@
import { useEffect, useRef, useState } from 'react';
import {
Brush, Eraser, Square, Slash, PaintBucket, BoxSelect, Pipette,
- FlipHorizontal, FlipVertical, RotateCw, Mountain, Plus, X, MousePointer2,
+ FlipHorizontal, FlipVertical, RotateCw, Mountain, Plus, X, MousePointer2, Dices,
ZoomIn, ZoomOut, Maximize2, Eye, EyeOff, Lock, Unlock,
} from 'lucide-react';
import { parseTileset, encodeTile, type TilesetAsset, type TileStamp } from 'esengine';
@@ -104,7 +104,7 @@ export function TilemapPainter() {
const {
tilesetPath, tilesets, activeTileset, stamp, tool, terrainSet,
setTilesets, setActiveTileset, setTilesetAsset, setStamp, setTool, setTerrainSet,
- setActiveAtlas, flipH, flipV, rotateCW,
+ setActiveAtlas, flipH, flipV, rotateCW, randomBrush, toggleRandomBrush,
} = useTilemapPaint();
const selectedId = useSelection((s) => s.selectedId);
const hasTilemap = selectedId != null
@@ -398,6 +398,15 @@ export function TilemapPainter() {
<button type="button" className="tp-tool" title="Rotate 90° (R)" onClick={() => rotateCW()}>
<RotateCw size={15} />
</button>
+ <button
+ type="button"
+ className={'tp-tool' + (randomBrush ? ' is-active' : '')}
+ title="Random: each painted cell samples one tile from the selection"
+ aria-pressed={randomBrush}
+ onClick={() => toggleRandomBrush()}
+ >
+ <Dices size={15} />
+ </button>
<span className="tp-grow" />
<span className="tp-brush">
{tool === 'terrain' ? 'Terrain brush' : (
diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.ts
index 2c7d3e1e5..8cbeff5c2 100644
--- a/desktop/src/store/tilemapPaintStore.ts
+++ b/desktop/src/store/tilemapPaintStore.ts
@@ -66,6 +66,9 @@ interface TilemapPaintState {
clipboard: TileStamp | null;
/** The active tool; null = not painting (the Viewport selects normally). */
tool: PaintTool | null;
+ /** Random mode: each painted cell samples one tile from the stamp instead of
+ * laying the pattern — scatter variation from a multi-tile selection. */
+ randomBrush: boolean;
/** The active tileset's atlas layout (for the viewport brush ghost), or null. */
activeAtlas: AtlasInfo | null;
/** Replace the active layer's palette list (from its tilesetAssets); resets active to 0. */
@@ -85,6 +88,7 @@ interface TilemapPaintState {
flipV(): void;
rotateCW(): void;
setTool(tool: PaintTool | null): void;
+ toggleRandomBrush(): void;
}
export const useTilemapPaint = create<TilemapPaintState>((set) => ({
@@ -97,6 +101,7 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({
selection: null,
clipboard: null,
tool: null,
+ randomBrush: false,
activeAtlas: null,
setTilesets: (tilesets) => set({
tilesets,
@@ -120,4 +125,5 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({
flipV: () => set((s) => ({ stamp: flipStampV(s.stamp) })),
rotateCW: () => set((s) => ({ stamp: rotateStampCW(s.stamp) })),
setTool: (tool) => set({ tool }),
+ toggleRandomBrush: () => set((s) => ({ randomBrush: !s.randomBrush })),
}));
diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.ts
index 1f2b3ac75..d15da97cc 100644
--- a/desktop/src/tools/tileTools.ts
+++ b/desktop/src/tools/tileTools.ts
@@ -56,6 +56,31 @@ function tiledCell(stamp: TileStamp, x: number, y: number): number {
return stamp.cells[mod(y, stamp.h) * stamp.w + mod(x, stamp.w)];
}
+/** The stamp's non-empty cells — the random mode's sampling pool. */
+function stampPool(stamp: TileStamp): number[] {
+ return stamp.cells.filter((c) => tileIdOf(c) !== 0);
+}
+
+/** Point-tool edits at (x, y): the stamp footprint, or ONE sampled tile in random mode.
+ * Exported for tests (like lineCells). */
+export function brushEdits(stamp: TileStamp, x: number, y: number): TilePaint[] {
+ if (useTilemapPaint.getState().randomBrush) {
+ const pool = stampPool(stamp);
+ return pool.length ? [{ x, y, tileId: pool[(Math.random() * pool.length) | 0] }] : [];
+ }
+ return stampEdits(stamp, x, y);
+}
+
+/** Area-tool cell chooser: pattern-tiled normally, per-cell random sample in random mode.
+ * Exported for tests (like lineCells). */
+export function cellPicker(stamp: TileStamp): (x: number, y: number) => number {
+ if (useTilemapPaint.getState().randomBrush) {
+ const pool = stampPool(stamp);
+ return pool.length ? () => pool[(Math.random() * pool.length) | 0] : () => 0;
+ }
+ return (x, y) => tiledCell(stamp, x, y);
+}
+
/** 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 }[] = [];
@@ -135,7 +160,7 @@ 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);
+ for (const e of brushEdits(activeStamp(), x, y)) SceneCommands.paintTileLive(selId, e.x, e.y, e.tileId);
},
end: () => SceneCommands.endTilePaint(),
});
@@ -236,11 +261,11 @@ function makeRectTool(): EditorTool {
const x1 = Math.max(stroke.startX, tile.x);
const y0 = Math.min(stroke.startY, tile.y);
const y1 = Math.max(stroke.startY, tile.y);
- const stamp = activeStamp();
+ const pick = cellPicker(activeStamp());
const edits: TilePaint[] = [];
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
- const raw = tiledCell(stamp, x - x0, y - y0);
+ const raw = pick(x - x0, y - y0);
if (tileIdOf(raw) === 0) continue;
edits.push({ x, y, tileId: raw });
}
@@ -283,7 +308,7 @@ function makeLineTool(): EditorTool {
const stamp = activeStamp();
const edits: TilePaint[] = [];
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);
+ for (const e of brushEdits(stamp, c.x, c.y)) edits.push(e);
}
if (edits.length > 0) SceneCommands.paintTiles(stroke.sourceId, edits);
}
@@ -314,10 +339,11 @@ const bucketTool: EditorTool = {
const queue: [number, number][] = [[tile.x, tile.y]];
const edits: TilePaint[] = [];
let capped = false;
+ const pick = cellPicker(stamp);
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);
+ const raw = pick(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) {
diff --git a/desktop/tests/tile-random-brush.test.ts b/desktop/tests/tile-random-brush.test.ts
new file mode 100644
index 000000000..bc3a6a168
--- /dev/null
+++ b/desktop/tests/tile-random-brush.test.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tile-random-brush.test.ts
+ * @brief Random brush mode: point tools lay ONE tile sampled from the stamp's
+ * non-empty cells; area tools sample per cell. Off = the classic
+ * pattern behavior (footprint stamp / continuous tiling).
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { encodeTile, type TileStamp } from 'esengine';
+import { brushEdits, cellPicker } from '@/tools/tileTools';
+import { useTilemapPaint } from '@/store/tilemapPaintStore';
+
+const A = encodeTile(3);
+const B = encodeTile(7);
+// A 2×2 stamp with one EMPTY cell — random sampling must never lay a 0.
+const stamp: TileStamp = { w: 2, h: 2, cells: [A, B, 0, encodeTile(9)] };
+const pool = new Set([A, B, encodeTile(9)]);
+
+beforeEach(() => useTilemapPaint.setState({ randomBrush: false }));
+
+describe('random brush', () => {
+ it('off: brush lays the full stamp footprint at the anchor', () => {
+ const edits = brushEdits(stamp, 10, 20);
+ expect(edits).toHaveLength(3); // the empty cell stays sparse
+ expect(edits[0]).toEqual({ x: 10, y: 20, tileId: A });
+ });
+
+ it('on: brush lays exactly one sampled tile at the cursor cell', () => {
+ useTilemapPaint.setState({ randomBrush: true });
+ for (let i = 0; i < 32; i++) {
+ const edits = brushEdits(stamp, 5, 6);
+ expect(edits).toHaveLength(1);
+ expect(edits[0].x).toBe(5);
+ expect(edits[0].y).toBe(6);
+ expect(pool.has(edits[0].tileId)).toBe(true);
+ }
+ });
+
+ it('on: an all-empty stamp paints nothing instead of zeros', () => {
+ useTilemapPaint.setState({ randomBrush: true });
+ expect(brushEdits({ w: 1, h: 1, cells: [0] }, 0, 0)).toEqual([]);
+ });
+
+ it('off: area picker tiles the pattern continuously', () => {
+ const pick = cellPicker(stamp);
+ expect(pick(0, 0)).toBe(A);
+ expect(pick(2, 0)).toBe(A); // wraps at stamp width
+ expect(pick(1, 1)).toBe(encodeTile(9));
+ });
+
+ it('on: area picker samples the pool for every cell', () => {
+ useTilemapPaint.setState({ randomBrush: true });
+ const pick = cellPicker(stamp);
+ for (let i = 0; i < 32; i++) expect(pool.has(pick(i, i))).toBe(true);
+ });
+});