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): one collision model for both asset paths + runtime queries + floating selection

esengine0c0f3da9686b
diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.ts
index ed8e247f6..6038ec4d4 100644
--- a/desktop/src/tools/tileTools.ts
+++ b/desktop/src/tools/tileTools.ts
@@ -506,10 +506,36 @@ const bucketTool: EditorTool = {
onPointerUp() {},
};
-/** Select: drag a marquee over the layer to define a tile-rect selection (copy/cut/paste). */
+/**
+ * Select: drag a marquee over the layer to define a tile-rect selection
+ * (copy/cut/paste), and drag from INSIDE the selection to MOVE its tiles — a
+ * floating cut that erases live, previews the target rect while dragging, and
+ * lands as ONE undo step on release (Esc restores the pre-drag tiles).
+ */
function makeSelectTool(): EditorTool {
let anchor: { x: number; y: number } | null = null;
let sourceId: number | null = null;
+ let move: {
+ sourceId: number;
+ /** Region content lifted at grab time (raw cells incl. flip flags). */
+ buf: number[];
+ x0: number; y0: number; w: number; h: number;
+ /** Grab point offset within the region, so it drags from where you grabbed it. */
+ dx: number; dy: number;
+ /** Target top-left (updates while dragging). */
+ tx: number; ty: number;
+ } | null = null;
+
+ const inSelection = (t: { x: number; y: number }): { x0: number; y0: number; x1: number; y1: number } | null => {
+ const sel = useTilemapPaint.getState().selection;
+ if (!sel) return null;
+ const x0 = Math.min(sel.x0, sel.x1);
+ const x1 = Math.max(sel.x0, sel.x1);
+ const y0 = Math.min(sel.y0, sel.y1);
+ const y1 = Math.max(sel.y0, sel.y1);
+ return t.x >= x0 && t.x <= x1 && t.y >= y0 && t.y <= y1 ? { x0, y0, x1, y1 } : null;
+ };
+
return {
id: 'tilemap.select',
onPointerDown(p, ctx) {
@@ -517,6 +543,29 @@ function makeSelectTool(): EditorTool {
if (selId == null) return false;
const tile = cursorTile(p.clientX, p.clientY, selId);
if (!tile) return false;
+ const rt = SceneModel.runtimeFor(selId);
+ const region = inSelection(tile);
+ if (region && rt != null) {
+ // Grab the region: lift its cells, erase them live, drag the block.
+ const w = region.x1 - region.x0 + 1;
+ const h = region.y1 - region.y0 + 1;
+ const buf: number[] = [];
+ for (let y = region.y0; y <= region.y1; y++) {
+ for (let x = region.x0; x <= region.x1; x++) buf.push(TilemapAPI.getTile(rt, x, y));
+ }
+ SceneCommands.beginTilePaint(selId);
+ for (let y = region.y0; y <= region.y1; y++) {
+ for (let x = region.x0; x <= region.x1; x++) SceneCommands.paintTileLive(selId, x, y, 0);
+ }
+ move = {
+ sourceId: selId, buf, x0: region.x0, y0: region.y0, w, h,
+ dx: tile.x - region.x0, dy: tile.y - region.y0,
+ tx: region.x0, ty: region.y0,
+ };
+ TilePaintPreview.set({ kind: 'rect', x0: region.x0, y0: region.y0, x1: region.x1, y1: region.y1 });
+ ctx.capture(p.pointerId);
+ return true;
+ }
anchor = tile;
sourceId = selId;
useTilemapPaint.getState().setSelection({ x0: tile.x, y0: tile.y, x1: tile.x, y1: tile.y });
@@ -524,6 +573,17 @@ function makeSelectTool(): EditorTool {
return true;
},
onPointerMove(p) {
+ if (move) {
+ const tile = cursorTile(p.clientX, p.clientY, move.sourceId);
+ if (!tile) return;
+ move.tx = tile.x - move.dx;
+ move.ty = tile.y - move.dy;
+ TilePaintPreview.set({
+ kind: 'rect',
+ x0: move.tx, y0: move.ty, x1: move.tx + move.w - 1, y1: move.ty + move.h - 1,
+ });
+ return;
+ }
if (!anchor || sourceId == null) return;
const tile = cursorTile(p.clientX, p.clientY, sourceId);
if (!tile) return;
@@ -531,10 +591,32 @@ function makeSelectTool(): EditorTool {
},
onPointerUp(p, ctx) {
ctx.release(p.pointerId);
+ if (move) {
+ TilePaintPreview.clear();
+ // Land the lifted block at the target: erase + place is ONE stroke commit.
+ for (let dy = 0; dy < move.h; dy++) {
+ for (let dx = 0; dx < move.w; dx++) {
+ const raw = move.buf[dy * move.w + dx];
+ if (tileIdOf(raw) === 0) continue; // sparse — moved emptiness never erases the target
+ SceneCommands.paintTileLive(move.sourceId, move.tx + dx, move.ty + dy, raw);
+ }
+ }
+ SceneCommands.endTilePaint();
+ useTilemapPaint.getState().setSelection({
+ x0: move.tx, y0: move.ty, x1: move.tx + move.w - 1, y1: move.ty + move.h - 1,
+ });
+ move = null;
+ return;
+ }
anchor = null;
sourceId = null;
},
cancel() {
+ if (move) {
+ SceneCommands.cancelTilePaint(); // restore the lifted tiles, no undo entry
+ TilePaintPreview.clear();
+ move = null;
+ }
anchor = null;
sourceId = null;
},
diff --git a/docs/astro/src/content/docs/guides/tilemap.mdx b/docs/astro/src/content/docs/guides/tilemap.mdx
index 7ecfa01b9..b2b2e514c 100644
--- a/docs/astro/src/content/docs/guides/tilemap.mdx
+++ b/docs/astro/src/content/docs/guides/tilemap.mdx
@@ -187,6 +187,13 @@ reorienting the geometry to match the rendering. The scene viewport draws the
selected layer's whole collision as an overlay (Show Flags → tile collision) —
WYSIWYG with what Play spawns.
+Tiled maps get the same treatment: shapes drawn in **Tiled's tile collision
+editor** (rectangles, ellipses, polygons) import into the identical model — a
+full-cell rectangle stays a merge-eligible solid box, everything else spawns
+one collider per tile — and the tile properties `oneway` / `sensor` /
+`friction` / `restitution` / `density` apply the same modifiers. The legacy
+`collision=true` tile property still marks a plain solid box.
+
<Aside type="note">
Tile **collision is play-mode only**: static colliders are spawned from the
`.estileset`'s per-tile collision when the scene runs — they are never in the
@@ -245,6 +252,12 @@ origin / pixels-per-unit / play-mode lifecycle as tile collision.
| `setGridType(layer, type)` / `setHexParams(...)` | Orientation (orthogonal / isometric / hex). |
| `destroyLayer(layer)` | Tear a layer down. |
+Tile **collision queries** run against the resolved collision data (no physics
+raycast needed): `tileCollisionAt(layer, x, y)` returns the tile's resolved
+shape + modifiers (or null), `isTileSolid(layer, x, y)` is true for any
+non-sensor collision (one-way platforms count — check `.oneWay` to treat them
+specially), and `tileCollisionAtWorld(...)` addresses in world pixels.
+
## Best practices
- **Paint hand-authored levels in the editor** (or import from Tiled with
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 a2a4a2279..71126c00a 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/tilemap.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/tilemap.mdx
@@ -168,6 +168,11 @@ tilemap.setChunkTiles(layer, chunkX, chunkY, tiles, 32, 32);
生成一个碰撞体,并按瓦片翻转标志重定向几何、与渲染严格一致。场景视口会把所选图层的完整
碰撞画成覆盖层(显示标志 → 瓦片碰撞)——与 Play 生成的完全一致。
+Tiled 地图享受同等待遇:在 **Tiled 瓦片碰撞编辑器** 里画的形状(矩形、椭圆、多边形)
+导入到同一模型——整格矩形保持可合并的实心方块,其余每瓦片各生成一个碰撞体;瓦片属性
+`oneway` / `sensor` / `friction` / `restitution` / `density` 应用相同修饰符。旧的
+`collision=true` 瓦片属性仍标记普通实心方块。
+
<Aside type="note">
瓦片**碰撞仅在播放模式**存在:静态碰撞体在场景运行时从 `.estileset` 的逐瓦片碰撞
生成——它们从不在编辑世界里,也不被序列化。
@@ -222,6 +227,10 @@ origin / 每单位像素 / 播放模式生命周期。
| `setGridType(layer, type)` / `setHexParams(...)` | 朝向(正交 / 等距 / 六边形)。 |
| `destroyLayer(layer)` | 销毁图层。 |
+瓦片**碰撞查询**直接查已解析的碰撞数据(无需物理射线):`tileCollisionAt(layer, x, y)`
+返回该瓦片解析后的形状+修饰符(或 null);`isTileSolid(layer, x, y)` 对任何非传感器碰撞
+为 true(单向平台也算——用 `.oneWay` 特殊处理);`tileCollisionAtWorld(...)` 以世界像素寻址。
+
## 最佳实践
- 手工关卡**在编辑器里绘制**(或用 `Tilemap` + `.tmj` 从 Tiled 导入);程序化或运行时
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 387c341e7..3ce2e218f 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -3383,6 +3383,7 @@ staggerIndex: string | undefined
tileAnimations: Map<number, { tileId: number; duration: number; }[]> | undefined
tileHeight: number
tileProperties: Map<number, Map<string, string>> | undefined
+tileShapes: Map<number, ResolvedTileCollision> | undefined
tileWidth: number
tilesets: LoadedTilemapTileset[]
```
@@ -6335,6 +6336,7 @@ staggerIndex: string
tileAnimations: Map<number, TiledAnimFrame[]>
tileHeight: number
tileProperties: Map<number, Map<string, string>>
+tileShapes: Map<number, ResolvedTileCollision>
tileWidth: number
tilesets: TiledTilesetData[]
width: number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index cef77ba55..a19ca5b77 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -3378,6 +3378,7 @@ staggerIndex: string | undefined
tileAnimations: Map<number, { tileId: number; duration: number; }[]> | undefined
tileHeight: number
tileProperties: Map<number, Map<string, string>> | undefined
+tileShapes: Map<number, ResolvedTileCollision> | undefined
tileWidth: number
tilesets: LoadedTilemapTileset[]
```
@@ -6330,6 +6331,7 @@ staggerIndex: string
tileAnimations: Map<number, TiledAnimFrame[]>
tileHeight: number
tileProperties: Map<number, Map<string, string>>
+tileShapes: Map<number, ResolvedTileCollision>
tileWidth: number
tilesets: TiledTilesetData[]
width: number
diff --git a/sdk/src/asset/loaders/TilemapAssetLoader.ts b/sdk/src/asset/loaders/TilemapAssetLoader.ts
index 567d38d63..6daf54ccb 100644
--- a/sdk/src/asset/loaders/TilemapAssetLoader.ts
+++ b/sdk/src/asset/loaders/TilemapAssetLoader.ts
@@ -80,6 +80,7 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {
})),
tilesets,
collisionTileIds: mapData.collisionTileIds,
+ tileShapes: mapData.tileShapes,
tileAnimations: mapData.tileAnimations,
tileProperties: mapData.tileProperties,
objectGroups: mapData.objectGroups,
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index 899799b25..9fac83d85 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -7,7 +7,8 @@ export { TilemapPlugin, tilemapPlugin } from './tilemapPlugin';
export {
parseTmjJson, parseTmjWithExternals, loadTiledMap, loadTiledCollisionObjects,
generateTileCollision, generateLayerCollision, generateChunkCollision,
- generateChunkPolygonCollision, generateChunkTileShapes, generateObjectCollision, isCollisionObjectGroup,
+ generateChunkPolygonCollision, generateChunkTileShapes, generateLayerTileShapes,
+ tiledObjectgroupShape, tiledCollisionMods, generateObjectCollision, isCollisionObjectGroup,
polygonLocalVerts, tileColliderShape, oneWayNormalWorld, resolveRelativePath, packCollectionGrid,
type TiledMapData, type TiledLayerData, type TiledTilesetData,
type TiledCollectionTile, type CollectionGridTile,
@@ -45,3 +46,8 @@ export {
type LoadedTilemapSource, type LoadedTilemapLayer, type LoadedTilemapTileset,
} from './tilesetCache';
export { getTextureDimensions, type TextureDimensions } from '../resourceManager';
+
+export {
+ tileCollisionAt, isTileSolid, tileCollisionAtWorld,
+ type LayerCollisionTable,
+} from './tileQuery';
diff --git a/sdk/src/tilemap/tileQuery.ts b/sdk/src/tilemap/tileQuery.ts
new file mode 100644
index 000000000..2ee841935
--- /dev/null
+++ b/sdk/src/tilemap/tileQuery.ts
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tilemap/tileQuery.ts
+ * @brief Runtime tile-collision queries — "what collision does the tile at
+ * (x, y) carry?" without raycasting the physics world.
+ *
+ * Collision data lives TS-side (resolved from `.estileset` / Tiled sources by the
+ * tilemap plugin), so these are cheap map lookups over the live tile grid: read
+ * the cell id via {@link TilemapAPI.getTile}, then classify it against the
+ * layer's resolved collision table. The plugin installs the layer → table
+ * resolver at build; querying before the plugin runs (or a layer with no
+ * collision data) returns null/false rather than throwing.
+ */
+import { TilemapAPI } from './tilemapAPI';
+import { tileIdOf } from './tileBits';
+import type { ResolvedTileCollision } from './tilesetResolve';
+import type { Entity } from '../types';
+
+/** A layer's resolved collision vocabulary: merge-eligible plain boxes + rich shapes. */
+export interface LayerCollisionTable {
+ boxIds: ReadonlySet<number>;
+ shapes: ReadonlyMap<number, ResolvedTileCollision>;
+}
+
+let lookup_: ((layer: number) => LayerCollisionTable | null) | null = null;
+
+/** Plugin-internal: install (or clear, with null) the layer → collision-table resolver. */
+export function _bindTileCollisionLookup(
+ fn: ((layer: number) => LayerCollisionTable | null) | null,
+): void {
+ lookup_ = fn;
+}
+
+const PLAIN_BOX: ResolvedTileCollision = { shape: { type: 'box' } };
+
+/**
+ * The resolved collision of the tile at grid cell (x, y) on `layer` — a plain
+ * solid box, a rich shape (polygon / circle / one-way / sensor / material), or
+ * null when the cell is empty or its tile has no collision.
+ */
+export function tileCollisionAt(layer: Entity | number, x: number, y: number): ResolvedTileCollision | null {
+ const table = lookup_?.(layer as number);
+ if (!table) return null;
+ const id = tileIdOf(TilemapAPI.getTile(layer as Entity, x, y));
+ if (id === 0) return null;
+ if (table.boxIds.has(id)) return PLAIN_BOX;
+ return table.shapes.get(id) ?? null;
+}
+
+/**
+ * True when the tile at grid cell (x, y) has SOLID collision — any non-sensor
+ * shape. One-way platforms count as solid (they block from their solid side);
+ * check {@link tileCollisionAt}'s `.oneWay` to treat them specially.
+ */
+export function isTileSolid(layer: Entity | number, x: number, y: number): boolean {
+ const c = tileCollisionAt(layer, x, y);
+ return c != null && !c.sensor;
+}
+
+/**
+ * {@link tileCollisionAt} addressed in WORLD pixels — converts through the
+ * layer's own grid (`worldToTile`, honoring the layer origin at (originX,
+ * originY), typically its Transform position).
+ */
+export function tileCollisionAtWorld(
+ layer: Entity | number,
+ worldX: number,
+ worldY: number,
+ originX = 0,
+ originY = 0,
+): ResolvedTileCollision | null {
+ const t = TilemapAPI.worldToTile(layer as Entity, worldX, worldY, originX, originY);
+ return tileCollisionAt(layer, Math.floor(t.x), Math.floor(t.y));
+}
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
index b010da9a2..905d14005 100644
--- a/sdk/src/tilemap/tiledLoader.ts
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -142,6 +142,13 @@ export interface TiledMapData {
tilesets: TiledTilesetData[];
objectGroups: TiledObjectGroupData[];
collisionTileIds: number[];
+ /**
+ * Rich per-tile collision (global id → normalized shape + modifiers), read from
+ * Tiled's tile collision editor (`tiles[].objectgroup`) and tile properties —
+ * the same {@link ResolvedTileCollision} model `.estileset` tiles resolve to,
+ * so both asset paths spawn identical colliders.
+ */
+ tileShapes: Map<number, ResolvedTileCollision>;
tileAnimations: Map<number, TiledAnimFrame[]>;
tileProperties: Map<number, Map<string, string>>;
}
@@ -416,10 +423,13 @@ export function parseTmjJson(json: Record<string, unknown>): TiledMapData | null
const tileAnimations = new Map<number, TiledAnimFrame[]>();
const tileProperties = new Map<number, Map<string, string>>();
+ const tileShapes = new Map<number, ResolvedTileCollision>();
if (rawTilesets) {
for (const ts of rawTilesets) {
const firstGid = (ts.firstgid as number) ?? 1;
+ const tsTw = (ts.tilewidth as number) || tileWidth || 1;
+ const tsTh = (ts.tileheight as number) || tileHeight || 1;
const rawTiles = ts.tiles as Array<Record<string, unknown>> | undefined;
if (rawTiles) {
for (const tile of rawTiles) {
@@ -438,19 +448,36 @@ export function parseTmjJson(json: Record<string, unknown>): TiledMapData | null
}
const tileProps = tile.properties as Array<Record<string, unknown>> | undefined;
+ let legacyCollision = false;
if (tileProps) {
const propMap = new Map<string, string>();
for (const p of tileProps) {
const name = p.name as string;
- if (name === 'collision' && p.value === true) {
- collisionTileIds.push(localId + firstGid);
- }
+ if (name === 'collision' && p.value === true) legacyCollision = true;
propMap.set(name, String(p.value));
}
if (propMap.size > 0) {
tileProperties.set(engineId, propMap);
}
}
+
+ // Tiled's tile collision editor (objectgroup) or the legacy
+ // `collision=true` property, folded into the SAME resolved model
+ // `.estileset` tiles use — plain solid boxes stay merge-eligible
+ // (collisionTileIds), everything richer spawns one collider each.
+ const og = tile.objectgroup as Record<string, unknown> | undefined;
+ const shape = tiledObjectgroupShape(
+ og?.objects as Array<Record<string, unknown>> | undefined, tsTw, tsTh)
+ ?? (legacyCollision ? { type: 'box' as const } : null);
+ if (shape) {
+ const rc: ResolvedTileCollision = { shape, ...tiledCollisionMods(tileProps) };
+ if (shape.type === 'box' && !rc.oneWay && !rc.sensor
+ && rc.density === undefined && rc.friction === undefined && rc.restitution === undefined) {
+ collisionTileIds.push(engineId);
+ } else {
+ tileShapes.set(engineId, rc);
+ }
+ }
}
}
}
@@ -464,11 +491,74 @@ export function parseTmjJson(json: Record<string, unknown>): TiledMapData | null
return {
width, height, tileWidth, tileHeight, orientation,
hexSideLength, staggerAxis, staggerIndex,
- layers, tilesets, objectGroups, collisionTileIds,
+ layers, tilesets, objectGroups, collisionTileIds, tileShapes,
tileAnimations, tileProperties,
};
}
+/**
+ * The first collision-editor object of a Tiled tile's `objectgroup`, as a
+ * normalized {@link ResolvedTileCollision} shape (tile-fraction coordinates, the
+ * same space `.estileset` collision resolves into). A full-cell rectangle folds
+ * to `box` (merge-eligible); a partial rectangle becomes its 4-corner polygon;
+ * an ellipse becomes the inscribed-average circle. Polylines/points are skipped.
+ */
+export function tiledObjectgroupShape(
+ objects: Array<Record<string, unknown>> | undefined,
+ tw: number,
+ th: number,
+): ResolvedTileCollision['shape'] | null {
+ if (!objects) return null;
+ for (const o of objects) {
+ if (o.point === true || o.polyline) continue;
+ const x = (o.x as number) ?? 0;
+ const y = (o.y as number) ?? 0;
+ const w = (o.width as number) ?? 0;
+ const h = (o.height as number) ?? 0;
+ if (o.ellipse === true) {
+ if (w <= 0 || h <= 0) continue;
+ return { type: 'circle', cx: (x + w / 2) / tw, cy: (y + h / 2) / th, r: (w + h) / 4 / tw };
+ }
+ const poly = o.polygon as Array<{ x: number; y: number }> | undefined;
+ if (poly && poly.length >= 3) {
+ return { type: 'polygon', points: poly.map((p) => [(x + p.x) / tw, (y + p.y) / th]) };
+ }
+ if (w > 0 && h > 0) {
+ const eps = 0.5; // px — Tiled UI drags land on fractional coords
+ if (Math.abs(x) <= eps && Math.abs(y) <= eps && Math.abs(w - tw) <= eps && Math.abs(h - th) <= eps) {
+ return { type: 'box' };
+ }
+ return {
+ type: 'polygon',
+ points: [[x / tw, y / th], [(x + w) / tw, y / th], [(x + w) / tw, (y + h) / th], [x / tw, (y + h) / th]],
+ };
+ }
+ }
+ return null;
+}
+
+/**
+ * Collision modifiers from a Tiled tile's typed properties — the same vocabulary
+ * the `.estileset` modifier bar writes: `oneway` (bool, solid-top), `sensor`
+ * (bool), `friction` / `restitution` / `density` (float).
+ */
+export function tiledCollisionMods(
+ props: Array<Record<string, unknown>> | undefined,
+): Partial<Pick<ResolvedTileCollision, 'oneWay' | 'sensor' | 'density' | 'friction' | 'restitution'>> {
+ const out: Partial<Pick<ResolvedTileCollision, 'oneWay' | 'sensor' | 'density' | 'friction' | 'restitution'>> = {};
+ if (!props) return out;
+ for (const p of props) {
+ const name = (p.name as string ?? '').toLowerCase();
+ const v = p.value;
+ if (name === 'oneway' && v === true) out.oneWay = { nx: 0, ny: 1 };
+ else if (name === 'sensor' && v === true) out.sensor = true;
+ else if ((name === 'friction' || name === 'restitution' || name === 'density') && typeof v === 'number') {
+ out[name] = v;
+ }
+ }
+ return out;
+}
+
/**
* Parse a .tmj whose tilesets may be EXTERNAL references (`{firstgid, source}`
* pointing at a .tsj): fetch each source through `resolveExternal`, merge it
@@ -917,6 +1007,67 @@ export function oneWayNormalWorld(nx: number, ny: number, fH: boolean, fV: boole
return { x, y };
}
+/**
+ * Spawn ONE static collider for a rich-shaped tile at grid cell (gx, gy) — the
+ * per-cell core shared by the chunked (painted-layer) and finite (Tiled-layer)
+ * drivers, so both asset paths produce byte-identical collision entities.
+ */
+function spawnTileShape(
+ world: World,
+ rc: ResolvedTileCollision,
+ raw: number,
+ gx: number,
+ gy: number,
+ tileW: number,
+ tileH: number,
+ originX: number,
+ originY: number,
+ ppu: number,
+): Entity {
+ const f = tileFlagsOf(raw);
+ const entity = world.spawn();
+ world.insert(entity, Transform, {
+ position: { x: originX + (gx + 0.5) * tileW, y: originY - (gy + 0.5) * tileH, z: 0 },
+ });
+ world.insert(entity, RigidBody, { bodyType: BodyType.Static });
+
+ // Only the material/sensor fields the tile overrode; the rest keep component defaults.
+ const mat: { density?: number; friction?: number; restitution?: number; isSensor?: boolean } = {};
+ if (rc.density !== undefined) mat.density = rc.density;
+ if (rc.friction !== undefined) mat.friction = rc.friction;
+ if (rc.restitution !== undefined) mat.restitution = rc.restitution;
+ if (rc.sensor) mat.isSensor = true;
+
+ // One pixel-space shape definition (flip-applied), scaled to physics units
+ // (÷ppu) into the matching collider component — the same geometry the editor
+ // overlay draws, so what you see out of Play is what spawns.
+ const shape = tileColliderShape(rc, tileW, tileH, f.flipH, f.flipV, f.flipD);
+ if (shape.kind === 'polygon') {
+ world.insert(entity, PolygonCollider, {
+ vertices: shape.vertices.map((v) => ({ x: v.x / ppu, y: v.y / ppu })),
+ ...mat,
+ });
+ } else if (shape.kind === 'circle') {
+ world.insert(entity, CircleCollider, {
+ radius: shape.radius / ppu,
+ offset: { x: shape.offset.x / ppu, y: shape.offset.y / ppu },
+ ...mat,
+ });
+ } else if (shape.kind === 'box') {
+ world.insert(entity, BoxCollider, {
+ halfExtents: { x: shape.halfExtents.x / ppu, y: shape.halfExtents.y / ppu },
+ ...mat,
+ });
+ }
+
+ if (rc.oneWay) {
+ world.insert(entity, OneWayPlatform, {
+ normal: oneWayNormalWorld(rc.oneWay.nx, rc.oneWay.ny, f.flipH, f.flipV, f.flipD),
+ });
+ }
+ return entity;
+}
+
/**
* Spawn one static collider per placed tile whose global id resolves to a RICH shape —
* polygon / circle, or a box carrying a one-way / sensor / material modifier — i.e. the
@@ -946,53 +1097,45 @@ export function generateChunkTileShapes(
if (!rc) continue;
const gx = baseX + (i % CHUNK_SIZE);
const gy = baseY + Math.floor(i / CHUNK_SIZE);
- const f = tileFlagsOf(raw);
- const entity = world.spawn();
- world.insert(entity, Transform, {
- position: { x: originX + (gx + 0.5) * tileW, y: originY - (gy + 0.5) * tileH, z: 0 },
- });
- world.insert(entity, RigidBody, { bodyType: BodyType.Static });
-
- // Only the material/sensor fields the tile overrode; the rest keep component defaults.
- const mat: { density?: number; friction?: number; restitution?: number; isSensor?: boolean } = {};
- if (rc.density !== undefined) mat.density = rc.density;
- if (rc.friction !== undefined) mat.friction = rc.friction;
- if (rc.restitution !== undefined) mat.restitution = rc.restitution;
- if (rc.sensor) mat.isSensor = true;
-
- // One pixel-space shape definition (flip-applied), scaled to physics units
- // (÷ppu) into the matching collider component — the same geometry the editor
- // overlay draws, so what you see out of Play is what spawns.
- const shape = tileColliderShape(rc, tileW, tileH, f.flipH, f.flipV, f.flipD);
- if (shape.kind === 'polygon') {
- world.insert(entity, PolygonCollider, {
- vertices: shape.vertices.map((v) => ({ x: v.x / ppu, y: v.y / ppu })),
- ...mat,
- });
- } else if (shape.kind === 'circle') {
- world.insert(entity, CircleCollider, {
- radius: shape.radius / ppu,
- offset: { x: shape.offset.x / ppu, y: shape.offset.y / ppu },
- ...mat,
- });
- } else if (shape.kind === 'box') {
- world.insert(entity, BoxCollider, {
- halfExtents: { x: shape.halfExtents.x / ppu, y: shape.halfExtents.y / ppu },
- ...mat,
- });
- }
-
- if (rc.oneWay) {
- world.insert(entity, OneWayPlatform, {
- normal: oneWayNormalWorld(rc.oneWay.nx, rc.oneWay.ny, f.flipH, f.flipV, f.flipD),
- });
- }
- entities.push(entity);
+ entities.push(spawnTileShape(world, rc, raw, gx, gy, tileW, tileH, originX, originY, ppu));
}
}
return entities;
}
+/**
+ * Finite-layer sibling of {@link generateChunkTileShapes} — rich shapes for a flat
+ * Tiled layer array. Runs alongside {@link generateLayerCollision} the same way
+ * the chunk pair runs together on the painted path.
+ */
+export function generateLayerTileShapes(
+ world: World,
+ tiles: ArrayLike<number>,
+ gridWidth: number,
+ gridHeight: number,
+ tileShapes: Map<number, ResolvedTileCollision>,
+ tileW: number,
+ tileH: number,
+ originX: number,
+ originY: number,
+ pixelsPerUnit: number = 1,
+): Entity[] {
+ const entities: Entity[] = [];
+ if (tileShapes.size === 0) return entities;
+ const ppu = pixelsPerUnit || 1;
+ const count = Math.min(tiles.length, gridWidth * gridHeight);
+ for (let i = 0; i < count; i++) {
+ const raw = tiles[i];
+ const rc = tileShapes.get(tileIdOf(raw));
+ if (!rc) continue;
+ entities.push(spawnTileShape(
+ world, rc, raw, i % gridWidth, Math.floor(i / gridWidth),
+ tileW, tileH, originX, originY, ppu,
+ ));
+ }
+ return entities;
+}
+
export function loadTiledMap(
world: World,
mapData: TiledMapData,
@@ -1054,6 +1197,15 @@ export function loadTiledMap(
entities.push(...tileEntities);
}
}
+ 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,
+ ));
+ }
+ }
return entities;
}
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 38f481b27..a01f52659 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -11,9 +11,10 @@ import { Tilemap } from './components';
import { registerSceneComponentCodec } from '../scene';
import { getTilemapSource, getResolvedTileset, type LoadedTilemapSource } from './tilesetCache';
import { resolveTilesetModel } from './tilesetResolve';
+import { _bindTileCollisionLookup, type LayerCollisionTable } from './tileQuery';
import type { ResolvedTileCollision } from './tilesetResolve';
import {
- generateLayerCollision, generateChunkCollision, generateChunkTileShapes,
+ generateLayerCollision, generateLayerTileShapes, generateChunkCollision, generateChunkTileShapes,
generateObjectCollision, isCollisionObjectGroup, decodeTiledGid,
} from './tiledLoader';
import { decodeTilemapChunks } from './chunkCodec';
@@ -65,6 +66,14 @@ export class TilemapPlugin implements Plugin {
private liveResolved_ = new Set<number>();
/** Resolved `.estileset` paths a load has already been kicked off for (de-dupes the lazy load). */
private requestedTilesetLoads_ = new Set<string>();
+ /** Tiled DERIVED child layer → its collision query table (see tileQuery). */
+ private derivedQueryTables_ = new Map<number, LayerCollisionTable>();
+ /** Painted-layer query-table cache, invalidated by source-map identity. */
+ private queryTableCache_ = new Map<number, {
+ ids: number[] | undefined;
+ shapes: Map<number, ResolvedTileCollision> | undefined;
+ table: LayerCollisionTable;
+ }>();
build(app: App): void {
const module = app.wasmModule as ESEngineModule;
@@ -91,6 +100,22 @@ export class TilemapPlugin implements Plugin {
};
TilemapLiveSync._bind(applyTilesetRefs);
+ // Tile-collision queries (tileCollisionAt / isTileSolid): resolve a layer to
+ // its collision vocabulary — a derived Tiled child's table, or a painted
+ // layer's live-resolved/baked sets (cached per source identity).
+ _bindTileCollisionLookup((layer) => {
+ const derived = this.derivedQueryTables_.get(layer);
+ if (derived) return derived;
+ const ids = this.nativeCollisionIds_.get(layer);
+ const shapes = this.nativeTileShapes_.get(layer);
+ if (!ids && !shapes) return null;
+ const cached = this.queryTableCache_.get(layer);
+ if (cached && cached.ids === ids && cached.shapes === shapes) return cached.table;
+ const table: LayerCollisionTable = { boxIds: new Set(ids ?? []), shapes: shapes ?? new Map() };
+ this.queryTableCache_.set(layer, { ids, shapes, table });
+ return table;
+ });
+
registerSceneComponentCodec('TilemapLayer', {
exportData: (entity, data) => {
const blob = TilemapAPI.exportChunks(entity);
@@ -398,6 +423,15 @@ export class TilemapPlugin implements Plugin {
+ 'works). See earlier [tilemap] load errors for the failing image path(s).');
}
+ // The child answers tile-collision queries with the
+ // source map's vocabulary (same table as the spawn path).
+ if ((cached.collisionTileIds?.length ?? 0) > 0 || (cached.tileShapes?.size ?? 0) > 0) {
+ this.derivedQueryTables_.set(child, {
+ boxIds: new Set(cached.collisionTileIds ?? []),
+ shapes: cached.tileShapes ?? new Map(),
+ });
+ }
+
children.push(child);
initializedLayers.add(child);
}
@@ -466,29 +500,42 @@ export class TilemapPlugin implements Plugin {
}
const hasTileCollision = !!(cached.collisionTileIds && cached.collisionTileIds.length > 0);
+ const hasTileShapes = !!(cached.tileShapes && cached.tileShapes.size > 0);
const collisionGroups = cached.objectGroups
? cached.objectGroups.filter(isCollisionObjectGroup)
: [];
if (
playMode
&& !collisionEntities.has(entity)
- && (hasTileCollision || collisionGroups.length > 0)
+ && (hasTileCollision || hasTileShapes || collisionGroups.length > 0)
) {
const tf = world.tryGet(entity, Transform) as
{ position: { x: number; y: number } } | null;
const ox = tf?.position.x ?? 0;
const oy = tf?.position.y ?? 0;
const spawned: Entity[] = [];
- if (hasTileCollision) {
+ 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;
- spawned.push(...generateLayerCollision(
- world, layer.tiles, layer.width, layer.height,
- cached.tileWidth, cached.tileHeight, ids, ox, oy, pixelsPerUnit,
- ));
+ if (hasTileCollision) {
+ spawned.push(...generateLayerCollision(
+ world, layer.tiles, layer.width, layer.height,
+ cached.tileWidth, cached.tileHeight, ids, ox, oy, pixelsPerUnit,
+ ));
+ }
+ // Rich Tiled tile-collision (shapes / one-way / sensor /
+ // material) spawns through the same per-tile core as the
+ // painted `.estileset` path.
+ if (hasTileShapes) {
+ spawned.push(...generateLayerTileShapes(
+ world, layer.tiles, layer.width, layer.height,
+ cached.tileShapes!, cached.tileWidth, cached.tileHeight,
+ ox, oy, pixelsPerUnit,
+ ));
+ }
}
}
// Tiled OBJECT layers marked as collision spawn static colliders
@@ -534,6 +581,7 @@ export class TilemapPlugin implements Plugin {
this.initializedLayers_.delete(child);
}
this.animatedLayers_.delete(child);
+ this.derivedQueryTables_.delete(child);
// An owner despawn cascades to its children; only a component
// removal leaves them alive to clean up here.
if (world.valid(child)) world.despawn(child);
@@ -564,11 +612,14 @@ export class TilemapPlugin implements Plugin {
this.tilesetRefs_.clear();
this.liveResolved_.clear();
this.requestedTilesetLoads_.clear();
+ this.derivedQueryTables_.clear();
+ this.queryTableCache_.clear();
}
cleanup(): void {
this.resetLayers();
TilemapLiveSync._bind(null);
+ _bindTileCollisionLookup(null);
shutdownTilemapAPI();
}
}
diff --git a/sdk/src/tilemap/tilesetCache.ts b/sdk/src/tilemap/tilesetCache.ts
index a0159a259..313e26aaf 100644
--- a/sdk/src/tilemap/tilesetCache.ts
+++ b/sdk/src/tilemap/tilesetCache.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { ResolvedTileset } from './tilesetResolve';
+import type { ResolvedTileset, ResolvedTileCollision } from './tilesetResolve';
import type { TiledObjectGroupData } from './tiledLoader';
export interface LoadedTilemapChunk {
@@ -43,6 +43,8 @@ export interface LoadedTilemapSource {
tileProperties?: Map<number, Map<string, string>>;
/** Tile ids flagged collidable (a `collision=true` tile property). Drives runtime collider generation. */
collisionTileIds?: number[];
+ /** Rich per-tile collision (Tiled collision editor / modifier properties) — see TiledMapData.tileShapes. */
+ tileShapes?: Map<number, ResolvedTileCollision>;
/**
* Tiled object layers — spawn/marker data queryable by gameplay via
* `getTilemapSource`; groups marked per `isCollisionObjectGroup` also spawn
diff --git a/sdk/tests/tile-query.test.ts b/sdk/tests/tile-query.test.ts
new file mode 100644
index 000000000..8ac924498
--- /dev/null
+++ b/sdk/tests/tile-query.test.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Runtime tile-collision queries: classification against the layer's
+ * resolved collision table over the live tile grid.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { tileCollisionAt, isTileSolid, _bindTileCollisionLookup, type LayerCollisionTable } from '../src/tilemap/tileQuery';
+import { TilemapAPI } from '../src/tilemap/tilemapAPI';
+import { encodeTile } from '../src/tilemap/tileBits';
+
+const grid = new Map<string, number>();
+vi.spyOn(TilemapAPI, 'getTile').mockImplementation(((_layer: number, x: number, y: number) =>
+ grid.get(`${x},${y}`) ?? 0) as never);
+
+const TABLE: LayerCollisionTable = {
+ boxIds: new Set([1]),
+ shapes: new Map([
+ [2, { shape: { type: 'circle', cx: 0.5, cy: 0.5, r: 0.5 } }],
+ [3, { shape: { type: 'box' }, sensor: true }],
+ [4, { shape: { type: 'box' }, oneWay: { nx: 0, ny: 1 } }],
+ ]),
+};
+
+describe('tileCollisionAt / isTileSolid', () => {
+ beforeEach(() => {
+ grid.clear();
+ _bindTileCollisionLookup(() => TABLE);
+ });
+ afterEach(() => _bindTileCollisionLookup(null));
+
+ it('classifies plain boxes, rich shapes, sensors, and empties', () => {
+ grid.set('0,0', encodeTile(1));
+ grid.set('1,0', encodeTile(2));
+ grid.set('2,0', encodeTile(3));
+ grid.set('3,0', encodeTile(4));
+ grid.set('4,0', encodeTile(9)); // decorative tile — no collision entry
+
+ expect(tileCollisionAt(0, 0, 0)).toEqual({ shape: { type: 'box' } });
+ expect(tileCollisionAt(0, 1, 0)?.shape.type).toBe('circle');
+ expect(tileCollisionAt(0, 5, 0)).toBeNull(); // empty cell
+ expect(tileCollisionAt(0, 4, 0)).toBeNull(); // no collision authored
+
+ expect(isTileSolid(0, 0, 0)).toBe(true);
+ expect(isTileSolid(0, 2, 0)).toBe(false); // sensor is not solid
+ expect(isTileSolid(0, 3, 0)).toBe(true); // one-way counts as solid
+ expect(tileCollisionAt(0, 3, 0)?.oneWay).toEqual({ nx: 0, ny: 1 });
+ });
+
+ it('returns null/false when no lookup is bound or the layer has no table', () => {
+ _bindTileCollisionLookup(null);
+ expect(tileCollisionAt(0, 0, 0)).toBeNull();
+ _bindTileCollisionLookup(() => null);
+ expect(isTileSolid(0, 0, 0)).toBe(false);
+ });
+});
diff --git a/sdk/tests/tiled-tile-collision.test.ts b/sdk/tests/tiled-tile-collision.test.ts
new file mode 100644
index 000000000..9653a13f8
--- /dev/null
+++ b/sdk/tests/tiled-tile-collision.test.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Tiled per-tile collision import: the collision editor's objectgroup and
+ * the modifier tile properties resolve into the SAME ResolvedTileCollision
+ * model .estileset tiles use, and spawn through the shared per-tile core.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { parseTmjJson, tiledObjectgroupShape, tiledCollisionMods, generateLayerTileShapes } from '../src/tilemap/tiledLoader';
+import type { World } from '../src/world';
+import type { Entity } from '../src/types';
+
+function mockWorld() {
+ let nextId = 1;
+ const comps = new Map<number, Map<string, any>>();
+ const world = {
+ spawn: vi.fn(() => { const id = nextId++ as Entity; comps.set(id, new Map()); return id; }),
+ insert: vi.fn((e: Entity, c: any, d: any) => { comps.get(e)!.set(c._name, d); }),
+ } as unknown as World;
+ return { world, comps };
+}
+
+const layerJson = (data: number[], w = 2, h = 1) => ({
+ type: 'tilelayer', name: 'ground', width: w, height: h, data, visible: true,
+});
+
+function mapJson(tiles: Array<Record<string, unknown>>, data: number[]) {
+ return {
+ width: 2, height: 1, tilewidth: 16, tileheight: 16, orientation: 'orthogonal',
+ layers: [layerJson(data)],
+ tilesets: [{
+ firstgid: 1, name: 'ts', image: 'a.png', imagewidth: 64, imageheight: 16,
+ tilewidth: 16, tileheight: 16, columns: 4, tilecount: 4,
+ tiles,
+ }],
+ };
+}
+
+describe('tiledObjectgroupShape', () => {
+ it('folds a full-cell rectangle to a merge-eligible box', () => {
+ expect(tiledObjectgroupShape([{ x: 0, y: 0, width: 16, height: 16 }], 16, 16)).toEqual({ type: 'box' });
+ });
+ it('turns a partial rectangle into its 4-corner polygon (normalized)', () => {
+ expect(tiledObjectgroupShape([{ x: 0, y: 8, width: 16, height: 8 }], 16, 16)).toEqual({
+ type: 'polygon',
+ points: [[0, 0.5], [1, 0.5], [1, 1], [0, 1]],
+ });
+ });
+ it('maps an ellipse to the averaged circle', () => {
+ expect(tiledObjectgroupShape([{ x: 0, y: 0, width: 16, height: 16, ellipse: true }], 16, 16)).toEqual({
+ type: 'circle', cx: 0.5, cy: 0.5, r: 0.5,
+ });
+ });
+ it('offsets polygon points by the object position and normalizes', () => {
+ expect(tiledObjectgroupShape(
+ [{ x: 0, y: 16, polygon: [{ x: 0, y: 0 }, { x: 16, y: -16 }, { x: 16, y: 0 }] }], 16, 16)).toEqual({
+ type: 'polygon', points: [[0, 1], [1, 0], [1, 1]],
+ });
+ });
+ it('skips points and polylines', () => {
+ expect(tiledObjectgroupShape([{ x: 1, y: 1, point: true }, { polyline: [{ x: 0, y: 0 }] }], 16, 16)).toBeNull();
+ });
+});
+
+describe('tiledCollisionMods', () => {
+ it('reads oneway/sensor/material from typed tile properties', () => {
+ expect(tiledCollisionMods([
+ { name: 'oneway', type: 'bool', value: true },
+ { name: 'sensor', type: 'bool', value: true },
+ { name: 'friction', type: 'float', value: 0.9 },
+ { name: 'density', type: 'float', value: 2 },
+ ])).toEqual({ oneWay: { nx: 0, ny: 1 }, sensor: true, friction: 0.9, density: 2 });
+ });
+});
+
+describe('parseTmjJson tile collision', () => {
+ it('routes plain full-cell boxes to collisionTileIds and rich shapes to tileShapes', () => {
+ const map = parseTmjJson(mapJson([
+ { id: 0, objectgroup: { objects: [{ x: 0, y: 0, width: 16, height: 16 }] } }, // gid 1: plain box
+ { id: 1, objectgroup: { objects: [{ x: 0, y: 8, width: 16, height: 8 }] } }, // gid 2: half slab
+ {
+ id: 2, // gid 3: one-way box
+ objectgroup: { objects: [{ x: 0, y: 0, width: 16, height: 16 }] },
+ properties: [{ name: 'oneway', type: 'bool', value: true }],
+ },
+ ], [1, 2]));
+
+ expect(map.collisionTileIds).toEqual([1]);
+ expect(map.tileShapes.get(2)?.shape.type).toBe('polygon');
+ expect(map.tileShapes.get(3)).toEqual({ shape: { type: 'box' }, oneWay: { nx: 0, ny: 1 } });
+ });
+
+ it('keeps the legacy collision=true property as a plain box', () => {
+ const map = parseTmjJson(mapJson([
+ { id: 0, properties: [{ name: 'collision', type: 'bool', value: true }] },
+ ], [1, 0]));
+ expect(map.collisionTileIds).toEqual([1]);
+ expect(map.tileShapes.size).toBe(0);
+ });
+});
+
+describe('generateLayerTileShapes', () => {
+ it('spawns one collider per rich tile in a finite layer, sharing the chunk core semantics', () => {
+ const map = parseTmjJson(mapJson([
+ { id: 1, objectgroup: { objects: [{ x: 0, y: 0, width: 16, height: 16, ellipse: true }] } }, // gid 2: circle
+ ], [2, 2]));
+ const { world, comps } = mockWorld();
+ const spawned = generateLayerTileShapes(
+ world, map.layers[0].tiles, 2, 1, map.tileShapes, 16, 16, 0, 0, 100);
+ expect(spawned).toHaveLength(2);
+ const c = comps.get(spawned[0] as number)!;
+ expect(c.get('CircleCollider')).toBeDefined();
+ expect(c.get('CircleCollider').radius).toBeCloseTo(8 / 100); // physics units
+ expect(c.get('RigidBody')).toBeDefined();
+ // Cell 1 sits one tile to the right.
+ expect(comps.get(spawned[1] as number)!.get('Transform').position.x).toBeCloseTo(24);
+ });
+});
diff --git a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp b/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp
index 61bd40a4e..b63536b58 100644
--- a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp
+++ b/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp
@@ -270,12 +270,13 @@ void TilemapRenderPlugin::collect(RenderCollectContext& collect_ctx) {
auto& cache = chunkCaches[coord];
if (chunkData.revision != cache.built_revision
- || cache.has_animated_tiles
+ || (cache.has_animated_tiles && layer.anim_revision != cache.built_anim_revision)
|| cache.slots.size() != slots.size()) {
rebuildChunk(layer, chunkData, coord,
adjOriginX, adjOriginY, packedColor,
slots, resolved, entity, cache);
cache.built_revision = chunkData.revision;
+ cache.built_anim_revision = layer.anim_revision;
}
for (usize si = 0; si < slots.size() && si < cache.slots.size(); ++si) {
diff --git a/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp b/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp
index 239516362..e9f44196f 100644
--- a/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp
+++ b/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp
@@ -37,6 +37,9 @@ private:
// against ChunkData::revision so we rebuild only on real edits — the
// renderer reads this snapshot stamp and never writes to content.
u32 built_revision = 0;
+ // Animation-frame revision this cache was built at; an animated chunk
+ // rebuilds when a visible frame flips, not every frame.
+ u32 built_anim_revision = 0;
};
// A layer slot with its texture resolved for the current frame.
diff --git a/src/esengine/tilemap/TilemapSystem.cpp b/src/esengine/tilemap/TilemapSystem.cpp
index cce31a88a..9a8aafcb4 100644
--- a/src/esengine/tilemap/TilemapSystem.cpp
+++ b/src/esengine/tilemap/TilemapSystem.cpp
@@ -251,12 +251,36 @@ void TilemapSystem::setTileAnimation(Entity entity, u16 tileId,
}
if (anim.total_duration_ms == 0) return;
layer->tile_animations[tileId] = std::move(anim);
+ layer->anim_revision++; // the frame table changed — cached meshes are stale
}
+namespace {
+/// Index of the frame an animation shows at `elapsedMs` (looped).
+u32 frameIndexAt(const TileAnimation& anim, f32 elapsedMs) {
+ u32 t = static_cast<u32>(std::fmod(elapsedMs, static_cast<f32>(anim.total_duration_ms)));
+ u32 acc = 0;
+ for (u32 i = 0; i < anim.frames.size(); ++i) {
+ acc += anim.frames[i].duration_ms;
+ if (t < acc) return i;
+ }
+ return static_cast<u32>(anim.frames.size()) - 1;
+}
+} // namespace
+
void TilemapSystem::advanceAnimations(Entity entity, f32 dtMs) {
auto* layer = getLayerDataMut(entity);
if (!layer || layer->tile_animations.empty()) return;
+ const f32 prev = layer->elapsed_ms;
layer->elapsed_ms += dtMs;
+ // Bump the revision only when some animation's visible frame actually
+ // flipped — the renderer rebuilds animated chunks on this stamp instead of
+ // every frame, so slow animations cost re-meshing only at their frame rate.
+ for (const auto& [id, anim] : layer->tile_animations) {
+ if (frameIndexAt(anim, prev) != frameIndexAt(anim, layer->elapsed_ms)) {
+ layer->anim_revision++;
+ return;
+ }
+ }
}
u16 TilemapSystem::resolveAnimatedTile(Entity entity, u16 tileId) const {
@@ -267,13 +291,7 @@ u16 TilemapSystem::resolveAnimatedTile(Entity entity, u16 tileId) const {
if (it == layer->tile_animations.end()) return tileId;
const auto& anim = it->second;
- u32 t = static_cast<u32>(std::fmod(layer->elapsed_ms, static_cast<f32>(anim.total_duration_ms)));
- u32 acc = 0;
- for (const auto& frame : anim.frames) {
- acc += frame.duration_ms;
- if (t < acc) return frame.tile_id;
- }
- return anim.frames.back().tile_id;
+ return anim.frames[frameIndexAt(anim, layer->elapsed_ms)].tile_id;
}
void TilemapSystem::setTileProperty(Entity entity, u16 tileId,
diff --git a/src/esengine/tilemap/TilemapSystem.hpp b/src/esengine/tilemap/TilemapSystem.hpp
index d84a0d4ee..3ab7bbfed 100644
--- a/src/esengine/tilemap/TilemapSystem.hpp
+++ b/src/esengine/tilemap/TilemapSystem.hpp
@@ -147,6 +147,10 @@ public:
std::unordered_map<u16, TileAnimation> tile_animations;
f32 elapsed_ms = 0;
+ // Bumped only when some animation's CURRENT frame changes (or the
+ // animation table itself does) — animated chunk meshes rebuild on this,
+ // not every frame.
+ u32 anim_revision = 0;
std::unordered_map<u16, std::unordered_map<std::string, std::string>> tile_properties;
};