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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(tilemap): a saved map says which encoding it was painted under
esengine7be4d9d363f5
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 160961442..978140819 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 84 beta · 1514 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"e59728e2336b5b14"+"7e0589f085f150f6"```## ANCHOR_AXES — const @experimentaldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 7659cb35f..0cdfe7764 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 89 beta · 1533 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"e59728e2336b5b14"+"7e0589f085f150f6"```## ANCHOR_AXES — const @experimentaldiff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.tsindex 4a84f05b9..a45a5ee30 100644--- a/sdk/src/ecs/component.generated.ts+++ b/sdk/src/ecs/component.generated.ts@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to* run on mismatch, because mismatched offsets read the wrong heap bytes.*/-export const ABI_LAYOUT_HASH = 'e59728e2336b5b14';+export const ABI_LAYOUT_HASH = '7e0589f085f150f6';/*** One asset-valued field of a component: which field, and what kind ofdiff --git a/sdk/src/tilemap/chunkCodec.ts b/sdk/src/tilemap/chunkCodec.tsindex 2cf218e28..952df04de 100644--- a/sdk/src/tilemap/chunkCodec.ts+++ b/sdk/src/tilemap/chunkCodec.ts@@ -5,11 +5,23 @@* @brief Decode the `tilemap_exportChunks` blob so the SDK can* read painted tiles back — used to derive runtime collision from a tilemap's* collidable tiles. Format (little-endian, base64url):- * u32 magic 'ESTM' · u32 chunkCount · per chunk: i32 x, i32 y, u16 tiles[256]- * (CHUNK_SIZE = 16; empty chunks are omitted by the exporter.)+ * u32 magic 'TMAP' · u16 chunkSize, idMask, flipH, flipV, flipD, reserved+ * · u32 chunkCount · per chunk: i32 x, i32 y, u16 tiles[chunkSize²]+ * Empty chunks are omitted by the exporter.+ *+ * A saved map outlives the binary that wrote it, and the ABI hash only+ * pairs a binary with a bundle. So the blob says which encoding it was+ * written under and a reader whose own differs REFUSES: the same bytes+ * would parse and mean other tiles. 'ESTM' is the older magic, which+ * carries no header and means exactly the frozen `TILEMAP_V1_*` values.*/-import { CHUNK_SIZE } from '../wasm/constants.generated';+import {+ CHUNK_SIZE, TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D,+ TILEMAP_BLOB_MAGIC_V1, TILEMAP_BLOB_MAGIC_V2,+ TILEMAP_V1_CHUNK_SIZE, TILEMAP_V1_ID_MASK,+ TILEMAP_V1_FLIP_H, TILEMAP_V1_FLIP_V, TILEMAP_V1_FLIP_D,+} from '../wasm/constants.generated';/*** Tiles per chunk side, from the C++ `CHUNK_SIZE` that owns it. Generated, so@@ -18,7 +30,15 @@ import { CHUNK_SIZE } from '../wasm/constants.generated';*/export { CHUNK_SIZE };const CHUNK_TILES = CHUNK_SIZE * CHUNK_SIZE;-const ESTM_MAGIC = 0x4d545345;++/** The chunk stride and cell split a blob has to have been written under. */+const RUNNING = [CHUNK_SIZE, TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D];+const V1 = [TILEMAP_V1_CHUNK_SIZE, TILEMAP_V1_ID_MASK,+ TILEMAP_V1_FLIP_H, TILEMAP_V1_FLIP_V, TILEMAP_V1_FLIP_D];+const V2_HEADER_BYTES = 4 + 2 * 6 + 4;+const V1_HEADER_BYTES = 8;++const sameEncoding = (a: number[]): boolean => a.every((v, i) => v === RUNNING[i]);/** One decoded chunk: its chunk-grid coords + the 16×16 row-major tile ids. */export interface DecodedChunk {@@ -64,13 +84,24 @@ export function decodeTilemapChunks(blob: string): DecodedChunk[] {} catch {return [];}- if (bytes.byteLength < 8) return [];+ if (bytes.byteLength < V1_HEADER_BYTES) return [];const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);- let off = 0;- if (dv.getUint32(off, true) !== ESTM_MAGIC) return [];- off += 4;- const count = dv.getUint32(off, true);- off += 4;+ const magic = dv.getUint32(0, true);+ let wrote: number[];+ let off: number;+ if (magic === TILEMAP_BLOB_MAGIC_V2) {+ if (bytes.byteLength < V2_HEADER_BYTES) return [];+ wrote = [0, 1, 2, 3, 4].map((i) => dv.getUint16(4 + i * 2, true));+ off = V2_HEADER_BYTES;+ } else if (magic === TILEMAP_BLOB_MAGIC_V1) {+ wrote = V1;+ off = V1_HEADER_BYTES;+ } else {+ return [];+ }+ // Refused, not decoded: these bytes would parse into different tiles.+ if (!sameEncoding(wrote)) return [];+ const count = dv.getUint32(off - 4, true);const chunks: DecodedChunk[] = [];const perChunk = 8 + CHUNK_TILES * 2;for (let i = 0; i < count; i++) {diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.tsindex 2ccebb860..a08dc1887 100644--- a/sdk/src/tilemap/tilemapPlugin.ts+++ b/sdk/src/tilemap/tilemapPlugin.ts@@ -159,7 +159,13 @@ export class TilemapRuntime {importData: (entity, outOfBand) => {const blob = outOfBand.chunks;if (typeof blob === 'string' && blob !== '') {- TilemapAPI.importChunks(entity, blob);+ // The engine refuses a map written under another cell+ // encoding rather than decoding it into other tiles, and+ // the only way that refusal is heard is here.+ if (!TilemapAPI.importChunks(entity, blob)) {+ log.error('tilemap', 'the saved map was refused — it is damaged, or was'+ + ' painted under a different cell encoding. The layer loads empty.');+ }}const ids = outOfBand.collidableTileIds;if (Array.isArray(ids) && ids.length > 0) {diff --git a/sdk/src/wasm/constants.generated.ts b/sdk/src/wasm/constants.generated.tsindex 9a8baed84..0a2b35be9 100644--- a/sdk/src/wasm/constants.generated.ts+++ b/sdk/src/wasm/constants.generated.ts@@ -17,6 +17,27 @@ export const CHUNK_SIZE = 16;/** C++ `kColorLutSize` in `src/esengine/particle/ParticleSystem.hpp`. */export const GRADIENT_LUT_SIZE = 32;+/** C++ `BLOB_MAGIC_V1` in `src/esengine/tilemap/ChunkBlob.hpp`. */+export const TILEMAP_BLOB_MAGIC_V1 = 0x4d545345;++/** C++ `BLOB_MAGIC_V2` in `src/esengine/tilemap/ChunkBlob.hpp`. */+export const TILEMAP_BLOB_MAGIC_V2 = 0x50414d54;++/** C++ `V1_CHUNK_SIZE` in `src/esengine/tilemap/ChunkBlob.hpp`. */+export const TILEMAP_V1_CHUNK_SIZE = 16;++/** C++ `V1_TILE_FLIP_D` in `src/esengine/tilemap/ChunkBlob.hpp`. */+export const TILEMAP_V1_FLIP_D = 0x8000;++/** C++ `V1_TILE_FLIP_H` in `src/esengine/tilemap/ChunkBlob.hpp`. */+export const TILEMAP_V1_FLIP_H = 0x2000;++/** C++ `V1_TILE_FLIP_V` in `src/esengine/tilemap/ChunkBlob.hpp`. */+export const TILEMAP_V1_FLIP_V = 0x4000;++/** C++ `V1_TILE_ID_MASK` in `src/esengine/tilemap/ChunkBlob.hpp`. */+export const TILEMAP_V1_ID_MASK = 0x1fff;+/** C++ `TILE_FLIP_D` in `src/esengine/tilemap/TilemapSystem.hpp`. */export const TILE_FLIP_D = 0x8000;diff --git a/sdk/tests/chunk-blob.test.ts b/sdk/tests/chunk-blob.test.tsnew file mode 100644index 000000000..b456f67c1--- /dev/null+++ b/sdk/tests/chunk-blob.test.ts@@ -0,0 +1,119 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The saved form of a painted map, and what it says about its own+ * encoding.+ *+ * A `.esscene` outlives the binary that wrote it, and the ABI layout hash only+ * pairs a binary with a bundle. Widening the id mask by one bit leaves every+ * byte where it was, so a map painted before it reads as different tiles with+ * nothing failing anywhere — which is what these refuse.+ *+ * This is the reading half. The engine writes the blob and reads it back+ * through the same header, which `tests/tilemap/test_tilemap.cpp` holds: the+ * bindings abort headless, so there is no round trip to be had from here.+ */+import { describe, it, expect } from 'vitest';+import { decodeTilemapChunks, CHUNK_SIZE } from '../src/tilemap/chunkCodec';+import {+ TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D,+ TILEMAP_BLOB_MAGIC_V1, TILEMAP_BLOB_MAGIC_V2,+ TILEMAP_V1_CHUNK_SIZE, TILEMAP_V1_ID_MASK,+ TILEMAP_V1_FLIP_H, TILEMAP_V1_FLIP_V, TILEMAP_V1_FLIP_D,+} from '../src/wasm/constants.generated';++const TILES = CHUNK_SIZE * CHUNK_SIZE;++function toBase64Url(buf: ArrayBuffer): string {+ let bin = '';+ for (const b of new Uint8Array(buf)) bin += String.fromCharCode(b);+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_');+}++/** The older magic: chunks, and no word about how to read them. */+function v1Blob(tiles: Uint16Array, chunkSize = CHUNK_SIZE): string {+ const per = 8 + chunkSize * chunkSize * 2;+ const dv = new DataView(new ArrayBuffer(8 + per));+ dv.setUint32(0, TILEMAP_BLOB_MAGIC_V1, true);+ dv.setUint32(4, 1, true);+ dv.setInt32(8, 3, true);+ dv.setInt32(12, -2, true);+ for (let i = 0; i < chunkSize * chunkSize; i++) dv.setUint16(16 + i * 2, tiles[i] ?? 0, true);+ return toBase64Url(dv.buffer);+}++/** The versioned magic, written under whatever encoding is passed. */+function v2Blob(tiles: Uint16Array, enc: number[] = [CHUNK_SIZE, TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D]): string {+ const side = enc[0]!;+ const per = 8 + side * side * 2;+ const dv = new DataView(new ArrayBuffer(20 + per));+ dv.setUint32(0, TILEMAP_BLOB_MAGIC_V2, true);+ for (let i = 0; i < 5; i++) dv.setUint16(4 + i * 2, enc[i]!, true);+ dv.setUint16(14, 0, true);+ dv.setUint32(16, 1, true);+ dv.setInt32(20, 3, true);+ dv.setInt32(24, -2, true);+ for (let i = 0; i < side * side; i++) dv.setUint16(28 + i * 2, tiles[i] ?? 0, true);+ return toBase64Url(dv.buffer);+}++function painted(): Uint16Array {+ const tiles = new Uint16Array(TILES);+ tiles[0] = 5;+ tiles[CHUNK_SIZE + 1] = 7 | TILE_FLIP_H;+ return tiles;+}++describe('a saved map says which encoding it was painted under', () => {+ it('reads the older magic, which is every scene painted so far', () => {+ const chunks = decodeTilemapChunks(v1Blob(painted()));+ expect(chunks).toHaveLength(1);+ expect(chunks[0]).toMatchObject({ x: 3, y: -2 });+ expect([chunks[0]!.tiles[0], chunks[0]!.tiles[CHUNK_SIZE + 1]]).toEqual([5, 7 | TILE_FLIP_H]);+ });++ it('reads the versioned magic to the same chunks', () => {+ expect(decodeTilemapChunks(v2Blob(painted()))).toEqual(decodeTilemapChunks(v1Blob(painted())));+ });++ /**+ * The bit that would be silent. A 14-bit id mask leaves every byte where it+ * is: the same blob parses, and each cell that carried a flip flag becomes a+ * different tile.+ */+ it('refuses a map painted under a wider id mask', () => {+ const wider = [CHUNK_SIZE, 0x3fff, 0x4000, 0x8000, 0x0000];+ expect(decodeTilemapChunks(v2Blob(painted(), wider))).toEqual([]);+ });++ /**+ * A LARGER side on purpose: a smaller one runs the reader off the end and+ * the truncation guard answers, so that version of this passes with the+ * encoding check taken out. At 32 the reader has bytes enough to hand back+ * 256 of them as a chunk.+ */+ it('refuses a map painted at another chunk size', () => {+ const wide = [32, TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D];+ const tiles = new Uint16Array(32 * 32);+ tiles[0] = 5;+ expect(decodeTilemapChunks(v2Blob(tiles, wide))).toEqual([]);+ });++ it('refuses a blob that is not one of ours', () => {+ const dv = new DataView(new ArrayBuffer(64));+ dv.setUint32(0, 0x12345678, true);+ expect(decodeTilemapChunks(toBase64Url(dv.buffer))).toEqual([]);+ });++ /**+ * What the older magic MEANT, as literals. Re-pointing these at the live+ * constants would make every map painted so far read as whatever the engine+ * is now — the one failure this format cannot detect for itself.+ */+ it('remembers the older magic as history, not as configuration', () => {+ expect([TILEMAP_V1_CHUNK_SIZE, TILEMAP_V1_ID_MASK,+ TILEMAP_V1_FLIP_H, TILEMAP_V1_FLIP_V, TILEMAP_V1_FLIP_D])+ .toEqual([16, 0x1fff, 0x2000, 0x4000, 0x8000]);+ });+});+diff --git a/src/esengine/bindings/TilemapBindings.cpp b/src/esengine/bindings/TilemapBindings.cppindex e4e3d93b3..c5cb96eb1 100644--- a/src/esengine/bindings/TilemapBindings.cpp+++ b/src/esengine/bindings/TilemapBindings.cpp@@ -7,6 +7,7 @@#include "ActiveContext.hpp"#include "BoundarySpan.hpp"#include "../tilemap/TilemapSystem.hpp"+#include "../tilemap/ChunkBlob.hpp"#include "../renderer/frame/RenderContext.hpp"#include "../renderer/frame/RenderFrame.hpp"#include "../renderer/draw/ImmediateDraw.hpp"@@ -202,11 +203,12 @@ bool base64Decode(const std::string& in, std::vector<u8>& out) {// Exports every non-empty chunk of `entity` as a single base64-encoded// blob. Layout (all little-endian):-// u32 magic = 'ESTM' (header — version-check on import)+// u32 magic = 'TMAP'+// u16 chunkSize, idMask, flipH, flipV, flipD, reserved(0)// u32 chunkCount// repeated for each chunk:// i32 chunkX, i32 chunkY-// u16 tiles[CHUNK_SIZE * CHUNK_SIZE]+// u16 tiles[chunkSize * chunkSize]// Empty chunks are skipped to keep the payload compact for sparse maps.std::string tilemap_exportChunks(u32 entity) {auto e = Entity::fromRaw(entity);@@ -223,19 +225,17 @@ std::string tilemap_exportChunks(u32 entity) {if (anyTile) nonEmpty.emplace_back(coord, &chunk);}- const u32 magic = 0x4D545345u; // 'ESTM'const u32 count = static_cast<u32>(nonEmpty.size());const usize perChunk = sizeof(i32) * 2+ tilemap::CHUNK_SIZE * tilemap::CHUNK_SIZE * sizeof(u16);std::vector<u8> raw;- raw.reserve(sizeof(u32) * 2 + count * perChunk);+ raw.reserve(tilemap::BLOB_HEADER_V2_BYTES + count * perChunk);auto append = [&](const void* p, usize n) {const u8* b = static_cast<const u8*>(p);raw.insert(raw.end(), b, b + n);};- append(&magic, sizeof(magic));- append(&count, sizeof(count));+ tilemap::appendBlobHeader(raw, count);for (const auto& [coord, chunk] : nonEmpty) {append(&coord.x, sizeof(coord.x));append(&coord.y, sizeof(coord.y));@@ -260,7 +260,7 @@ bool tilemap_importChunks(u32 entity, const std::string& encoded) {std::vector<u8> raw;if (!base64Decode(encoded, raw)) return false;- if (raw.size() < sizeof(u32) * 2) return false;+ if (raw.size() < tilemap::BLOB_HEADER_V1_BYTES) return false;auto read = [&raw](usize offset, void* out, usize n) -> bool {if (offset + n > raw.size()) return false;@@ -268,19 +268,16 @@ bool tilemap_importChunks(u32 entity, const std::string& encoded) {return true;};- u32 magic = 0;- u32 count = 0;- if (!read(0, &magic, sizeof(magic))) return false;- if (magic != 0x4D545345u) return false;- if (!read(sizeof(u32), &count, sizeof(count))) return false;+ tilemap::BlobHeader header{};+ if (!tilemap::parseBlobHeader(raw.data(), raw.size(), header)) return false;const usize perChunk = sizeof(i32) * 2+ tilemap::CHUNK_SIZE * tilemap::CHUNK_SIZE * sizeof(u16);- if (raw.size() < sizeof(u32) * 2 + static_cast<usize>(count) * perChunk) return false;+ if (raw.size() < header.payloadAt + static_cast<usize>(header.chunkCount) * perChunk) return false;layer->chunks.clear();- usize cursor = sizeof(u32) * 2;- for (u32 i = 0; i < count; ++i) {+ usize cursor = header.payloadAt;+ for (u32 i = 0; i < header.chunkCount; ++i) {i32 cx = 0, cy = 0;if (!read(cursor, &cx, sizeof(cx))) return false;cursor += sizeof(cx);diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex 0c8dcfcda..0981c97dd 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -3116,7 +3116,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif// ABI Hash -- runtime handshake against the SDK bundle// =============================================================================-static const char* kEsAbiLayoutHash = "e59728e2336b5b14";+static const char* kEsAbiLayoutHash = "7e0589f085f150f6";std::string esengineGetAbiLayoutHash() {return std::string(kEsAbiLayoutHash);diff --git a/src/esengine/tilemap/ChunkBlob.hpp b/src/esengine/tilemap/ChunkBlob.hppnew file mode 100644index 000000000..c4803bb2b--- /dev/null+++ b/src/esengine/tilemap/ChunkBlob.hpp@@ -0,0 +1,127 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ChunkBlob.hpp — the saved form of a painted tilemap, and what it says+ * about the encoding it was written under.+ *+ * The ABI layout hash pairs a BINARY with a BUNDLE. A saved map is neither: it+ * outlives both, and the cell encoding is not written anywhere in it. Widening+ * the id mask by one bit therefore reads every `.esscene` ever painted into+ * different tiles — every check passes, the byte layout is unchanged, and only+ * the picture is wrong.+ *+ * So the blob carries its own encoding, and a reader whose encoding differs+ * REFUSES rather than decoding. The legacy magic has no such header; it means+ * exactly the frozen values below, which is why those are literals and never a+ * reference to the live constants.+ */+#pragma once++#include "../core/Types.hpp"+#include "../core/Reflection.hpp"+#include "TilemapSystem.hpp"++#include <cstring>+#include <vector>++namespace esengine {+namespace tilemap {++/** 'ESTM' — chunks only, and the encoding of the day it was written. */+ES_CONST(hex, ts=TILEMAP_BLOB_MAGIC_V1)+static constexpr u32 BLOB_MAGIC_V1 = 0x4D545345;++/** 'TMAP' — the same chunks behind a header that says how to read them. */+ES_CONST(hex, ts=TILEMAP_BLOB_MAGIC_V2)+static constexpr u32 BLOB_MAGIC_V2 = 0x50414D54;++// What 'ESTM' meant. History, not configuration: pointing these at the live+// constants would make every old map read as whatever the engine is now, which+// is the failure this file exists to refuse.+ES_CONST(ts=TILEMAP_V1_CHUNK_SIZE)+static constexpr u32 V1_CHUNK_SIZE = 16;+ES_CONST(hex, ts=TILEMAP_V1_ID_MASK)+static constexpr u16 V1_TILE_ID_MASK = 0x1FFF;+ES_CONST(hex, ts=TILEMAP_V1_FLIP_H)+static constexpr u16 V1_TILE_FLIP_H = 0x2000;+ES_CONST(hex, ts=TILEMAP_V1_FLIP_V)+static constexpr u16 V1_TILE_FLIP_V = 0x4000;+ES_CONST(hex, ts=TILEMAP_V1_FLIP_D)+static constexpr u16 V1_TILE_FLIP_D = 0x8000;++/** How a saved map has to be read: the chunk stride and the split of a cell. */+struct CellEncoding {+ u16 chunkSize;+ u16 idMask;+ u16 flipH;+ u16 flipV;+ u16 flipD;++ bool operator==(const CellEncoding& o) const {+ return chunkSize == o.chunkSize && idMask == o.idMask+ && flipH == o.flipH && flipV == o.flipV && flipD == o.flipD;+ }+};++inline CellEncoding runningEncoding() {+ return { static_cast<u16>(CHUNK_SIZE), TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D };+}++/** What the legacy magic means, which is a fact about the past. */+inline CellEncoding v1Encoding() {+ return { static_cast<u16>(V1_CHUNK_SIZE), V1_TILE_ID_MASK,+ V1_TILE_FLIP_H, V1_TILE_FLIP_V, V1_TILE_FLIP_D };+}++inline constexpr usize BLOB_HEADER_V1_BYTES = sizeof(u32) * 2;+inline constexpr usize BLOB_HEADER_V2_BYTES = sizeof(u32) + sizeof(u16) * 6 + sizeof(u32);++/** Where the chunks begin, and how many of them the header claims. */+struct BlobHeader {+ usize payloadAt;+ u32 chunkCount;+};++inline void appendBlobHeader(std::vector<u8>& out, u32 chunkCount) {+ const CellEncoding enc = runningEncoding();+ const u16 fields[6] = { enc.chunkSize, enc.idMask, enc.flipH, enc.flipV, enc.flipD, 0 };+ auto put = [&out](const void* p, usize n) {+ const u8* b = static_cast<const u8*>(p);+ out.insert(out.end(), b, b + n);+ };+ put(&BLOB_MAGIC_V2, sizeof(BLOB_MAGIC_V2));+ put(fields, sizeof(fields));+ put(&chunkCount, sizeof(chunkCount));+}++/**+ * The header, or a refusal. A blob written under another encoding parses+ * perfectly and means other tiles, so it is refused rather than decoded — and+ * the legacy magic carries no header at all, which is why it means v1 and not+ * "whatever this engine is now".+ */+inline bool parseBlobHeader(const u8* raw, usize size, BlobHeader& out) {+ if (size < BLOB_HEADER_V1_BYTES) return false;+ u32 magic = 0;+ std::memcpy(&magic, raw, sizeof(magic));++ CellEncoding wrote{};+ if (magic == BLOB_MAGIC_V2) {+ if (size < BLOB_HEADER_V2_BYTES) return false;+ u16 fields[5] = {};+ std::memcpy(fields, raw + sizeof(u32), sizeof(fields));+ wrote = { fields[0], fields[1], fields[2], fields[3], fields[4] };+ out.payloadAt = BLOB_HEADER_V2_BYTES;+ } else if (magic == BLOB_MAGIC_V1) {+ wrote = v1Encoding();+ out.payloadAt = BLOB_HEADER_V1_BYTES;+ } else {+ return false;+ }+ if (!(wrote == runningEncoding())) return false;+ std::memcpy(&out.chunkCount, raw + out.payloadAt - sizeof(u32), sizeof(out.chunkCount));+ return true;+}++} // namespace tilemap+} // namespace esenginediff --git a/tests/tilemap/test_tilemap.cpp b/tests/tilemap/test_tilemap.cppindex 4d1e437f3..ccc19c908 100644--- a/tests/tilemap/test_tilemap.cpp+++ b/tests/tilemap/test_tilemap.cpp@@ -3,6 +3,7 @@#include <esengine/tilemap/TilemapSystem.hpp>#include <esengine/tilemap/TileFlip.hpp>+#include <esengine/tilemap/ChunkBlob.hpp>using namespace esengine;using namespace esengine::tilemap;@@ -421,3 +422,59 @@ TEST_CASE("tileset_atlas_cells") {CHECK(atlasCells(16.0f, 4096.0f, 32.0f, 0.0f) == 0);CHECK(atlasCells(64.0f, 0.0f, 0.0f, 0.0f) == 0);}+++// A saved map outlives the binary that wrote it, and the ABI layout hash pairs a+// binary with a bundle only. The header is where that gap is closed.+TEST_CASE("tilemap_blob_header") {+ SUBCASE("what it writes, it reads back") {+ std::vector<u8> raw;+ appendBlobHeader(raw, 7);+ CHECK(raw.size() == BLOB_HEADER_V2_BYTES);++ BlobHeader header{};+ REQUIRE(parseBlobHeader(raw.data(), raw.size(), header));+ CHECK(header.chunkCount == 7);+ CHECK(header.payloadAt == BLOB_HEADER_V2_BYTES);+ }++ SUBCASE("the older magic means the encoding it was written under, and still reads") {+ std::vector<u8> raw(BLOB_HEADER_V1_BYTES);+ const u32 count = 3;+ std::memcpy(raw.data(), &BLOB_MAGIC_V1, sizeof(u32));+ std::memcpy(raw.data() + sizeof(u32), &count, sizeof(count));++ BlobHeader header{};+ REQUIRE(parseBlobHeader(raw.data(), raw.size(), header));+ CHECK(header.chunkCount == 3);+ CHECK(header.payloadAt == BLOB_HEADER_V1_BYTES);+ // Which is only sound while the frozen values ARE the running ones.+ CHECK(v1Encoding() == runningEncoding());+ }++ // The bit that would otherwise be silent: a wider id mask leaves every byte+ // where it is, so the blob parses and each flipped cell becomes another tile.+ SUBCASE("a map painted under another encoding is refused, not decoded") {+ std::vector<u8> raw;+ appendBlobHeader(raw, 1);+ u16 wider = 0x3FFF;+ std::memcpy(raw.data() + sizeof(u32) + sizeof(u16), &wider, sizeof(wider));++ BlobHeader header{};+ CHECK_FALSE(parseBlobHeader(raw.data(), raw.size(), header));+ }++ SUBCASE("a blob that is not one of ours, and one that stops mid-header") {+ std::vector<u8> raw;+ appendBlobHeader(raw, 1);+ const u32 alien = 0x12345678;+ std::memcpy(raw.data(), &alien, sizeof(alien));+ BlobHeader header{};+ CHECK_FALSE(parseBlobHeader(raw.data(), raw.size(), header));++ std::vector<u8> cut;+ appendBlobHeader(cut, 1);+ cut.resize(BLOB_HEADER_V2_BYTES - 2);+ CHECK_FALSE(parseBlobHeader(cut.data(), cut.size(), header));+ }+}diff --git a/tools/lib/contractFacts.mjs b/tools/lib/contractFacts.mjsindex 08e1d3e05..8ceee4cab 100644--- a/tools/lib/contractFacts.mjs+++ b/tools/lib/contractFacts.mjs@@ -201,10 +201,23 @@ export const FACTS = [{ path: 'sdk/tests/cpp-contract.test.ts', how: 'test', probe: /tilemap cell encoding/ },],digest: { name: 'eht-abi-layout-hash', path: 'tools/eht/constants.py', probe: /CONST /},- owed: 'the hash pairs a BINARY with a BUNDLE; it says nothing about a saved map.'- + ' This is a file format, so widening the id mask still reads every older'- + ' `.esscene` into the wrong cells — that half needs a format version of its'- + ' own, not an ABI comparison.',+ },+ {+ id: 'tilemapBlobFormat',+ what: 'The saved form of a painted map, and the cell encoding it says it was painted under.',+ surface: 'project-asset-format',+ // A saved map outlives both halves the ABI hash pairs, so it carries the+ // encoding it was painted under and a reader whose own differs refuses+ // it. The frozen `V1_*` values are what the older magic MEANT.+ authors: [+ { path: 'src/esengine/tilemap/ChunkBlob.hpp', probe: /BLOB_MAGIC_V2/, kind: 'semantic' },+ ],+ projections: ['sdk/src/wasm/constants.generated.ts'],+ verification: [+ { path: 'tests/tilemap/test_tilemap.cpp', how: 'test', probe: /tilemap_blob_header/ },+ { path: 'sdk/tests/chunk-blob.test.ts', how: 'test', probe: /refuses a map painted/ },+ ],+ digest: { name: 'eht-abi-layout-hash', path: 'tools/eht/constants.py', probe: /CONST /},},{id: 'uiBaseLayer',