Halve the frame time of a playing scene with a tilemap (#284)

The performance panel showed Physics and Editor as the large parts of
a frame in a scene of 222 entities. Nearly all of it came from a
tilemap that only stands there.

- Whoever writes cells in place now says so with cellsChanged. Only
  then does cellsVersion compare the content. The comparison ran about
  60 times per frame and was the largest single item at 14 percent.
- The four writers call it: the painter during and at the end of a
  stroke, PaintTilesCommand on execute and on undo. A new writer that
  forgets it stays invisible.
- The game view is drawn once per frame in play. With an animated tile
  in view it was drawn twice, once by the run and once by animate().
  animate() now gets the redraw count from the start of the tick.
- TilemapField builds the geometry of a mesh only when its source
  changes: the cells, the tile size, the origin or the image. For that
  groupByTile and layerRows return the same objects for the same list.
- PhysicsSystem skips a tilemap whose source and switch are unchanged.
  The switch is kept because a map that starts switched off would
  otherwise have dead colliders once it is switched on.
- World.syncToModel looks entities and assets up in a map per pass
  instead of a linear search per object.

Measured on stein2 with a copy of the reference project, ms per frame:
Physics 2.64 to 0.97, Drawing 6.89 to 2.56, Editor 1.95 to 1.31.

Left open: syncToModel still mirrors every entity every frame. That
is its own issue.

Tests:
- Gate: 198 files, 2887 tests (2883 + 4), exit 0
- e2e 1-17,28,33,39-43,59: 810 checks passed, 40 has +3
- Smokes: 24 / 19 / 21, exit 0
- Three unit tests wrote cells directly and now call cellsChanged
- Eleven counter-probes fail. Two did not at first: the stroke needed
  a check of its own, the physics test has to start with the map
  switched off. That last one was repeated on stein2 only.
- e2e total 1613 is computed, not measured in a full run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-01 09:52:57 +02:00
1 parent 6491888f56
commit cfd288c4b7
15 files changed
+303 -43

No files matched your search

+30
View File
@@ -177,6 +177,36 @@ describe('falling and resting', () => {
expect(entity(box).y).toBeCloseTo(192 - 16, 0);
});
it('a map switched off by its parent holds nothing, holds once switched on, and lets go again', () => {
const f = physicsScene();
const solid = new CreateAssetCommand('tile', 'Wall');
const map = new CreateAssetCommand('tilemap', 'Ground');
f.stack.execute(solid);
f.stack.execute(map);
f.stack.execute(new SetAssetPropertyCommand(solid.asset.id, TILE_SOLID_KEY, true));
f.stack.execute(new SetAssetPropertyCommand(map.asset.id, TILEMAP_COLUMNS_KEY, 10));
f.stack.execute(new SetAssetPropertyCommand(map.asset.id, TILEMAP_ROWS_KEY, 10));
const holder = place(f, f.spriteId, { x: 0, y: 0 });
place(f, map.asset.id, { x: 0, y: 0 }, holder);
const layer = (findAsset(f.project, map.asset.id) as TilemapAsset).layers[0]!.id;
const row = Array.from({ length: 10 }, (_, x) => ({ x, y: 9, tileId: solid.asset.id }));
f.stack.execute(new PaintTilesCommand(map.asset.id, layer, row));
const box = f.add(0, 0, { w: 32, body: {} });
const { seconds, entity, physics } = run(f);
// The map's own values stay as they are throughout: only what is above it changes.
entity(holder).props.enabled = false;
seconds(1);
expect(entity(box).y).toBeGreaterThan(300);
entity(holder).props.enabled = true;
entity(box).y = 0;
physics.setVelocity(entity(box), { x: 0, y: 0 });
seconds(3);
expect(entity(box).y).toBeCloseTo(192 - 16, 0);
entity(holder).props.enabled = false;
seconds(1);
expect(entity(box).y).toBeGreaterThan(300);
});
it('lands on a floor set during the run and falls on once it is taken away (#135)', () => {
const f = physicsScene();
const solid = new CreateAssetCommand('tile', 'Wall');
+39 -4
View File
@@ -14,7 +14,7 @@ import {
TILEMAP_TILE_KEY,
} from '../../src/core/model/tilemap';
import { solidPolygons, solidRects } from '../../src/core/model/tilemapCollision';
import { cellsVersion, KeyedMemo } from '../../src/core/model/tilemapMemo';
import { cellsChanged, cellsVersion, KeyedMemo } from '../../src/core/model/tilemapMemo';
import { loadPhysics } from '../../src/runtime/physics/engine';
import { Solids } from '../../src/runtime/systems/solids';
import { makeSpriteScene, place, startWorld } from '../helpers';
@@ -83,18 +83,50 @@ function map() {
describe('what a tilemap works out is remembered while its content stays', () => {
it('a version stays while the cells hold the same, and changes when one is painted in place', () => {
const cells: Record<string, string> = { '0,0': 'a', '1,0': 'b' };
const paint = (key: string, tileId: string) => {
if (tileId) cells[key] = tileId;
else delete cells[key];
cellsChanged(cells);
};
const first = cellsVersion(cells);
expect(cellsVersion(cells)).toBe(first);
cells['2,0'] = 'a';
paint('2,0', 'a');
const added = cellsVersion(cells);
expect(added).not.toBe(first);
cells['2,0'] = 'b';
paint('2,0', 'b');
const changed = cellsVersion(cells);
expect(changed).not.toBe(added);
delete cells['0,0'];
paint('0,0', '');
expect(cellsVersion(cells)).not.toBe(changed);
});
it('cells are compared only when their painter says so, and keep their version when nothing differs', () => {
const cells: Record<string, string> = { '0,0': 'a', '1,0': 'b' };
const first = cellsVersion(cells);
// A stroke that ends where it began: written to, but the same content as before.
cells['2,0'] = 'a';
delete cells['2,0'];
cellsChanged(cells);
expect(cellsVersion(cells)).toBe(first);
// Not walked again on every question: a write nobody reported goes unseen until one is.
cells['2,0'] = 'a';
expect(cellsVersion(cells)).toBe(first);
cellsChanged(cells);
expect(cellsVersion(cells)).not.toBe(first);
});
it('a paint command and its undo are each seen at once', () => {
const m = map();
expect(solidRects(m.project, m.props, m.asset)).toEqual([{ x: 0, y: 0, w: 4, h: 1 }]);
m.stack.execute(new PaintTilesCommand(m.asset.id, m.layer.id, [{ x: 0, y: 3, tileId: m.boxId }]));
expect(solidRects(m.project, m.props, m.asset)).toEqual([
{ x: 0, y: 0, w: 4, h: 1 },
{ x: 0, y: 3, w: 1, h: 1 },
]);
m.stack.undo();
expect(solidRects(m.project, m.props, m.asset)).toEqual([{ x: 0, y: 0, w: 4, h: 1 }]);
});
it('the cache hands out what it made for a key, and forgets the oldest once full', () => {
const memo = new KeyedMemo<number[]>(2);
const make = vi.fn(() => [1]);
@@ -119,12 +151,14 @@ describe('what a tilemap works out is remembered while its content stays', () =>
const rects = solidRects(m.project, m.props, m.asset);
expect(rects).toEqual([{ x: 0, y: 0, w: 4, h: 1 }]);
m.layer.cells['0,3'] = m.boxId;
cellsChanged(m.layer.cells);
expect(solidRects(m.project, m.props, m.asset)).toEqual([
{ x: 0, y: 0, w: 4, h: 1 },
{ x: 0, y: 3, w: 1, h: 1 },
]);
expect(layerTiles(m.project, m.props, m.layer).map((t) => `${t.x},${t.y}`)).toContain('0,3');
delete m.layer.cells['1,2'];
cellsChanged(m.layer.cells);
expect(solidPolygons(m.project, m.props, m.asset)).toEqual([]);
});
@@ -155,6 +189,7 @@ describe('what a tilemap works out is remembered while its content stays', () =>
const first = liveLayers(m.asset, edits)[0]!;
expect(liveLayers(m.asset, edits)[0]).toBe(first);
m.layer.cells['2,3'] = m.boxId;
cellsChanged(m.layer.cells);
const painted = liveLayers(m.asset, edits)[0]!;
expect(painted).not.toBe(first);
expect(painted.cells['2,3']).toBe(m.boxId);
+29 -1
View File
@@ -13,9 +13,10 @@ import { findAsset } from '../../src/core/model/Project';
import { frameSortLine } from '../../src/core/model/texture';
import { TILE_SORT_OFFSET_KEY, tileSortOffset } from '../../src/core/model/tile';
import { deserializeProject, serializeProject } from '../../src/core/store/serialize';
import { type DrawSlot, drawSlots } from '../../src/viewport/drawOrder';
import { type DrawSlot, drawSlots, layerRows } from '../../src/viewport/drawOrder';
import { collectHolderItems, collectWorldItems } from '../../src/viewport/items';
import { stackAt } from '../../src/viewport/pick';
import { groupByTile } from '../../src/viewport/tilemapMesh';
import { sortLineAt, sortLineY } from '../../src/editor/texture/sheetView';
import { makeSpriteScene, place, roundTrip, startWorld } from '../helpers';
@@ -148,6 +149,33 @@ describe('a tilemap layer sorted by Y (#228)', () => {
expect(sceneOrder(plain)).toEqual(['map', 'Ground', 'Trees 4', 'box', 'Trees 5', 'Trees 8']);
});
it('hands out the very same rows while cells and offsets stay, and new ones when either changes', () => {
const s = makeScene(-80);
s.sortTrees();
const rows = () => {
const draw = collectHolderItems(s.f.project, s.f.sceneOf(), 0).items.find(
(item) => item.id === s.mapObject,
)!.tilemap!;
return layerRows(
draw,
draw.layers.find((layer) => layer.id === s.trees)!,
);
};
const first = rows();
expect(rows()).toBe(first);
expect([...first.keys()]).toEqual([5, 8]);
expect(groupByTile(first.get(5)!)).toBe(groupByTile(rows().get(5)!));
s.f.stack.execute(new SetAssetPropertyCommand(s.crown, TILE_SORT_OFFSET_KEY, 0));
const moved = rows();
expect(moved).not.toBe(first);
expect([...moved.keys()]).toEqual([4, 5, 8]);
s.f.stack.execute(new PaintTilesCommand(s.mapId, s.trees, [{ x: 3, y: 9, tileId: s.crown }]));
expect(rows()).not.toBe(moved);
expect([...rows().keys()]).toEqual([4, 5, 8, 9]);
});
it('sorts objects on that z among each other by their feet, too', () => {
const s = makeScene(100);
s.sortTrees();