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.

fix(tilemap): preserve inactive layers and own runtime colliders

yhhee584b19666d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 43a3505cf..f154e09fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,13 +16,15 @@ published separately; it ships inside the editor.
### Fixed
+- **Tilemap activity preserves painted data and owns generated collision.** Disabling a layer or its ancestor retains its chunks and derived layers. Runtime colliders inherit the map's movement and activity, remain outside saved scenes, and resume with their existing identities; inactive tile animations stop advancing.
+
- **Static 2D bodies follow authored transforms and parent movement.** Box2D updates changed static poses in place, preserving bodies and shapes without repeating writes for unchanged poses. Initial body creation composes the hierarchy first, and parented static bodies no longer force dynamic-body writeback out of its batch path.
- **Recreated tilemap layers discard old geometry and collision.** A layer generation distinguishes replacement from ordinary edits, even when the same entity and edit count are reused. Reinitializing or immediately recreating a layer releases its old chunk meshes and rebuilds collision from the replacement; unchanged layers retain their caches.
- **Tilemap runtimes and saved chunks stay with their own worlds.** Closing a preview or an older App no longer destroys another core's same-numbered layers or disables its collision updates. Scene codecs serialize each world's own tiles; closing the current runtime restores the previous live tooling interface and collision lookup, and releases the retired codec.
-- **Native tilemap collisions follow live edits.** Changing painted tiles, importing an empty map, moving a layer or removing its collision palette replaces obsolete runtime colliders. A native content revision keeps unchanged frames and repeated writes from exporting the map or rebuilding collision.
+- **Native tilemap collisions follow live edits.** Changing painted tiles, importing an empty map or removing its collision palette replaces obsolete runtime colliders. A native content revision keeps unchanged frames and repeated writes from exporting the map or rebuilding collision.
- **Unchanged tile writes preserve chunk caches.** Repainting a tile with its existing value no longer advances the chunk revision or forces geometry rebuilding. Erasing untouched empty space does not allocate empty chunks, including negative coordinates in infinite maps.
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 2b0961171..818d5e758 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -25,6 +25,7 @@ import { Time } from '../ecs/resource';
import { playModeOnly } from '../ecs/env';
import { log } from '../util/logger';
import type { Entity } from '../types';
+import type { World } from '../ecs/world';
const GRID_TYPE_MAP: Record<string, number> = {
orthogonal: 0,
@@ -40,8 +41,6 @@ interface CollisionInputs {
revision: number;
width: number;
height: number;
- x: number;
- y: number;
pixelsPerUnit: number;
ids: number[] | undefined;
shapes: Map<number, ResolvedTileCollision> | undefined;
@@ -246,9 +245,9 @@ export class TilemapRuntime {
[TilemapLayer, Transform],
);
- const currentLayerSet = new Set(layerEntities);
for (const entity of initializedLayers) {
- if (!currentLayerSet.has(entity)) {
+ if (!world.valid(entity as Entity) || !world.has(entity as Entity, TilemapLayer)
+ || !world.has(entity as Entity, Transform)) {
TilemapAPI.destroyLayer(entity);
initializedLayers.delete(entity);
collisionInputs.delete(entity);
@@ -397,9 +396,6 @@ export class TilemapRuntime {
const tileShapes = nativeTileShapes.get(entity);
const hasBox = collIds != null && collIds.length > 0;
const hasShapes = tileShapes != null && tileShapes.size > 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 revision = playMode && (hasBox || hasShapes)
? engine.tilemap_getEditRevision?.(entity) ?? 0
: 0;
@@ -409,7 +405,7 @@ export class TilemapRuntime {
const previous = collisionInputs.get(entity);
const changed = !previous || previous.generation !== generation || previous.revision !== revision
|| previous.width !== layerData.cellSize.x || previous.height !== layerData.cellSize.y
- || previous.x !== ox || previous.y !== oy || previous.pixelsPerUnit !== pixelsPerUnit
+ || previous.pixelsPerUnit !== pixelsPerUnit
|| previous.ids !== collIds || previous.shapes !== tileShapes;
if (playMode && collisionEntities.has(entity) && (changed || (!hasBox && !hasShapes))) {
for (const collider of collisionEntities.get(entity)!) world.despawn(collider);
@@ -422,18 +418,19 @@ export class TilemapRuntime {
if (hasBox) {
spawned.push(...generateChunkCollision(
world, chunks, new Set(collIds),
- layerData.cellSize.x, layerData.cellSize.y, ox, oy, pixelsPerUnit,
+ layerData.cellSize.x, layerData.cellSize.y, 0, 0, pixelsPerUnit,
));
}
if (hasShapes) {
spawned.push(...generateChunkTileShapes(
world, chunks, tileShapes,
- layerData.cellSize.x, layerData.cellSize.y, ox, oy, pixelsPerUnit,
+ layerData.cellSize.x, layerData.cellSize.y, 0, 0, pixelsPerUnit,
));
}
+ this.attachCollision_(world, entity, spawned);
collisionEntities.set(entity, spawned);
collisionInputs.set(entity, { generation, revision, width: layerData.cellSize.x,
- height: layerData.cellSize.y, x: ox, y: oy, pixelsPerUnit,
+ height: layerData.cellSize.y, pixelsPerUnit,
ids: collIds, shapes: tileShapes });
}
}
@@ -666,10 +663,6 @@ export class TilemapRuntime {
&& !collisionEntities.has(entity)
&& (hasTileCollision || hasTileShapes)
) {
- 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 || hasTileShapes) {
const ids = new Set(cached.collisionTileIds);
@@ -682,13 +675,13 @@ export class TilemapRuntime {
if (hasTileCollision) {
spawned.push(...generateChunkCollision(
world, layer.chunks, ids,
- cached.tileWidth, cached.tileHeight, ox, oy, pixelsPerUnit,
+ cached.tileWidth, cached.tileHeight, 0, 0, pixelsPerUnit,
));
}
if (hasTileShapes) {
spawned.push(...generateChunkTileShapes(
world, layer.chunks, cached.tileShapes!,
- cached.tileWidth, cached.tileHeight, ox, oy, pixelsPerUnit,
+ cached.tileWidth, cached.tileHeight, 0, 0, pixelsPerUnit,
));
}
continue;
@@ -697,7 +690,7 @@ export class TilemapRuntime {
if (hasTileCollision) {
spawned.push(...generateLayerCollision(
world, layer.tiles, layer.width, layer.height,
- cached.tileWidth, cached.tileHeight, ids, ox, oy, pixelsPerUnit,
+ cached.tileWidth, cached.tileHeight, ids, 0, 0, pixelsPerUnit,
));
}
// Rich Tiled tile-collision (shapes / one-way / sensor /
@@ -707,24 +700,25 @@ export class TilemapRuntime {
spawned.push(...generateLayerTileShapes(
world, layer.tiles, layer.width, layer.height,
cached.tileShapes!, cached.tileWidth, cached.tileHeight,
- ox, oy, pixelsPerUnit,
+ 0, 0, pixelsPerUnit,
));
}
}
}
+ this.attachCollision_(world, entity, spawned);
collisionEntities.set(entity, spawned);
}
}
- const currentTilemapSet = new Set(tilemapEntities);
for (const entity of [...sourceLayerEntities.keys()]) {
- if (!currentTilemapSet.has(entity)) this.teardownDerived_(world, entity);
+ if (!world.valid(entity as Entity) || !world.has(entity as Entity, Tilemap)
+ || world.has(entity as Entity, TilemapLayer)) this.teardownDerived_(world, entity);
}
if (animatedLayers.size > 0) {
const dtMs = app.getResource(Time).delta * 1000;
for (const key of animatedLayers) {
- TilemapAPI.advanceAnimations(key, dtMs);
+ if (world.isEntityActive(key as Entity)) TilemapAPI.advanceAnimations(key, dtMs);
}
}
},
@@ -733,6 +727,13 @@ export class TilemapRuntime {
app.addSystemToSchedule(Schedule.PreUpdate, tilemapSyncSystem);
}
+ private attachCollision_(world: World, owner: Entity, colliders: Entity[]): void {
+ for (const collider of colliders) {
+ if (!world.has(collider, RuntimeOnly)) world.insert(collider, RuntimeOnly, {});
+ world.setParent(collider, owner);
+ }
+ }
+
/** Drop ONE tilemap entity's derived artifacts (child layer entities +
* play-mode colliders + bookkeeping) so the sync can re-derive — or not,
* if its source is gone. Fires when the Tilemap component disappears AND
diff --git a/sdk/tests/tilemap-live-collision-wasm.test.ts b/sdk/tests/tilemap-live-collision-wasm.test.ts
index 4a3a012a8..a769d6760 100644
--- a/sdk/tests/tilemap-live-collision-wasm.test.ts
+++ b/sdk/tests/tilemap-live-collision-wasm.test.ts
@@ -3,7 +3,8 @@
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
import { App } from '../src/app/app';
-import { Transform, TilemapLayer } from '../src/ecs/component';
+import { Transform, TilemapLayer, Disabled, RuntimeOnly, Parent } from '../src/ecs/component';
+import { serializeScene } from '../src/scene/scene';
import { TilemapPlugin, TilemapRuntimeState } from '../src/tilemap/tilemapPlugin';
import { Tilemaps } from '../src/tilemap/tilemapAPI';
@@ -51,13 +52,13 @@ describe.skipIf(!HAS_WASM)('live native tile collision', () => {
tiles.setTile(entity, -1, -1, 1); await app.tick(1 / 60);
expect(colliders().length).toBeGreaterThan(0);
});
- it('updates collision after a layer move and palette removal', async () => {
+ it('inherits layer movement without rebuilding and removes collision with its palette', async () => {
const { app, entity, colliders } = await scene();
const original = [...colliders()];
app.world.update(entity, Transform, value => { value.position.x = 32; });
await app.tick(1 / 60);
- expect(colliders()).not.toEqual(original);
- for (const id of original) expect(app.world.valid(id)).toBe(false);
+ expect(colliders()).toEqual(original);
+ for (const id of original) expect(app.world.get(id, Parent).entity).toBe(entity);
app.getResource(TilemapRuntimeState).setLayerTilesets(entity, []);
await app.tick(1 / 60);
expect(colliders() ?? []).toHaveLength(0);
@@ -80,4 +81,34 @@ describe.skipIf(!HAS_WASM)('live native tile collision', () => {
expect(app.world.get(colliders()[0], Transform).position.x).toBe(24);
for (const id of original) expect(app.world.valid(id)).toBe(false);
});
+ it('preserves tiles and collider identity while disabling and reenabling a layer', async () => {
+ const { app, entity, tiles, colliders } = await scene();
+ const original = [...colliders()];
+ app.world.insert(entity, Disabled);
+ await app.tick(1 / 60);
+ expect(tiles.getTile(entity, 0, 0)).toBe(1);
+ for (const collider of original) expect(app.world.isEntityActive(collider)).toBe(false);
+ app.world.remove(entity, Disabled); await app.tick(1 / 60);
+ expect(colliders()).toEqual(original);
+ for (const collider of original) expect(app.world.isEntityActive(collider)).toBe(true);
+ });
+ it('keeps generated collision out of serialized scenes', async () => {
+ const { app, entity, colliders } = await scene();
+ for (const collider of colliders()) {
+ expect(app.world.has(collider, RuntimeOnly)).toBe(true);
+ expect(app.world.get(collider, Parent).entity).toBe(entity);
+ }
+ expect(serializeScene(app.world).entities).toHaveLength(1);
+ });
+ it('inherits a disabled ancestor without losing painted tiles', async () => {
+ const { app, entity, tiles, colliders } = await scene();
+ const parent = app.world.spawn(); app.world.insert(parent, Transform);
+ app.world.setParent(entity, parent);
+ const original = [...colliders()];
+ app.world.insert(parent, Disabled); await app.tick(1 / 60);
+ expect(tiles.getTile(entity, 0, 0)).toBe(1);
+ for (const collider of original) expect(app.world.isEntityActive(collider)).toBe(false);
+ app.world.remove(parent, Disabled); await app.tick(1 / 60);
+ expect(colliders()).toEqual(original);
+ });
});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index f6e4fa200..bbfbaa797 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(tilemap): preserve inactive layers and own runtime colliders':
+ { note: 'Tilemap activity preserves painted data and owns generated collision.' },
'fix(physics): synchronize static body transforms in place':
{ note: 'Static 2D bodies follow authored transforms and parent movement.' },
'fix(tilemap): invalidate caches when a layer is recreated':