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): probability-weighted scatter, hollow shapes, infinite Tiled collision

esengine8bc742c7e6b4
diff --git a/desktop/src/i18n/messages/tile.ts b/desktop/src/i18n/messages/tile.ts
index 78ede34a2..2a0ac368b 100644
--- a/desktop/src/i18n/messages/tile.ts
+++ b/desktop/src/i18n/messages/tile.ts
@@ -7,13 +7,13 @@ import { defineMessages } from './types';
export const tileMessages = defineMessages({
// — Painter paint tools (button tooltips; the shortcut letter is appended in code) —
- 'tile.tool.brush': { en: 'Brush', zh: '笔刷' },
+ 'tile.tool.brush': { en: 'Brush (Alt eyedrops)', zh: '笔刷(Alt 取色)' },
'tile.tool.eraser': { en: 'Eraser', zh: '橡皮擦' },
- 'tile.tool.rect': { en: 'Rect', zh: '矩形' },
- 'tile.tool.ellipse': { en: 'Ellipse', zh: '椭圆' },
- 'tile.tool.line': { en: 'Line', zh: '直线' },
+ 'tile.tool.rect': { en: 'Rect (Shift square · Alt hollow)', zh: '矩形(Shift 正方 · Alt 空心)' },
+ 'tile.tool.ellipse': { en: 'Ellipse (Shift circle · Alt hollow)', zh: '椭圆(Shift 正圆 · Alt 空心)' },
+ 'tile.tool.line': { en: 'Line (Shift 45°)', zh: '直线(Shift 45°)' },
'tile.tool.bucket': { en: 'Bucket', zh: '填充' },
- 'tile.tool.select': { en: 'Select ({mod}C/X/V copy/cut/paste)', zh: '选择({mod}C/X/V 复制/剪切/粘贴)' },
+ 'tile.tool.select': { en: 'Select ({mod}C/X/V copy/cut/paste · drag inside to move)', zh: '选择({mod}C/X/V 复制/剪切/粘贴 · 选区内拖动=移动)' },
'tile.tool.eyedropper': { en: 'Eyedropper', zh: '取色器' },
'tile.tool.terrain': { en: 'Terrain', zh: '地形' },
'tile.tool.exit': { en: 'Select / transform (Q · Esc to exit painting)', zh: '选择 / 变换(Q · Esc 退出绘制)' },
@@ -21,8 +21,8 @@ export const tileMessages = defineMessages({
'tile.flipV': { en: 'Flip vertical (V)', zh: '垂直翻转(V)' },
'tile.rotate': { en: 'Rotate 90° (R)', zh: '旋转 90°(R)' },
'tile.randomTip': {
- en: 'Random: each painted cell samples one tile from the selection',
- zh: '随机:每个绘制的单元格从选区中随机取一块瓦片',
+ en: 'Random: each painted cell samples one tile from the selection (weighted by tile probability)',
+ zh: '随机:每个绘制的单元格从选区中随机取一块瓦片(按瓦片概率加权)',
},
'tile.terrainBrush': { en: 'Terrain brush', zh: '地形笔刷' },
@@ -105,6 +105,11 @@ export const tileMessages = defineMessages({
'tile.cell.circleTip': { en: 'Tile #{id} — drag paints fitted circle colliders (start on a circled tile to clear)', zh: '瓦片 #{id}——拖动铺设圆形碰撞(从已有圆形的瓦片起拖则清除)' },
'tile.cell.propTip': { en: 'Tile #{id} — click to edit its custom properties', zh: '瓦片 #{id}——点击编辑自定义属性' },
'tile.prop.pickHint': { en: 'Click a tile to edit its custom key/value properties.', zh: '点击一个瓦片以编辑它的自定义键值属性。' },
+ 'tile.prop.probability': { en: 'probability', zh: '概率' },
+ 'tile.prop.probabilityTip': {
+ en: 'Random-brush weight (default 1; 0 = never scattered)',
+ zh: '随机刷权重(默认 1;0 = 永不散布)',
+ },
'tile.prop.key': { en: 'key', zh: '键' },
'tile.prop.value': { en: 'value', zh: '值' },
'tile.prop.add': { en: 'Add property', zh: '添加属性' },
diff --git a/desktop/src/panels/TilesetEditor.tsx b/desktop/src/panels/TilesetEditor.tsx
index 39b77f951..c093dbf26 100644
--- a/desktop/src/panels/TilesetEditor.tsx
+++ b/desktop/src/panels/TilesetEditor.tsx
@@ -584,6 +584,20 @@ export function TilesetEditor() {
<span className="ts-fthumb" style={thumb(propTile)} title={`#${propTile}`} />
<span className="ts-astat">#{propTile}</span>
<span className="ts-sep" />
+ <label className="ts-modnum" title={t('tile.prop.probabilityTip')}>
+ <span>{t('tile.prop.probability')}</span>
+ <input
+ key={`${propTile}-p-${asset.tiles[propTile]?.probability ?? 1}`}
+ type="text" inputMode="decimal" spellCheck={false}
+ defaultValue={String(asset.tiles[propTile]?.probability ?? 1)}
+ onBlur={(e) => {
+ const n = parseFloat(e.target.value);
+ TilesetCommands.setTileProbability(propTile, Number.isFinite(n) ? n : 1);
+ }}
+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
+ />
+ </label>
+ <span className="ts-sep" />
{Object.entries(asset.tiles[propTile]?.properties ?? {}).map(([k, v]) => (
<span key={k} className="ts-prop">
<span className="ts-prop-key" title={k}>{k}</span>
diff --git a/desktop/src/tileset/TilesetCommands.ts b/desktop/src/tileset/TilesetCommands.ts
index 8b1f226e4..2e14cd7f4 100644
--- a/desktop/src/tileset/TilesetCommands.ts
+++ b/desktop/src/tileset/TilesetCommands.ts
@@ -39,7 +39,8 @@ function withMods<T extends object>(shape: T, mods?: TileCollisionMods): T & Til
/** Drop a tile entry that no longer carries any metadata, keeping the map sparse. */
function pruneEmpty(asset: TilesetAsset, id: number): void {
const t = asset.tiles[id];
- if (t && !t.collision && !t.properties && !t.animation && !t.terrain) delete asset.tiles[id];
+ if (t && !t.collision && !t.properties && !t.animation && !t.terrain
+ && t.probability === undefined) delete asset.tiles[id];
}
export const TilesetCommands = {
@@ -130,6 +131,19 @@ export const TilesetCommands = {
});
},
+ /** Set a tile's random-brush weight as ONE undo step; 1 (the default) clears it. */
+ setTileProbability(id: number, p: number): void {
+ if (id <= 0) return;
+ TilesetDocument.edit('Edit Tile Probability', (a) => {
+ if (Number.isFinite(p) && p >= 0 && p !== 1) {
+ a.tiles[id] = { ...(a.tiles[id] ?? {}), probability: p };
+ } else if (a.tiles[id]?.probability !== undefined) {
+ delete a.tiles[id].probability;
+ pruneEmpty(a, id);
+ }
+ });
+ },
+
/** Replace a tile's custom properties as ONE undo step; an empty record clears them. */
setTileProperties(id: number, props: Record<string, string>): void {
if (id <= 0) return;
diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.ts
index 6038ec4d4..c2a8b3ebc 100644
--- a/desktop/src/tools/tileTools.ts
+++ b/desktop/src/tools/tileTools.ts
@@ -62,12 +62,41 @@ function stampPool(stamp: TileStamp): number[] {
return stamp.cells.filter((c) => tileIdOf(c) !== 0);
}
+/** A gid's random-brush weight from its owning palette tileset (tile `probability`). */
+function tileWeight(gid: number): number {
+ const ts = useTilemapPaint.getState().tilesets;
+ for (let i = ts.length - 1; i >= 0; i--) {
+ if (ts[i].firstId <= gid) {
+ const p = ts[i].asset.tiles[gid - ts[i].firstId + 1]?.probability;
+ return typeof p === 'number' && p >= 0 ? p : 1;
+ }
+ }
+ return 1;
+}
+
+/** Weighted sampler over the pool (per-tile `probability`; all-zero falls back to uniform).
+ * Exported for tests (like lineCells). */
+export function weightedSampler(pool: number[], weightOf: (gid: number) => number = tileWeight): () => number {
+ const weights = pool.map((c) => weightOf(tileIdOf(c)));
+ const total = weights.reduce((a, b) => a + b, 0);
+ if (total <= 0) return () => pool[(Math.random() * pool.length) | 0];
+ return () => {
+ let r = Math.random() * total;
+ for (let i = 0; i < pool.length; i++) {
+ r -= weights[i];
+ if (r <= 0) return pool[i];
+ }
+ return pool[pool.length - 1];
+ };
+}
+
/** 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] }] : [];
+ if (!pool.length) return [];
+ return [{ x, y, tileId: weightedSampler(pool)() }];
}
return stampEdits(stamp, x, y);
}
@@ -77,7 +106,7 @@ export function brushEdits(stamp: TileStamp, x: number, y: number): TilePaint[]
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 pool.length ? weightedSampler(pool) : () => 0;
}
return (x, y) => tiledCell(stamp, x, y);
}
@@ -109,6 +138,22 @@ export function ellipseCells(x0: number, y0: number, x1: number, y1: number): {
return cells;
}
+/**
+ * The ellipse OUTLINE: the inscribed ellipse's cells minus the ellipse one cell
+ * smaller on every side (Alt-hollow mode). Degenerate boxes (≤2 wide/tall) have
+ * no interior, so the ring is the full set. Exported for tests (like lineCells).
+ */
+export function ellipseRing(x0: number, y0: number, x1: number, y1: number): { x: number; y: number }[] {
+ const full = ellipseCells(x0, y0, x1, y1);
+ const minX = Math.min(x0, x1);
+ const maxX = Math.max(x0, x1);
+ const minY = Math.min(y0, y1);
+ const maxY = Math.max(y0, y1);
+ if (maxX - minX < 2 || maxY - minY < 2) return full;
+ const inner = new Set(ellipseCells(minX + 1, minY + 1, maxX - 1, maxY - 1).map((c) => `${c.x},${c.y}`));
+ return full.filter((c) => !inner.has(`${c.x},${c.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 }[] = [];
@@ -353,6 +398,8 @@ function makeRectTool(): EditorTool {
const edits: TilePaint[] = [];
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
+ // Alt = hollow: keep the perimeter, skip the interior.
+ if (p.alt && x !== x0 && x !== x1 && y !== y0 && y !== y1) continue;
const raw = pick(x - x0, y - y0);
if (tileIdOf(raw) === 0) continue;
edits.push({ x, y, tileId: raw });
@@ -434,7 +481,8 @@ function makeEllipseTool(): EditorTool {
let tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
if (!tile) return;
if (p.shift) tile = squareSnap(stroke.startX, stroke.startY, tile.x, tile.y);
- TilePaintPreview.set({ kind: 'line', cells: ellipseCells(stroke.startX, stroke.startY, tile.x, tile.y) });
+ const cells = (p.alt ? ellipseRing : ellipseCells)(stroke.startX, stroke.startY, tile.x, tile.y);
+ TilePaintPreview.set({ kind: 'line', cells });
},
onPointerUp(p, ctx) {
if (!stroke) return;
@@ -446,8 +494,10 @@ function makeEllipseTool(): EditorTool {
const minX = Math.min(stroke.startX, tile.x);
const minY = Math.min(stroke.startY, tile.y);
const pick = cellPicker(activeStamp());
+ let cells = ellipseCells(stroke.startX, stroke.startY, tile.x, tile.y);
+ if (p.alt) cells = ellipseRing(stroke.startX, stroke.startY, tile.x, tile.y);
const edits: TilePaint[] = [];
- for (const c of ellipseCells(stroke.startX, stroke.startY, tile.x, tile.y)) {
+ for (const c of cells) {
const raw = pick(c.x - minX, c.y - minY);
if (tileIdOf(raw) === 0) continue;
edits.push({ x: c.x, y: c.y, tileId: raw });
diff --git a/desktop/tests/tile-constraints.test.ts b/desktop/tests/tile-constraints.test.ts
index fcc13db4c..8e5e9c2d7 100644
--- a/desktop/tests/tile-constraints.test.ts
+++ b/desktop/tests/tile-constraints.test.ts
@@ -22,3 +22,33 @@ describe('squareSnap (Shift-constrained rect/ellipse)', () => {
expect(squareSnap(10, 10, 6, 12)).toEqual({ x: 6, y: 14 });
});
});
+
+import { ellipseRing, weightedSampler } from '@/tools/tileTools';
+import { encodeTile } from 'esengine';
+
+describe('ellipseRing (Alt-hollow ellipse)', () => {
+ it('keeps only the outline for boxes with an interior', () => {
+ const ring = ellipseRing(0, 0, 4, 4);
+ const keys = new Set(ring.map((c) => `${c.x},${c.y}`));
+ expect(keys.has('2,2')).toBe(false); // centre carved out
+ expect(keys.has('2,0')).toBe(true); // top of the ring survives
+ expect(keys.has('0,2')).toBe(true);
+ });
+ it('degenerates to the full set when there is no interior', () => {
+ expect(ellipseRing(0, 0, 1, 1).length).toBe(4);
+ });
+});
+
+describe('weightedSampler (tile probability)', () => {
+ const pool = [encodeTile(1), encodeTile(2)];
+ it('never picks a zero-weight tile when another has weight', () => {
+ const pick = weightedSampler(pool, (gid) => (gid === 1 ? 0 : 1));
+ for (let i = 0; i < 50; i++) expect(pick()).toBe(pool[1]);
+ });
+ it('falls back to uniform when every weight is zero', () => {
+ const pick = weightedSampler(pool, () => 0);
+ const seen = new Set<number>();
+ for (let i = 0; i < 200; i++) seen.add(pick());
+ expect(seen.size).toBe(2);
+ });
+});
diff --git a/desktop/tests/tileset-commands.test.ts b/desktop/tests/tileset-commands.test.ts
index 5b15bcffb..ec75fbbe2 100644
--- a/desktop/tests/tileset-commands.test.ts
+++ b/desktop/tests/tileset-commands.test.ts
@@ -112,3 +112,19 @@ describe('TilesetCommands — stamps + properties', () => {
expect(tiles()[7].properties).toEqual({ kind: 'spike' });
});
});
+
+describe('TilesetCommands — probability', () => {
+ beforeEach(() => {
+ EditorHistory.clear();
+ TilesetDocument.open(freshTileset(), 'a.estileset');
+ });
+
+ it('sets a weight, clears at the default 1, and undoes', () => {
+ TilesetCommands.setTileProbability(3, 0.2);
+ expect(tiles()[3].probability).toBe(0.2);
+ TilesetCommands.setTileProbability(3, 1);
+ expect(tiles()[3]).toBeUndefined(); // pruned back to sparse
+ EditorHistory.undo();
+ expect(tiles()[3].probability).toBe(0.2);
+ });
+});
diff --git a/docs/astro/src/content/docs/guides/tilemap.mdx b/docs/astro/src/content/docs/guides/tilemap.mdx
index b2b2e514c..a6f2e3dd6 100644
--- a/docs/astro/src/content/docs/guides/tilemap.mdx
+++ b/docs/astro/src/content/docs/guides/tilemap.mdx
@@ -30,13 +30,13 @@ viewport — a stamp ghost previews every stroke:
| Tool | Key | What it does |
|---|---|---|
-| Brush | `B` | Paint the current stamp; drag for strokes. |
+| Brush | `B` | Paint the current stamp; drag for strokes. `Alt`+click eyedrops. |
| Erase | `E` | Clear tiles. |
-| Rectangle | `U` | Fill a dragged rectangle with the stamp pattern. |
-| Ellipse | `O` | Drag a bounding box, fill its inscribed ellipse. |
-| Line | `L` | Lay the stamp along a straight line. |
+| Rectangle | `U` | Fill a dragged rectangle with the stamp pattern. `Shift` squares it, `Alt` paints the outline only. |
+| Ellipse | `O` | Drag a bounding box, fill its inscribed ellipse. `Shift` makes a circle, `Alt` a ring. |
+| Line | `L` | Lay the stamp along a straight line. `Shift` constrains to horizontal / vertical / 45°. |
| Bucket | `G` | Flood-fill the connected region of matching tiles. |
-| Select | `M` | Marquee a region — `mod + C` / `X` copy / cut it, `Delete` clears it, `mod + V` pastes it as the brush. |
+| Select | `M` | Marquee a region — `mod + C` / `X` copy / cut it, `Delete` clears it, `mod + V` pastes it as the brush; **drag from inside the marquee to move the block** (one undo step, `Esc` cancels). |
| Eyedropper | `I` | Pick the stamp from tiles already on the layer. |
| Terrain | `T` | Autotile brush — paints a terrain and fixes up the neighbors. |
@@ -51,7 +51,8 @@ While a paint tool is active, `H` / `V` flip the stamp and `R` rotates it 90°.
deletes it. Identical patterns deduplicate.
- **Random mode** — toggle the dice button and each painted cell samples one tile
at random from the stamp instead of repeating the pattern — quick scatter for
- grass, rubble, and other variation.
+ grass, rubble, and other variation. Sampling honors each tile's **probability**
+ weight from the tileset editor's Properties mode (default 1; 0 = never scattered).
- **Layer strip** — when the scene has several tilemap layers, a strip at the top
of the panel switches the active layer and toggles per-layer visibility and lock.
diff --git a/docs/astro/src/content/docs/zh-cn/guides/tilemap.mdx b/docs/astro/src/content/docs/zh-cn/guides/tilemap.mdx
index 71126c00a..bab021cbe 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/tilemap.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/tilemap.mdx
@@ -25,13 +25,13 @@ Estella 在 C++/WebAssembly 内核里渲染瓦片图层,按图集纹理合批并
| 工具 | 键 | 作用 |
|---|---|---|
-| 画笔 | `B` | 绘制当前印章;拖动连续作画。 |
+| 画笔 | `B` | 绘制当前印章;拖动连续作画。`Alt`+点击临时取色。 |
| 橡皮 | `E` | 清除瓦片。 |
-| 矩形 | `U` | 用印章图案填充拖出的矩形。 |
-| 椭圆 | `O` | 拖出包围盒,填充其内切椭圆。 |
-| 直线 | `L` | 沿直线铺设印章。 |
+| 矩形 | `U` | 用印章图案填充拖出的矩形。`Shift` 锁正方,`Alt` 只画边框。 |
+| 椭圆 | `O` | 拖出包围盒,填充其内切椭圆。`Shift` 锁正圆,`Alt` 只画圆环。 |
+| 直线 | `L` | 沿直线铺设印章。`Shift` 约束到水平 / 垂直 / 45°。 |
| 油漆桶 | `G` | 泛洪填充相连的同类瓦片区域。 |
-| 框选 | `M` | 框选一块区域——`mod + C` / `X` 复制 / 剪切,`Delete` 清空,`mod + V` 作为画笔粘贴。 |
+| 框选 | `M` | 框选一块区域——`mod + C` / `X` 复制 / 剪切,`Delete` 清空,`mod + V` 作为画笔粘贴;**从选区内部拖动可整块移动**(单一 undo 步,`Esc` 取消)。 |
| 吸管 | `I` | 从图层上已有的瓦片取印章。 |
| 地形 | `T` | 自动拼接画笔——绘制地形并自动修正邻居。 |
@@ -43,7 +43,8 @@ Estella 在 C++/WebAssembly 内核里渲染瓦片图层,按图集纹理合批并
- **图章库** —— 工具行下方的书签按钮把当前画笔存进按项目持久化的图章库;点击章片
即可换回该图案,`×` 删除。相同图案自动去重。
- **随机模式** —— 打开骰子按钮,每个落笔格从印章里随机取一个瓦片,而不是重复图案——
- 给草地、碎石等做变化最快的方式。
+ 给草地、碎石等做变化最快的方式。采样按图集编辑器属性模式里每个瓦片的 **概率** 权重
+ 加权(默认 1;0 = 永不散布)。
- **图层条** —— 场景里有多个瓦片图层时,面板顶部的图层条切换活动图层,并可逐层切换
可见性与锁定。
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 3ce2e218f..89d7c951c 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6461,6 +6461,7 @@ name: string
```
animation: TilesetAnimFrame[] | undefined
collision: TilesetCollision | undefined
+probability: number | undefined
properties: Record<string, string> | undefined
terrain: TilesetTileTerrain | undefined
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index a19ca5b77..84ca79591 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6456,6 +6456,7 @@ name: string
```
animation: TilesetAnimFrame[] | undefined
collision: TilesetCollision | undefined
+probability: number | undefined
properties: Record<string, string> | undefined
terrain: TilesetTileTerrain | undefined
```
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
index 905d14005..0925ca102 100644
--- a/sdk/src/tilemap/tiledLoader.ts
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -1191,19 +1191,25 @@ export function loadTiledMap(
if (tileCollisionIds.size > 0) {
for (const layer of mapData.layers) {
if (!layer.visible) continue;
- const tileEntities = generateTileCollision(
- world, layer, mapData, tileCollisionIds, 0, 0,
- );
- entities.push(...tileEntities);
+ // Infinite layers are re-chunked to CHUNK_SIZE at parse — same generators
+ // as the painted path.
+ entities.push(...(layer.infinite
+ ? generateChunkCollision(
+ world, layer.chunks, tileCollisionIds,
+ mapData.tileWidth, mapData.tileHeight, 0, 0)
+ : generateTileCollision(world, layer, mapData, tileCollisionIds, 0, 0)));
}
}
if (mapData.tileShapes && mapData.tileShapes.size > 0) {
for (const layer of mapData.layers) {
if (!layer.visible) continue;
- entities.push(...generateLayerTileShapes(
- world, layer.tiles, layer.width, layer.height, mapData.tileShapes,
- mapData.tileWidth, mapData.tileHeight, 0, 0,
- ));
+ entities.push(...(layer.infinite
+ ? generateChunkTileShapes(
+ world, layer.chunks, mapData.tileShapes,
+ mapData.tileWidth, mapData.tileHeight, 0, 0)
+ : generateLayerTileShapes(
+ world, layer.tiles, layer.width, layer.height, mapData.tileShapes,
+ mapData.tileWidth, mapData.tileHeight, 0, 0)));
}
}
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index a01f52659..81e248dce 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -517,9 +517,26 @@ export class TilemapPlugin implements Plugin {
if (hasTileCollision || hasTileShapes) {
const ids = new Set(cached.collisionTileIds);
for (const layer of cached.layers) {
- // Collision covers finite layers (flat tile arrays);
- // infinite/chunk collision is deferred.
- if (layer.infinite || layer.tiles.length === 0) continue;
+ if (layer.infinite) {
+ // Infinite Tiled layers are re-chunked to CHUNK_SIZE at
+ // parse, so they ride the SAME chunk generators the
+ // painted path uses.
+ if (layer.chunks.length === 0) continue;
+ if (hasTileCollision) {
+ spawned.push(...generateChunkCollision(
+ world, layer.chunks, ids,
+ cached.tileWidth, cached.tileHeight, ox, oy, pixelsPerUnit,
+ ));
+ }
+ if (hasTileShapes) {
+ spawned.push(...generateChunkTileShapes(
+ world, layer.chunks, cached.tileShapes!,
+ cached.tileWidth, cached.tileHeight, ox, oy, pixelsPerUnit,
+ ));
+ }
+ continue;
+ }
+ if (layer.tiles.length === 0) continue;
if (hasTileCollision) {
spawned.push(...generateLayerCollision(
world, layer.tiles, layer.width, layer.height,
diff --git a/sdk/src/tilemap/tilesetAsset.ts b/sdk/src/tilemap/tilesetAsset.ts
index aab7132c2..0d1e8e076 100644
--- a/sdk/src/tilemap/tilesetAsset.ts
+++ b/sdk/src/tilemap/tilesetAsset.ts
@@ -79,6 +79,8 @@ export interface TilesetTile {
properties?: Record<string, string>;
animation?: TilesetAnimFrame[];
terrain?: TilesetTileTerrain;
+ /** Random-brush weight (Tiled's tile probability). Default 1; 0 = never scattered. */
+ probability?: number;
}
/** A reusable tileset palette asset (`.estileset`). */
@@ -182,7 +184,12 @@ export function parseTileset(raw: any): TilesetAsset {
&& Number.isInteger(t.terrain.mask) && t.terrain.mask >= 0) {
tile.terrain = { set: t.terrain.set, mask: t.terrain.mask };
}
- if (tile.collision || tile.properties || tile.animation || tile.terrain) tiles[id] = tile;
+ if (typeof t.probability === 'number' && Number.isFinite(t.probability)
+ && t.probability >= 0 && t.probability !== 1) {
+ tile.probability = t.probability;
+ }
+ if (tile.collision || tile.properties || tile.animation || tile.terrain
+ || tile.probability !== undefined) tiles[id] = tile;
}
const terrains: TilesetTerrain[] = Array.isArray(raw?.terrains)
? raw.terrains
diff --git a/sdk/tests/tileset-asset.test.ts b/sdk/tests/tileset-asset.test.ts
index bb17ba469..e117f1f84 100644
--- a/sdk/tests/tileset-asset.test.ts
+++ b/sdk/tests/tileset-asset.test.ts
@@ -107,3 +107,23 @@ describe('tilesetAsset (.estileset format)', () => {
});
});
});
+
+describe('tile probability', () => {
+ it('parses, round-trips, and drops the default weight of 1', () => {
+ const asset = parseTileset({
+ texture: '@uuid:x', tileWidth: 16, tileHeight: 16, columns: 4,
+ tiles: {
+ 2: { probability: 0.25 },
+ 3: { probability: 1 }, // default → dropped
+ 4: { probability: 0 }, // "never scattered" is meaningful
+ },
+ });
+ expect(asset.tiles[2]).toEqual({ probability: 0.25 });
+ expect(asset.tiles[3]).toBeUndefined();
+ expect(asset.tiles[4]).toEqual({ probability: 0 });
+
+ const round = parseTileset(serializeTileset(asset));
+ expect(round.tiles[2]).toEqual({ probability: 0.25 });
+ expect(round.tiles[4]).toEqual({ probability: 0 });
+ });
+});