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): migrate TilemapLayer to C++ builtin
esengine7dab8482e1e5
diff --git a/sdk/src/asset/AssetFieldRegistry.ts b/sdk/src/asset/AssetFieldRegistry.tsindex ebd467420..178d152db 100644--- a/sdk/src/asset/AssetFieldRegistry.ts+++ b/sdk/src/asset/AssetFieldRegistry.ts@@ -98,7 +98,7 @@ export function initBuiltinAssetFields(): void {]);registerAssetFields('TilemapLayer', [- { field: 'texture', type: 'texture' },+ { field: 'tileset', type: 'texture' },]);registerAssetFields('TimelinePlayer', [diff --git a/sdk/src/component.ts b/sdk/src/component.tsindex 23a0bf8d8..61077a99f 100644--- a/sdk/src/component.ts+++ b/sdk/src/component.ts@@ -412,6 +412,19 @@ export interface SpineAnimationData {enabled: boolean;}+export interface TilemapLayerData {+ cellSize: Vec2;+ originOffset: Vec2;+ tileset: number;+ tilesetColumns: number;+ tilesetRows: number;+ renderLayer: number;+ tintColor: Color;+ opacity: number;+ parallaxFactor: Vec2;+ visible: boolean;+}+export interface BitmapTextData {text: string;color: Color;@@ -495,6 +508,10 @@ export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation'metaDefaults<SpineAnimationData>('SpineAnimation'));+export const TilemapLayer = defineBuiltin<TilemapLayerData>('TilemapLayer',+ metaDefaults<TilemapLayerData>('TilemapLayer')+);+// =============================================================================// ParticleEmitter Enums// =============================================================================diff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex 50f596c5d..ca579a9d2 100644--- a/sdk/src/scene.ts+++ b/sdk/src/scene.ts@@ -10,6 +10,7 @@ import { discoverSceneAssets } from './asset/discoverAssets';import { requireResourceManager } from './resourceManager';import { validateComponentData, formatValidationErrors } from './validation';import { log } from './logger';+import { TilemapAPI } from './tilemap/tilemapAPI';// =============================================================================// Types@@ -281,12 +282,25 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompo}const comp = getComponent(compData.type);if (comp) {+ // TilemapLayer carries tile chunks out-of-component as a base64 blob+ // alongside the regular field record. Strip it before validation so+ // the insert doesn't choke on the sibling field, then replay the+ // chunks through the C++ import binding once the component is in.+ let tilemapChunks: string | undefined;+ if (compData.type === 'TilemapLayer') {+ const raw = compData.data.chunks;+ if (typeof raw === 'string') tilemapChunks = raw;+ delete compData.data.chunks;+ }const errors = validateComponentData(compData.type, comp._default as Record<string, unknown>, compData.data);if (errors.length > 0) {const context = entityName ? ` (entity "${entityName}")` : '';log.warn('scene', formatValidationErrors(compData.type + context, errors));}world.insert(entity, comp, compData.data);+ if (tilemapChunks !== undefined && tilemapChunks !== '') {+ TilemapAPI.importChunks(entity as unknown as number, tilemapChunks);+ }} else {const context = entityName ? ` on entity "${entityName}"` : '';log.warn('scene', `Unknown component type: ${compData.type}${context}`);@@ -354,9 +368,14 @@ export function serializeScene(world: World, sceneName = 'scene'): SceneData {if (!comp) continue;const data = world.tryGet(entity, comp);if (data === null) continue;+ const payload = data as Record<string, unknown>;+ if (typeName === 'TilemapLayer') {+ const blob = TilemapAPI.exportChunks(entityNum);+ if (blob) payload.chunks = blob;+ }components.push({type: typeName,- data: data as Record<string, unknown>,+ data: payload,});}diff --git a/sdk/src/tilemap/components.ts b/sdk/src/tilemap/components.tsindex 87c02d845..f70dec89f 100644--- a/sdk/src/tilemap/components.ts+++ b/sdk/src/tilemap/components.ts@@ -1,47 +1,13 @@import { defineComponent } from '../component';+export { TilemapLayer, type TilemapLayerData } from '../component';+export interface TilemapData {source: string;}-export interface TilemapLayerData {- width: number;- height: number;- tileWidth: number;- tileHeight: number;- texture: number;- tilesetColumns: number;- layer: number;- tiles: number[];- infinite: boolean;- chunks: Record<string, number[]>;- tint: { r: number; g: number; b: number; a: number };- opacity: number;- visible: boolean;- parallaxFactor: { x: number; y: number };-}-export const Tilemap = defineComponent<TilemapData>('Tilemap', {source: '',}, {assetFields: [{ field: 'source', type: 'tilemap' }],});--export const TilemapLayer = defineComponent<TilemapLayerData>('TilemapLayer', {- width: 10,- height: 10,- tileWidth: 32,- tileHeight: 32,- texture: 0,- tilesetColumns: 1,- layer: 0,- tiles: [],- infinite: false,- chunks: {},- tint: { r: 1, g: 1, b: 1, a: 1 },- opacity: 1,- visible: true,- parallaxFactor: { x: 1, y: 1 },-}, {- assetFields: [{ field: 'texture', type: 'texture' }],-});diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.tsindex aae64d992..f4e33c816 100644--- a/sdk/src/tilemap/tiledLoader.ts+++ b/sdk/src/tilemap/tiledLoader.ts@@ -1,8 +1,40 @@-import { getTiledAPI } from './tilemapAPI';+import { getTiledAPI, TilemapAPI } from './tilemapAPI';import type { World } from '../world';import type { Entity } from '../types';import { TilemapLayer } from './components';import { Transform } from '../component';++// Matches TilemapSystem::CHUNK_SIZE on the C++ side.+const TILEMAP_CHUNK_SIZE = 16;++function uploadTiledLayerTiles(entity: Entity, layer: TiledLayerData): void {+ if (layer.infinite) {+ for (const chunk of layer.chunks) {+ TilemapAPI.setChunkTiles(entity, chunk.x, chunk.y, chunk.tiles, chunk.width, chunk.height);+ }+ return;+ }+ const { width, height, tiles } = layer;+ if (width <= 0 || height <= 0 || tiles.length === 0) return;+ const chunksX = Math.ceil(width / TILEMAP_CHUNK_SIZE);+ const chunksY = Math.ceil(height / TILEMAP_CHUNK_SIZE);+ const buf = new Uint16Array(TILEMAP_CHUNK_SIZE * TILEMAP_CHUNK_SIZE);+ for (let cy = 0; cy < chunksY; cy++) {+ for (let cx = 0; cx < chunksX; cx++) {+ buf.fill(0);+ const regionW = Math.min(TILEMAP_CHUNK_SIZE, width - cx * TILEMAP_CHUNK_SIZE);+ const regionH = Math.min(TILEMAP_CHUNK_SIZE, height - cy * TILEMAP_CHUNK_SIZE);+ for (let ly = 0; ly < regionH; ly++) {+ const gy = cy * TILEMAP_CHUNK_SIZE + ly;+ for (let lx = 0; lx < regionW; lx++) {+ const gx = cx * TILEMAP_CHUNK_SIZE + lx;+ buf[ly * TILEMAP_CHUNK_SIZE + lx] = tiles[gy * width + gx];+ }+ }+ TilemapAPI.setChunkTiles(entity, cx, cy, buf, regionW, regionH);+ }+ }+}import { RigidBody, BoxCollider, CircleCollider, BodyType } from '../physics/PhysicsComponents';import { mergeCollisionTiles } from './collisionMerge';import { log } from '../logger';@@ -565,20 +597,23 @@ export function loadTiledMap(const columns = firstTileset?.columns ?? 1;world.insert(entity, TilemapLayer, {- width: layer.width,- height: layer.height,- tileWidth: mapData.tileWidth,- tileHeight: mapData.tileHeight,- texture: textureHandle,+ cellSize: { x: mapData.tileWidth, y: mapData.tileHeight },+ tileset: textureHandle,tilesetColumns: columns,- layer: layerIndex,- tiles: Array.from(layer.tiles),- tint: { ...layer.tintColor },+ tilesetRows: firstTileset+ ? Math.max(1, Math.ceil(firstTileset.tileCount / Math.max(1, columns)))+ : 1,+ renderLayer: layerIndex,+ tintColor: { ...layer.tintColor },opacity: layer.opacity,visible: layer.visible,parallaxFactor: { x: layer.parallaxX, y: layer.parallaxY },});+ TilemapAPI.initInfiniteLayer(entity, mapData.tileWidth, mapData.tileHeight);+ TilemapAPI.setOriginEntity(entity, entity);+ uploadTiledLayerTiles(entity, layer);+entities.push(entity);layerIndex++;}diff --git a/sdk/src/tilemap/tilemapAPI.ts b/sdk/src/tilemap/tilemapAPI.tsindex 14f21fdf3..a4d85f06a 100644--- a/sdk/src/tilemap/tilemapAPI.ts+++ b/sdk/src/tilemap/tilemapAPI.ts@@ -41,6 +41,9 @@ interface TilemapModule {tilemap_rotateTile(entity: number, x: number, y: number, degrees: number): void;tilemap_setGridType(entity: number, type: number): void;tilemap_initInfiniteLayer(entity: number, tileWidth: number, tileHeight: number): void;+ tilemap_initInfinite?(entity: number, tileWidth: number, tileHeight: number): void;+ tilemap_exportChunks?(entity: number): string;+ tilemap_importChunks?(entity: number, encoded: string): boolean;tilemap_setChunkTiles(entity: number, chunkX: number, chunkY: number,tilesPtr: number, width: number, height: number): void;tilemap_tileToWorld(entity: number, tx: number, ty: number,@@ -225,6 +228,11 @@ export const TilemapAPI = {},initInfiniteLayer(entity: number, tileWidth: number, tileHeight: number): void {+ // Prefer the idempotent binding so a second call doesn't wipe tiles.+ if (module_?.tilemap_initInfinite) {+ module_.tilemap_initInfinite(entity, tileWidth, tileHeight);+ return;+ }module_?.tilemap_initInfiniteLayer(entity, tileWidth, tileHeight);},@@ -257,4 +265,12 @@ export const TilemapAPI = {const floats = new Float32Array(module_.HEAPU8.buffer, ptr, 2);return { x: floats[0], y: floats[1] };},++ exportChunks(entity: number): string {+ return module_?.tilemap_exportChunks?.(entity) ?? '';+ },++ importChunks(entity: number, encoded: string): boolean {+ return module_?.tilemap_importChunks?.(entity, encoded) ?? false;+ },};diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.tsindex 004bf1db4..d9fb719b0 100644--- a/sdk/src/tilemap/tilemapPlugin.ts+++ b/sdk/src/tilemap/tilemapPlugin.ts@@ -1,10 +1,10 @@import type { App, Plugin } from '../app';import type { ESEngineModule } from '../wasm';-import { Transform, type TransformData } from '../component';+import { Transform, TilemapLayer, type TilemapLayerData } from '../component';import { Schedule } from '../system';import type { SystemDef } from '../system';import { initTilemapAPI, shutdownTilemapAPI, TilemapAPI } from './tilemapAPI';-import { Tilemap, TilemapLayer, type TilemapLayerData } from './components';+import { Tilemap } from './components';import { getTilemapSource } from './tilesetCache';import { getTextureDimensions } from '../resourceManager';import { Time } from '../resource';@@ -27,7 +27,7 @@ export class TilemapPlugin implements Plugin {private layerState_ = new Map<number, {texture: number;tilesetColumns: number;- layer: number;+ renderLayer: number;tintR: number; tintG: number; tintB: number; tintA: number;opacity: number;parallaxX: number; parallaxY: number;@@ -67,54 +67,30 @@ export class TilemapPlugin implements Plugin {const layerData = world.tryGet(entity, TilemapLayer) as TilemapLayerData | null;if (!layerData) continue;- const textureHandle = layerData.texture;+ const textureHandle = layerData.tileset;if (!textureHandle) continue;const dims = getTextureDimensions(textureHandle);if (!dims) continue;if (!initializedLayers.has(entity)) {- if (layerData.infinite) {- TilemapAPI.initInfiniteLayer(- entity, layerData.tileWidth, layerData.tileHeight,- );- if (layerData.chunks) {- for (const [key, tiles] of Object.entries(layerData.chunks)) {- const [cxStr, cyStr] = key.split(',');- const cx = parseInt(cxStr, 10);- const cy = parseInt(cyStr, 10);- const u16 = new Uint16Array(tiles.length);- for (let i = 0; i < tiles.length; i++) u16[i] = tiles[i];- TilemapAPI.setChunkTiles(entity, cx, cy, u16, 16, 16);- }- }- } else {- TilemapAPI.initLayer(- entity, layerData.width, layerData.height,- layerData.tileWidth, layerData.tileHeight,- );- if (layerData.tiles.length > 0) {- const u16 = new Uint16Array(layerData.tiles.length);- for (let i = 0; i < layerData.tiles.length; i++) {- u16[i] = layerData.tiles[i];- }- TilemapAPI.setTiles(entity, u16);- }- }+ TilemapAPI.initInfiniteLayer(+ entity, layerData.cellSize.x, layerData.cellSize.y,+ );TilemapAPI.setOriginEntity(entity, entity);initializedLayers.add(entity);}- const uvTileWidth = layerData.tileWidth / dims.width;- const uvTileHeight = layerData.tileHeight / dims.height;- const tint = layerData.tint;+ const uvTileWidth = layerData.cellSize.x / dims.width;+ const uvTileHeight = layerData.cellSize.y / dims.height;+ const tint = layerData.tintColor;const pf = layerData.parallaxFactor;const prev = layerState.get(entity);const needsUpdate = !prev|| prev.texture !== textureHandle|| prev.tilesetColumns !== layerData.tilesetColumns- || prev.layer !== layerData.layer+ || prev.renderLayer !== layerData.renderLayer|| prev.parallaxX !== pf.x || prev.parallaxY !== pf.y|| prev.tintR !== tint.r || prev.tintG !== tint.g|| prev.tintB !== tint.b || prev.tintA !== tint.a@@ -125,7 +101,7 @@ export class TilemapPlugin implements Plugin {TilemapAPI.setRenderProps(entity, textureHandle, layerData.tilesetColumns,uvTileWidth, uvTileHeight,- layerData.layer, 0,+ layerData.renderLayer, 0,pf.x, pf.y,);TilemapAPI.setTint(entity, tint.r, tint.g, tint.b, tint.a, layerData.opacity ?? 1);@@ -134,7 +110,7 @@ export class TilemapPlugin implements Plugin {layerState.set(entity, {texture: textureHandle,tilesetColumns: layerData.tilesetColumns,- layer: layerData.layer,+ renderLayer: layerData.renderLayer,tintR: tint.r, tintG: tint.g, tintB: tint.b, tintA: tint.a,opacity: layerData.opacity,parallaxX: pf.x, parallaxY: pf.y,diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.tsindex b4e290eb0..e61c03f82 100644--- a/sdk/tests/tilemap.test.ts+++ b/sdk/tests/tilemap.test.ts@@ -44,44 +44,37 @@ describe('Tilemap Components', () => {expect(TilemapLayer._name).toBe('TilemapLayer');});- it('should have texture field defaulting to 0', () => {- expect(TilemapLayer._default.texture).toBe(0);+ it('should be a C++ builtin', () => {+ expect(TilemapLayer._builtin).toBe(true);});- it('should have tilesetColumns field defaulting to 1', () => {+ it('should have tileset field defaulting to 0', () => {+ expect(TilemapLayer._default.tileset).toBe(0);+ });++ it('should have tilesetColumns and tilesetRows defaults', () => {expect(TilemapLayer._default.tilesetColumns).toBe(1);+ expect(TilemapLayer._default.tilesetRows).toBe(1);});- it('should have tileWidth and tileHeight defaults', () => {- expect(TilemapLayer._default.tileWidth).toBe(32);- expect(TilemapLayer._default.tileHeight).toBe(32);+ it('should have cellSize defaulting to 32x32', () => {+ expect(TilemapLayer._default.cellSize).toEqual({ x: 32, y: 32 });});it('should have correct defaults', () => {expect(TilemapLayer._default).toEqual({- width: 10,- height: 10,- tileWidth: 32,- tileHeight: 32,- texture: 0,+ cellSize: { x: 32, y: 32 },+ originOffset: { x: 0, y: 0 },+ tileset: 0,tilesetColumns: 1,- layer: 0,- tiles: [],- infinite: false,- chunks: {},- tint: { r: 1, g: 1, b: 1, a: 1 },+ tilesetRows: 1,+ renderLayer: 0,+ tintColor: { r: 1, g: 1, b: 1, a: 1 },opacity: 1,- visible: true,parallaxFactor: { x: 1, y: 1 },+ visible: true,});});-- it('should create instances with deep-cloned tiles array', () => {- const a = TilemapLayer.create();- const b = TilemapLayer.create();- a.tiles.push(1);- expect(b.tiles).toEqual([]);- });});});@@ -381,13 +374,10 @@ describe('loadTiledMap', () => {const layerInserts = insertCalls.filter((c: any) => c[1]._name === 'TilemapLayer');expect(layerInserts).toHaveLength(2);- expect(layerInserts[0][2].texture).toBe(42);+ expect(layerInserts[0][2].tileset).toBe(42);expect(layerInserts[0][2].tilesetColumns).toBe(8);- expect(layerInserts[0][2].tileWidth).toBe(16);- expect(layerInserts[0][2].tileHeight).toBe(16);- expect(layerInserts[0][2].width).toBe(20);- expect(layerInserts[0][2].height).toBe(15);- expect(layerInserts[0][2].layer).toBe(0);+ expect(layerInserts[0][2].cellSize).toEqual({ x: 16, y: 16 });+ expect(layerInserts[0][2].renderLayer).toBe(0);});it('should assign incremental layer sort order', () => {@@ -398,20 +388,8 @@ describe('loadTiledMap', () => {const insertCalls = (world.insert as any).mock.calls;const layerInserts = insertCalls.filter((c: any) => c[1]._name === 'TilemapLayer');- expect(layerInserts[0][2].layer).toBe(0);- expect(layerInserts[1][2].layer).toBe(1);- });-- it('should convert Uint16Array tiles to number[]', () => {- const world = createMockWorld();- const textureHandles = new Map([['terrain.png', 42]]);-- loadTiledMap(world, sampleMapData, textureHandles);-- const insertCalls = (world.insert as any).mock.calls;- const layerInsert = insertCalls.find((c: any) => c[1]._name === 'TilemapLayer');- expect(Array.isArray(layerInsert[2].tiles)).toBe(true);- expect(layerInsert[2].tiles).toEqual([1, 2, 3, 0, 0]);+ expect(layerInserts[0][2].renderLayer).toBe(0);+ expect(layerInserts[1][2].renderLayer).toBe(1);});it('should use texture handle 0 when tileset image is not in textureHandles', () => {@@ -422,7 +400,7 @@ describe('loadTiledMap', () => {const insertCalls = (world.insert as any).mock.calls;const layerInsert = insertCalls.find((c: any) => c[1]._name === 'TilemapLayer');- expect(layerInsert[2].texture).toBe(0);+ expect(layerInsert[2].tileset).toBe(0);});it('should return empty array for map with no layers', () => {@@ -457,7 +435,7 @@ describe('loadTiledMap', () => {const insertCalls = (world.insert as any).mock.calls;const layerInsert = insertCalls.find((c: any) => c[1]._name === 'TilemapLayer');expect(layerInsert[2].opacity).toBe(0.5);- expect(layerInsert[2].tint).toEqual({ r: 1, g: 0.5, b: 0, a: 0.8 });+ expect(layerInsert[2].tintColor).toEqual({ r: 1, g: 0.5, b: 0, a: 0.8 });expect(layerInsert[2].parallaxFactor).toEqual({ x: 0.5, y: 0.75 });expect(layerInsert[2].visible).toBe(true);});diff --git a/src/esengine/ecs/components/TilemapLayer.hpp b/src/esengine/ecs/components/TilemapLayer.hppindex 94522de4f..f0e7edb12 100644--- a/src/esengine/ecs/components/TilemapLayer.hpp+++ b/src/esengine/ecs/components/TilemapLayer.hpp@@ -1,18 +1,9 @@/*** @file TilemapLayer.hpp* @brief Tilemap layer ECS component (editor-facing metadata)- * @details The ECS component holds only the fields the editor needs to- * show in the Inspector and to round-trip through scene I/O.- * Heavy runtime state — chunks, per-tile animations, tile- * properties — lives in TilemapSystem::LayerData keyed by this- * entity, same split SpineAnimation uses with SpineResourceManager.*/#pragma once-// =============================================================================-// Includes-// =============================================================================-#include "../../core/Types.hpp"#include "../../core/Reflection.hpp"#include "../../math/Math.hpp"@@ -20,82 +11,44 @@namespace esengine::ecs {-// =============================================================================-// TilemapLayer Component-// =============================================================================-/**- * @brief Editor-facing metadata for a tilemap layer entity- *- * @details The bulk tile data (chunks, animations, per-tile properties)- * lives in TilemapSystem's LayerData keyed by this entity —- * see TilemapSystem for why the heavy state is held out-of-- * component. Chunks flow through the- * tilemap_exportChunks / tilemap_importChunks bindings during- * scene serialization so the component itself stays light.+ * Heavy tile data (chunks, animations, per-tile properties) lives in+ * TilemapSystem's LayerData keyed by this entity. Chunks flow through+ * tilemap_exportChunks / tilemap_importChunks during scene I/O.*/ES_COMPONENT()struct TilemapLayer {- /** @brief Size in world units of one tile cell */ES_PROPERTY()glm::vec2 cellSize{32.0f, 32.0f};- /**- * @brief World offset applied before rendering- * @details Per-layer parallax scales this by the camera position so- * background layers can drift more slowly.- */ES_PROPERTY()glm::vec2 originOffset{0.0f, 0.0f};- /**- * @brief Texture atlas from which tile IDs index quads- * @details Tile 0 is always treated as empty; IDs 1..N index into- * the atlas row-major.- */ES_PROPERTY(asset = texture)resource::TextureHandle tileset;- /** @brief Atlas layout: columns of tiles in the tileset texture */ES_PROPERTY()i32 tilesetColumns{1};- /** @brief Atlas layout: rows of tiles in the tileset texture */ES_PROPERTY()i32 tilesetRows{1};- /** @brief Sort order within the 2D renderer. Lower draws first */ES_PROPERTY()i32 renderLayer{0};- /** @brief Multiplied against the tile sample colour before blending */ES_PROPERTY(animatable)glm::vec4 tintColor{1.0f, 1.0f, 1.0f, 1.0f};- /** @brief Multiplied into the alpha channel of tintColor at submit time */ES_PROPERTY(animatable)f32 opacity{1.0f};- /**- * @brief Per-axis parallax factor- * @details 1.0 = locked to camera, 0.0 = static background.- * Evaluated against the active camera each frame.- */ES_PROPERTY()glm::vec2 parallaxFactor{1.0f, 1.0f};- /** @brief Whether the layer is drawn this frame */ES_PROPERTY()bool visible{true};- /**- * @brief Runtime-only dirty flag for TilemapSystem- * @details Set by TilemapSystem when author-settable fields (tint,- * visible, render layer) need to sync back into LayerData.- * Not ES_PROPERTY — not author data, not serialized.- * Starts true so the first tick after spawn pushes the- * component defaults through.- */+ // Runtime-only; not ES_PROPERTY so it isn't serialized.bool needsSync{true};TilemapLayer() = default;