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): one count of what an atlas holds

esenginef2ce53b74c37
diff --git a/desktop/src/tools/tileMath.ts b/desktop/src/tools/tileMath.ts
index cdeeb6e8a..2f20ecec7 100644
--- a/desktop/src/tools/tileMath.ts
+++ b/desktop/src/tools/tileMath.ts
@@ -6,18 +6,17 @@
* Tilemap painter and the Tileset editor, which each carried a verbatim
* copy before.
*/
+import { atlasCells } from 'esengine';
-/** Columns an atlas grid fits: floor over the tile stride, honoring the outer
- * margin and inter-tile spacing. At least 1. */
+/** Columns an atlas grid fits. At least 1: a palette with no column has no cell
+ * to focus, and an atlas too small for one tile still shows the tile it has. */
export function colsFor(width: number, tileW: number, margin: number, spacing: number): number {
- const stride = tileW + spacing;
- return stride > 0 ? Math.max(1, Math.floor((width - margin + spacing) / stride)) : 1;
+ return Math.max(1, atlasCells(width, margin, tileW, spacing));
}
/** Rows an atlas grid fits (0 when the image is shorter than a single tile). */
export function rowsFor(height: number, tileH: number, margin: number, spacing: number): number {
- const stride = tileH + spacing;
- return stride > 0 ? Math.max(0, Math.floor((height - margin + spacing) / stride)) : 0;
+ return atlasCells(height, margin, tileH, spacing);
}
/** Swatch color per terrain/autotile set — set identity in the tileset editor's
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 8bcc70655..90ec4f9e7 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 65,
- "experimental": 1530,
+ "experimental": 1531,
"deprecated": 3
},
- "total": 1708,
+ "total": 1709,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index a2ce7dd4d..53d5d3779 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 58 beta · 1415 experimental · 3 deprecated
+Symbols: 113 public · 58 beta · 1416 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -9012,6 +9012,11 @@ AssetPlugin
(atlas: CookedAtlasInfo, pagePath: string): Pick<CatalogEntry, "atlas" | "frame" | "uv">
```
+## atlasCells — function @experimental
+```
+(size: number, margin: number, tileSize: number, spacing: number): number
+```
+
## audioPlugin — const @experimental
```
AudioPlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 609a7959f..ef1cd187e 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 63 beta · 1434 experimental · 3 deprecated
+Symbols: 113 public · 63 beta · 1435 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -9220,6 +9220,11 @@ AssetPlugin
(atlas: CookedAtlasInfo, pagePath: string): Pick<CatalogEntry, "atlas" | "frame" | "uv">
```
+## atlasCells — function @experimental
+```
+(size: number, margin: number, tileSize: number, spacing: number): number
+```
+
## audioPlugin — const @experimental
```
AudioPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 1f26b2727..778c1ec77 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 60 beta · 1414 experimental · 3 deprecated
+Symbols: 113 public · 60 beta · 1415 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -9007,6 +9007,11 @@ AssetPlugin
(atlas: CookedAtlasInfo, pagePath: string): Pick<CatalogEntry, "atlas" | "frame" | "uv">
```
+## atlasCells — function @experimental
+```
+(size: number, margin: number, tileSize: number, spacing: number): number
+```
+
## audioPlugin — const @experimental
```
AudioPlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 80865ce35..97608e179 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 58 beta · 1435 experimental · 3 deprecated
+Symbols: 113 public · 58 beta · 1436 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -9252,6 +9252,11 @@ AssetPlugin
(atlas: CookedAtlasInfo, pagePath: string): Pick<CatalogEntry, "atlas" | "frame" | "uv">
```
+## atlasCells — function @experimental
+```
+(size: number, margin: number, tileSize: number, spacing: number): number
+```
+
## audioPlugin — const @experimental
```
AudioPlugin
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index c79b9a6a2..deb7475e1 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 58 beta · 1425 experimental · 3 deprecated
+Symbols: 113 public · 58 beta · 1426 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -9034,6 +9034,11 @@ AssetPlugin
(atlas: CookedAtlasInfo, pagePath: string): Pick<CatalogEntry, "atlas" | "frame" | "uv">
```
+## atlasCells — function @experimental
+```
+(size: number, margin: number, tileSize: number, spacing: number): number
+```
+
## audioPlugin — const @experimental
```
AudioPlugin
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 262a3a2b2..c029cc6e8 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -543,6 +543,7 @@ export {
createTileset,
collidableTileIds,
resolveTilesetModel,
+ atlasCells,
decodeTilemapChunks,
CHUNK_SIZE,
tileCollisionOutlines,
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index dd14c8e26..08e2135f0 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -41,7 +41,7 @@ export {
type TerrainMode, type TerrainColor, type TilesetTerrain, type TilesetTileTerrain,
} from './tilesetAsset';
export {
- resolveTilesetModel,
+ resolveTilesetModel, atlasCells,
type ResolvedTileset, type TilesetModel, type TilesetModelSlot, type ResolvedTileCollision,
} from './tilesetResolve';
export {
diff --git a/sdk/src/tilemap/tilesetResolve.ts b/sdk/src/tilemap/tilesetResolve.ts
index b4c755154..95a696189 100644
--- a/sdk/src/tilemap/tilesetResolve.ts
+++ b/sdk/src/tilemap/tilesetResolve.ts
@@ -101,6 +101,20 @@ function resolveTileCollision(c: TilesetCollision, tw: number, th: number): Reso
return out;
}
+/**
+ * Cells of `tileSize` along an atlas axis of `size`: n span `2*margin +
+ * n*tileSize + (n-1)*spacing`, Tiled's margin bordering both sides. The palette
+ * grid, the id spans below and the renderer's bounds check are all this one
+ * count — offering a cell the id space lacks paints another tileset's tile.
+ *
+ * @experimental
+ */
+export function atlasCells(size: number, margin: number, tileSize: number, spacing: number): number {
+ const step = tileSize + spacing;
+ if (step <= 0) return 0;
+ return Math.max(0, Math.floor((size - 2 * margin + spacing) / step));
+}
+
/**
* Tiles in a tileset — the span its global ids occupy. Explicit `tileCount` wins;
* else derive `columns × rows` from the atlas texture height (the correct span for
@@ -110,10 +124,8 @@ function resolveTileCollision(c: TilesetCollision, tw: number, th: number): Reso
function tilesetCount(asset: TilesetAsset, textureHeight?: number): number {
if (typeof asset.tileCount === 'number' && asset.tileCount > 0) return asset.tileCount;
if (typeof textureHeight === 'number' && textureHeight > 0) {
- const th = asset.tileHeight || 1;
- const m = asset.margin || 0;
- const sp = asset.spacing || 0;
- const rows = Math.max(1, Math.floor((textureHeight - 2 * m + sp) / (th + sp)));
+ const rows = Math.max(1, atlasCells(
+ textureHeight, asset.margin || 0, asset.tileHeight || 1, asset.spacing || 0));
return Math.max(1, asset.columns * rows);
}
let max = 0;
diff --git a/sdk/tests/tileset-resolve.test.ts b/sdk/tests/tileset-resolve.test.ts
index 42b5e781a..c9df8c5b8 100644
--- a/sdk/tests/tileset-resolve.test.ts
+++ b/sdk/tests/tileset-resolve.test.ts
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { readFileSync } from 'node:fs';
import { describe, it, expect } from 'vitest';
-import { resolveTilesetModel, type ResolvedTileset } from '../src/tilemap/tilesetResolve';
+import { resolveTilesetModel, atlasCells, type ResolvedTileset } from '../src/tilemap/tilesetResolve';
import type { TilesetAsset } from '../src/tilemap/tilesetAsset';
function tileset(over: Partial<TilesetAsset>): TilesetAsset {
@@ -85,3 +86,41 @@ describe('resolveTilesetModel', () => {
expect(m.collidableTileIds).toEqual([3, 4]); // a tile 3 → 3; b tile 1 → global 4
});
});
+
+describe('atlasCells', () => {
+ // Every shipped Tiled map, read for the one thing Tiled itself decides: how
+ // many columns its atlas has. Only one of them carries a margin, and that is
+ // the case a hand-written expectation would most likely get wrong.
+ it('agrees with the column count Tiled wrote for every shipped map', () => {
+ const maps = [
+ '../../desktop/public/scenes/tilemap-spacing/map.tmj',
+ '../../desktop/public/scenes/tilemap-multiset/map.tmj',
+ '../../desktop/public/scenes/tilemap-gidobj/map.tmj',
+ '../../desktop/public/scenes/tilemap-hex/map.tmj',
+ '../../examples/tilemap-demo/assets/maps/level.tmj',
+ ];
+ let checked = 0;
+ for (const rel of maps) {
+ const map = JSON.parse(readFileSync(new URL(rel, import.meta.url), 'utf8'));
+ for (const ts of map.tilesets ?? []) {
+ if (!ts.imagewidth) continue;
+ expect(atlasCells(ts.imagewidth, ts.margin ?? 0, ts.tilewidth, ts.spacing ?? 0))
+ .toBe(ts.columns);
+ checked++;
+ }
+ }
+ expect(checked).toBeGreaterThan(4);
+ });
+
+ it("a Tiled margin borders both sides of the atlas", () => {
+ // Three 32px tiles with 2px gaps inside a 4px border span 4+96+4+4 = 108.
+ expect(atlasCells(108, 4, 32, 2)).toBe(3);
+ // At 104 a third tile would have to eat the far border, so only two fit.
+ expect(atlasCells(104, 4, 32, 2)).toBe(2);
+ });
+
+ it('answers zero rather than a negative count', () => {
+ expect(atlasCells(16, 4096, 32, 0)).toBe(0);
+ expect(atlasCells(64, 0, 0, 0)).toBe(0);
+ });
+});
diff --git a/src/esengine/tilemap/TilesetTable.hpp b/src/esengine/tilemap/TilesetTable.hpp
index 9021264b9..adc98385b 100644
--- a/src/esengine/tilemap/TilesetTable.hpp
+++ b/src/esengine/tilemap/TilesetTable.hpp
@@ -26,23 +26,23 @@ struct TilesetSlot {
};
/**
- * Index of the slot owning @p id — the one with the largest first_id <= id.
- * Returns -1 if none (id below the first slot, or empty table). @p slots must be
- * sorted ascending by first_id (TilemapSystem::setTilesets guarantees this).
- */
-/**
- * Cells of @p tileSize along an atlas axis of @p size: n span margin +
- * n*tileSize + (n-1)*spacing. Past them a tile samples some other tile, so the
- * renderer skips it; the palette counts the same way (desktop tileMath.ts) and
- * the two must agree. Zero when the margin leaves none — that float would trap.
+ * Cells of @p tileSize along an atlas axis of @p size: n span 2*margin +
+ * n*tileSize + (n-1)*spacing (Tiled's margin borders both sides). Past them a
+ * tile samples some other tile, so it is skipped. Must agree with the SDK's
+ * `atlasCells`; zero when the margin leaves none, a float that would trap.
*/
inline uint32_t atlasCells(float size, float margin, float tileSize, float spacing) {
float step = tileSize + spacing;
if (step <= 0.0f) return 0;
- float n = (size - margin + spacing) / step;
+ float n = (size - 2.0f * margin + spacing) / step;
return n > 0.0f ? static_cast<uint32_t>(n) : 0;
}
+/**
+ * Index of the slot owning @p id — the one with the largest first_id <= id.
+ * Returns -1 if none (id below the first slot, or empty table). @p slots must be
+ * sorted ascending by first_id (TilemapSystem::setTilesets guarantees this).
+ */
inline int resolveTilesetSlot(const std::vector<TilesetSlot>& slots, uint16_t id) {
int found = -1;
for (std::size_t i = 0; i < slots.size(); ++i) {
diff --git a/tests/tilemap/test_tilemap.cpp b/tests/tilemap/test_tilemap.cpp
index a479e3d95..4d1e437f3 100644
--- a/tests/tilemap/test_tilemap.cpp
+++ b/tests/tilemap/test_tilemap.cpp
@@ -406,10 +406,15 @@ TEST_CASE("tileset_atlas_cells") {
CHECK(atlasCells(64.0f, 0.0f, 32.0f, 0.0f) == 2);
CHECK(atlasCells(80.0f, 0.0f, 32.0f, 0.0f) == 2);
- // Tiled's margin sits before the first cell, spacing only between cells — so
- // three 32px tiles with 2px gaps and a 4px border need 4 + 96 + 4 = 104.
- CHECK(atlasCells(104.0f, 4.0f, 32.0f, 2.0f) == 3);
- CHECK(atlasCells(103.0f, 4.0f, 32.0f, 2.0f) == 2);
+ // A Tiled margin borders BOTH sides: three 32px tiles with 2px gaps inside a
+ // 4px border need 4+96+4+4 = 108. At 104 only two fit — counting the margin
+ // once says three and hands that third cell the border pixels.
+ CHECK(atlasCells(108.0f, 4.0f, 32.0f, 2.0f) == 3);
+ CHECK(atlasCells(104.0f, 4.0f, 32.0f, 2.0f) == 2);
+
+ // The tileset shipped with the spacing gate, whose own JSON says 2 columns:
+ // 4 + 16 + 8 + 16 + 4 is exactly its 48px atlas.
+ CHECK(atlasCells(48.0f, 4.0f, 16.0f, 8.0f) == 2);
// Degenerate inputs answer "no cells" rather than converting an out-of-range
// float: a margin wider than the image, and a tile with no size.