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.

feat: add tilemap system with Tiled map support

esengine0cdf68f3414c
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e5a461e93..853f93fe7 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -51,6 +51,8 @@ set(ESENGINE_SOURCES
src/esengine/animation/TweenSystem.cpp
src/esengine/particle/Particle.cpp
src/esengine/particle/ParticleSystem.cpp
+ src/esengine/tilemap/TilemapSystem.cpp
+ src/esengine/tilemap/TiledMapLoader.cpp
)
if(ES_ENABLE_SPINE)
@@ -116,6 +118,8 @@ set(ESENGINE_HEADERS
src/esengine/animation/TweenData.hpp
src/esengine/animation/EasingFunctions.hpp
src/esengine/animation/TweenSystem.hpp
+ src/esengine/tilemap/TilemapSystem.hpp
+ src/esengine/tilemap/TiledMapLoader.hpp
)
if(ES_ENABLE_SPINE)
@@ -203,7 +207,7 @@ target_include_directories(esengine
${CMAKE_CURRENT_SOURCE_DIR}/third_party/stb
)
-target_link_libraries(esengine PUBLIC glm)
+target_link_libraries(esengine PUBLIC glm cute_tiled)
if(ES_ENABLE_SPINE)
target_link_libraries(esengine PUBLIC spine-cpp)
@@ -241,6 +245,7 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
src/esengine/bindings/ImmediateDrawBindings.cpp
src/esengine/bindings/GeometryBindings.cpp
src/esengine/bindings/PostProcessBindings.cpp
+ src/esengine/bindings/TilemapBindings.cpp
${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_sdk PRIVATE esengine)
es_apply_sdk_settings(esengine_sdk)
@@ -260,6 +265,7 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
src/esengine/bindings/ImmediateDrawBindings.cpp
src/esengine/bindings/GeometryBindings.cpp
src/esengine/bindings/PostProcessBindings.cpp
+ src/esengine/bindings/TilemapBindings.cpp
${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_single PRIVATE esengine)
es_apply_single_file_settings(esengine_single)
@@ -356,6 +362,7 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}
src/esengine/bindings/ImmediateDrawBindings.cpp
src/esengine/bindings/GeometryBindings.cpp
src/esengine/bindings/PostProcessBindings.cpp
+ src/esengine/bindings/TilemapBindings.cpp
${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_wxgame PRIVATE esengine)
es_apply_wxgame_sdk_settings(esengine_wxgame)
@@ -453,6 +460,7 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}
src/esengine/bindings/ImmediateDrawBindings.cpp
src/esengine/bindings/GeometryBindings.cpp
src/esengine/bindings/PostProcessBindings.cpp
+ src/esengine/bindings/TilemapBindings.cpp
${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_sdk_main PRIVATE esengine)
es_apply_main_module_settings(esengine_sdk_main)
@@ -470,6 +478,7 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}
src/esengine/bindings/ImmediateDrawBindings.cpp
src/esengine/bindings/GeometryBindings.cpp
src/esengine/bindings/PostProcessBindings.cpp
+ src/esengine/bindings/TilemapBindings.cpp
${GENERATED_WEB_BINDINGS})
target_link_libraries(esengine_wxgame_main PRIVATE esengine)
es_apply_wxgame_main_module_settings(esengine_wxgame_main)
diff --git a/editor/src/asset/AssetTypeRegistry.ts b/editor/src/asset/AssetTypeRegistry.ts
index 1af5bec34..d2157fd1b 100644
--- a/editor/src/asset/AssetTypeRegistry.ts
+++ b/editor/src/asset/AssetTypeRegistry.ts
@@ -10,6 +10,7 @@ import { renderFolderInspector } from '../panels/inspector/FolderInspector';
import { renderScriptInspector, renderSceneInspector, renderFileInspector } from '../panels/inspector/FileInspector';
import { renderAnimClipInspector } from '../panels/inspector/AnimClipInspector';
import { renderAudioInspector } from '../panels/inspector/AudioInspector';
+
import { getInitialComponentData, getDefaultComponentData } from '../schemas/ComponentSchemas';
import { getGlobalPathResolver } from '../asset';
import { getPlatformAdapter } from '../platform/PlatformAdapter';
diff --git a/editor/src/asset/ImporterRegistry.ts b/editor/src/asset/ImporterRegistry.ts
index 3e5ea5134..26fa77876 100644
--- a/editor/src/asset/ImporterRegistry.ts
+++ b/editor/src/asset/ImporterRegistry.ts
@@ -14,6 +14,7 @@ import { BitmapFontImporter } from './importers/BitmapFontImporter';
import { SceneImporter } from './importers/SceneImporter';
import { PrefabImporter } from './importers/PrefabImporter';
+
// =============================================================================
// Types
// =============================================================================
diff --git a/editor/src/builder/AssetCollector.ts b/editor/src/builder/AssetCollector.ts
index f6ae96542..63ffe235c 100644
--- a/editor/src/builder/AssetCollector.ts
+++ b/editor/src/builder/AssetCollector.ts
@@ -210,6 +210,9 @@ export class AssetReferenceCollector {
case 'prefab':
await this.collectPrefabRefs(resolved, refs, visited);
break;
+ case 'tilemap':
+ await this.collectTilemapRefs(resolved, refs);
+ break;
}
}
@@ -333,6 +336,32 @@ export class AssetReferenceCollector {
}
}
+ private async collectTilemapRefs(tilemapPath: string, refs: Set<string>): Promise<void> {
+ const fullPath = isAbsolutePath(tilemapPath)
+ ? tilemapPath
+ : joinPath(this.projectDir_, tilemapPath);
+
+ const content = await this.fs_.readFile(fullPath);
+ if (!content) return;
+
+ try {
+ const json = JSON.parse(content);
+ const dir = getDirName(tilemapPath);
+ const tilesets = json.tilesets as Array<Record<string, unknown>> | undefined;
+ if (!tilesets) return;
+
+ for (const tileset of tilesets) {
+ const image = tileset.image as string | undefined;
+ if (image) {
+ const texturePath = dir ? `${dir}/${image}` : image;
+ refs.add(texturePath);
+ }
+ }
+ } catch {
+ // Ignore parse errors
+ }
+ }
+
private async collectAtlasTextures(atlasPath: string, refs: Set<string>): Promise<void> {
const fullPath = isAbsolutePath(atlasPath)
? atlasPath
diff --git a/editor/src/gizmos/TilemapOverlay.ts b/editor/src/gizmos/TilemapOverlay.ts
new file mode 100644
index 000000000..ff8034be4
--- /dev/null
+++ b/editor/src/gizmos/TilemapOverlay.ts
@@ -0,0 +1,242 @@
+import type { OverlayContext } from './ColliderOverlay';
+import type { EntityData } from '../types/SceneTypes';
+import { getGlobalPathResolver } from '../asset';
+import { getPlatformAdapter } from '../platform/PlatformAdapter';
+import { isUUID, getAssetLibrary } from '../asset/AssetLibrary';
+
+const GRID_COLOR = 'rgba(100, 200, 255, 0.5)';
+const FALLBACK_TILE_COLOR = 'rgba(100, 200, 255, 0.15)';
+
+const TILED_FLIP_H = 0x80000000;
+const TILED_FLIP_V = 0x40000000;
+const TILED_FLIP_D = 0x20000000;
+const TILED_GID_MASK = 0x1FFFFFFF;
+
+interface ParsedTilemapLayer {
+ width: number;
+ height: number;
+ tiles: number[];
+}
+
+interface CachedTilemap {
+ tileWidth: number;
+ tileHeight: number;
+ layers: ParsedTilemapLayer[];
+ tilesetImage: HTMLImageElement | null;
+ tilesetColumns: number;
+}
+
+export class TilemapOverlay {
+ private cache_ = new Map<string, CachedTilemap | null>();
+ private loading_ = new Set<string>();
+ private requestRender_: (() => void) | null = null;
+
+ setRenderCallback(cb: () => void): void {
+ this.requestRender_ = cb;
+ }
+
+ drawAll(octx: OverlayContext): void {
+ const { store } = octx;
+
+ for (const entity of store.scene.entities) {
+ if (!store.isEntityVisible(entity.id)) continue;
+ this.drawEntity_(octx, entity);
+ }
+ }
+
+ private drawEntity_(octx: OverlayContext, entity: EntityData): void {
+ const tilemapComp = entity.components.find(c => c.type === 'Tilemap');
+ if (!tilemapComp) return;
+
+ const source: string = (tilemapComp.data as any).source ?? '';
+ if (!source) return;
+
+ const cached = this.loadTilemap_(source);
+ if (!cached) return;
+
+ const { ctx, zoom, store } = octx;
+ const worldTransform = store.getWorldTransform(entity.id);
+ const ox = worldTransform.position.x;
+ const oy = -worldTransform.position.y;
+
+ ctx.save();
+
+ for (const layer of cached.layers) {
+ this.drawLayer_(ctx, cached, layer, ox, oy);
+ }
+
+ if (cached.layers.length > 0) {
+ const firstLayer = cached.layers[0];
+ this.drawGrid_(ctx, firstLayer.width, firstLayer.height,
+ cached.tileWidth, cached.tileHeight, ox, oy, zoom);
+ }
+
+ ctx.restore();
+ }
+
+ private drawLayer_(
+ ctx: CanvasRenderingContext2D,
+ cached: CachedTilemap,
+ layer: ParsedTilemapLayer,
+ ox: number, oy: number,
+ ): void {
+ const { tileWidth, tileHeight, tilesetImage, tilesetColumns } = cached;
+
+ if (tilesetImage && tilesetImage.complete && tilesetImage.naturalWidth > 0) {
+ for (let ty = 0; ty < layer.height; ty++) {
+ for (let tx = 0; tx < layer.width; tx++) {
+ const tileId = layer.tiles[ty * layer.width + tx] ?? 0;
+ if (tileId === 0) continue;
+
+ const tileIndex = tileId - 1;
+ const sx = (tileIndex % tilesetColumns) * tileWidth;
+ const sy = Math.floor(tileIndex / tilesetColumns) * tileHeight;
+
+ ctx.drawImage(
+ tilesetImage,
+ sx, sy, tileWidth, tileHeight,
+ ox + tx * tileWidth, oy + ty * tileHeight, tileWidth, tileHeight,
+ );
+ }
+ }
+ } else {
+ ctx.fillStyle = FALLBACK_TILE_COLOR;
+ for (let ty = 0; ty < layer.height; ty++) {
+ for (let tx = 0; tx < layer.width; tx++) {
+ const tileId = layer.tiles[ty * layer.width + tx] ?? 0;
+ if (tileId === 0) continue;
+ ctx.fillRect(
+ ox + tx * tileWidth + 1, oy + ty * tileHeight + 1,
+ tileWidth - 2, tileHeight - 2,
+ );
+ }
+ }
+ }
+ }
+
+ private drawGrid_(
+ ctx: CanvasRenderingContext2D,
+ mapWidth: number, mapHeight: number,
+ tileWidth: number, tileHeight: number,
+ ox: number, oy: number, zoom: number,
+ ): void {
+ ctx.strokeStyle = GRID_COLOR;
+ ctx.lineWidth = 1 / zoom;
+
+ for (let x = 0; x <= mapWidth; x++) {
+ const wx = ox + x * tileWidth;
+ ctx.beginPath();
+ ctx.moveTo(wx, oy);
+ ctx.lineTo(wx, oy + mapHeight * tileHeight);
+ ctx.stroke();
+ }
+ for (let y = 0; y <= mapHeight; y++) {
+ const wy = oy + y * tileHeight;
+ ctx.beginPath();
+ ctx.moveTo(ox, wy);
+ ctx.lineTo(ox + mapWidth * tileWidth, wy);
+ ctx.stroke();
+ }
+ }
+
+ private loadTilemap_(source: string): CachedTilemap | null {
+ if (this.cache_.has(source)) {
+ return this.cache_.get(source) ?? null;
+ }
+ if (this.loading_.has(source)) {
+ return null;
+ }
+
+ this.loading_.add(source);
+ this.loadTilemapAsync_(source).then(result => {
+ this.cache_.set(source, result);
+ this.loading_.delete(source);
+ if (result) {
+ this.requestRender_?.();
+ }
+ });
+ return null;
+ }
+
+ private resolveSource_(source: string): string {
+ if (isUUID(source)) {
+ return getAssetLibrary().getPath(source) ?? source;
+ }
+ return source;
+ }
+
+ private async loadTilemapAsync_(source: string): Promise<CachedTilemap | null> {
+ try {
+ const resolver = getGlobalPathResolver();
+ if (!resolver) return null;
+
+ const platform = getPlatformAdapter();
+ const resolvedPath = this.resolveSource_(source);
+ const absPath = resolver.toAbsolutePath(resolvedPath);
+ const jsonText = await platform.readTextFile(absPath);
+ const json = JSON.parse(jsonText) as Record<string, unknown>;
+
+ const mapWidth = json.width as number;
+ const mapHeight = json.height as number;
+ const tileWidth = (json.tilewidth as number) ?? 32;
+ const tileHeight = (json.tileheight as number) ?? 32;
+ if (!mapWidth || !mapHeight) return null;
+
+ const rawTilesets = json.tilesets as Array<Record<string, unknown>> | undefined;
+ const firstGid = rawTilesets?.[0]?.firstgid as number ?? 1;
+ const tilesetImage = rawTilesets?.[0]?.image as string ?? '';
+ const tilesetColumns = (rawTilesets?.[0]?.columns as number) ?? 1;
+
+ const rawLayers = json.layers as Array<Record<string, unknown>> | undefined;
+ const layers: ParsedTilemapLayer[] = [];
+
+ if (rawLayers) {
+ for (const layer of rawLayers) {
+ if (layer.type !== 'tilelayer') continue;
+ const lw = (layer.width as number) ?? mapWidth;
+ const lh = (layer.height as number) ?? mapHeight;
+ if (layer.visible === false) continue;
+ const rawData = layer.data as number[] | undefined;
+ const tiles: number[] = [];
+ if (rawData) {
+ for (const gid of rawData) {
+ if (gid === 0) {
+ tiles.push(0);
+ } else {
+ const localId = (gid & TILED_GID_MASK) - firstGid;
+ tiles.push(localId + 1);
+ }
+ }
+ }
+ layers.push({ width: lw, height: lh, tiles });
+ }
+ }
+
+ let loadedImage: HTMLImageElement | null = null;
+ if (tilesetImage) {
+ const baseDir = resolvedPath.substring(0, resolvedPath.lastIndexOf('/') + 1);
+ const imagePath = baseDir + tilesetImage;
+ const absImagePath = resolver.toAbsolutePath(imagePath);
+ const imageUrl = platform.convertFilePathToUrl(absImagePath);
+
+ const img = new Image();
+ img.src = imageUrl;
+ await new Promise<void>((resolve, reject) => {
+ img.onload = () => resolve();
+ img.onerror = () => reject(new Error('Failed to load tileset image'));
+ });
+ loadedImage = img;
+ }
+
+ return {
+ tileWidth,
+ tileHeight,
+ layers,
+ tilesetImage: loadedImage,
+ tilesetColumns,
+ };
+ } catch {
+ return null;
+ }
+ }
+}
diff --git a/editor/src/panels/content-browser/AssetContextMenu.ts b/editor/src/panels/content-browser/AssetContextMenu.ts
index b8aa3ec31..dfc577680 100644
--- a/editor/src/panels/content-browser/AssetContextMenu.ts
+++ b/editor/src/panels/content-browser/AssetContextMenu.ts
@@ -93,6 +93,7 @@ export function showFolderContextMenu(state: ContentBrowserState, e: MouseEvent,
{ label: 'BitmapFont', icon: icons.type(14), onClick: () => createNewBitmapFont(state, path) },
{ label: 'Animation Clip', icon: icons.layers(14), onClick: () => createNewAnimClip(state, path) },
{ label: 'Scene', icon: icons.layers(14), onClick: () => createNewScene(state, path) },
+
],
},
{ label: '', separator: true },
diff --git a/editor/src/panels/hierarchy/HierarchyContextMenu.ts b/editor/src/panels/hierarchy/HierarchyContextMenu.ts
index 4f73a08e1..7e2b621f7 100644
--- a/editor/src/panels/hierarchy/HierarchyContextMenu.ts
+++ b/editor/src/panels/hierarchy/HierarchyContextMenu.ts
@@ -30,6 +30,7 @@ export function showEntityContextMenu(state: HierarchyState, x: number, y: numbe
{ label: 'BitmapText', icon: icons.type(14), onClick: () => createEntityWithComponent(state, 'BitmapText', entity) },
{ label: 'Spine', icon: icons.bone(14), onClick: () => createEntityWithComponent(state, 'SpineAnimation', entity) },
{ label: 'Particle', icon: icons.star(14), onClick: () => createEntityWithComponent(state, 'ParticleEmitter', entity) },
+ { label: 'Tilemap', icon: icons.grid(14), onClick: () => createTilemapEntity(state, entity) },
] },
{ label: 'UI', icon: icons.pointer(14), children: [
{ label: 'Canvas', icon: icons.template(14), onClick: () => createEntityWithComponent(state, 'Canvas', entity) },
@@ -545,6 +546,12 @@ async function saveEntityAsPrefab(state: HierarchyState, entity: Entity): Promis
}
}
+function createTilemapEntity(state: HierarchyState, parent: Entity | null): void {
+ const newEntity = state.store.createEntity('Tilemap', parent);
+ state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
+ state.store.addComponent(newEntity, 'Tilemap', getInitialComponentData('Tilemap'));
+}
+
export async function createEntityFromAsset(
state: HierarchyState,
asset: { type: string; path: string; name: string },
diff --git a/editor/src/panels/scene-view/SceneViewPanel.ts b/editor/src/panels/scene-view/SceneViewPanel.ts
index 1cae6f435..ef9613833 100644
--- a/editor/src/panels/scene-view/SceneViewPanel.ts
+++ b/editor/src/panels/scene-view/SceneViewPanel.ts
@@ -21,6 +21,7 @@ import { GizmoToolbar } from './GizmoToolbar';
import { MarqueeSelection } from './MarqueeSelection';
import { EntityDropHandler } from './EntityDropHandler';
import { SceneViewInput } from './SceneViewInput';
+import { TilemapOverlay } from '../../gizmos/TilemapOverlay';
const CAMERA_COLORS = [
'#ffaa00',
@@ -70,6 +71,8 @@ export class SceneViewPanel {
private dropHandler_: EntityDropHandler;
private input_: SceneViewInput;
+ private tilemapOverlay_: TilemapOverlay;
+
private fpsCollector_ = new StatsCollector();
private lastFrameTime_ = 0;
@@ -85,6 +88,8 @@ export class SceneViewPanel {
this.gizmoManager_ = new GizmoManager();
this.colliderOverlay_ = new ColliderOverlay();
this.particleOverlay_ = new ParticleOverlay();
+ this.tilemapOverlay_ = new TilemapOverlay();
+ this.tilemapOverlay_.setRenderCallback(() => this.requestRender());
this.camera_ = new CameraController(null!, () => this.requestRender());
this.toolbar_ = new GizmoToolbar(container, this.gizmoManager_, () => this.requestRender());
@@ -118,6 +123,8 @@ export class SceneViewPanel {
this.camera_.setCanvas(this.canvas_);
+ const viewport = this.container_.querySelector('.es-sceneview-viewport')!;
+
this.input_ = new SceneViewInput({
store,
canvas: this.canvas_,
@@ -156,11 +163,8 @@ export class SceneViewPanel {
}
});
- const viewport = this.container_.querySelector('.es-sceneview-viewport');
- if (viewport) {
- this.resizeObserver_ = new ResizeObserver(() => this.resize());
- this.resizeObserver_.observe(viewport);
- }
+ this.resizeObserver_ = new ResizeObserver(() => this.resize());
+ this.resizeObserver_.observe(viewport);
this.resize();
@@ -446,6 +450,7 @@ export class SceneViewPanel {
this.requestRender();
}
+
// =========================================================================
// Texture Cache
// =========================================================================
@@ -598,6 +603,7 @@ export class SceneViewPanel {
} else {
this.renderPreview();
}
+
}
// =========================================================================
@@ -633,6 +639,7 @@ export class SceneViewPanel {
this.drawCanvasBounds(ctx);
const oScale = this.overlayScale_();
+ this.tilemapOverlay_.drawAll({ ctx, zoom: oScale, store: this.store_ });
if (getSettingsValue<boolean>('scene.showColliders')) {
this.colliderOverlay_.drawAll({
ctx,
@@ -712,6 +719,7 @@ export class SceneViewPanel {
this.drawCanvasBounds(ctx);
const oScale = this.overlayScale_();
+ this.tilemapOverlay_.drawAll({ ctx, zoom: oScale, store: this.store_ });
if (getSettingsValue<boolean>('scene.showColliders')) {
this.colliderOverlay_.drawAll({
ctx,
diff --git a/editor/src/renderer/SharedRenderContext.ts b/editor/src/renderer/SharedRenderContext.ts
index 83f1e61eb..89e0e0ea3 100644
--- a/editor/src/renderer/SharedRenderContext.ts
+++ b/editor/src/renderer/SharedRenderContext.ts
@@ -29,6 +29,8 @@ import {
initRendererAPI,
shutdownRendererAPI,
particlePlugin,
+ tilemapPlugin,
+ sceneManagerPlugin,
} from 'esengine';
import type { SpineModuleController } from 'esengine/spine';
import { EditorSceneManager } from '../scene/EditorSceneManager';
@@ -129,6 +131,7 @@ export class SharedRenderContext {
const app = App.new();
const cppRegistry = new module.Registry() as unknown as CppRegistry;
app.connectCpp(cppRegistry, module);
+ app.setPipeline(this.pipeline_);
app.insertResource(UICameraInfo, {
viewProjection: new Float32Array(16),
@@ -160,6 +163,8 @@ export class SharedRenderContext {
app.addPlugin(animationPlugin);
app.addPlugin(audioPlugin);
app.addPlugin(particlePlugin);
+ app.addPlugin(tilemapPlugin);
+ app.addPlugin(sceneManagerPlugin);
for (const plugin of uiPlugins) {
app.addPlugin(plugin);
}
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index 12b051a37..c1a8b9397 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -34,6 +34,10 @@ import {
type TextInputData,
type LayoutRect,
ScaleMode,
+ parseTmjJson,
+ resolveRelativePath,
+ registerTextureDimensions,
+ registerTilemapSource,
} from 'esengine';
import type { SpineModuleController } from 'esengine/spine';
import { submitSpineMeshesToCore } from 'esengine/spine';
@@ -758,6 +762,15 @@ export class EditorSceneManager {
}
break;
}
+ case 'tilemap': {
+ try {
+ await this.loadTilemapSource(resolved);
+ data[desc.field] = resolved;
+ } catch (err) {
+ console.warn(`[EditorSceneManager] Failed to load tilemap: ${resolved}`, err);
+ }
+ break;
+ }
}
}
@@ -815,6 +828,45 @@ export class EditorSceneManager {
registerAnimClip(clip);
}
+ private async loadTilemapSource(tmjPath: string): Promise<void> {
+ const fs = getEditorContext().fs;
+ if (!fs) return;
+
+ const absPath = this.pathResolver_.toAbsolutePath(tmjPath);
+ const raw = await fs.readFile(absPath);
+ if (!raw) return;
+
+ const json = JSON.parse(raw) as Record<string, unknown>;
+ const mapData = parseTmjJson(json);
+ if (!mapData) return;
+
+ const tilesets = [];
+ for (const ts of mapData.tilesets) {
+ const imagePath = resolveRelativePath(tmjPath, ts.image);
+ let textureHandle = 0;
+ try {
+ const info = await this.assetServer_.loadTexture(imagePath);
+ textureHandle = info.handle;
+ registerTextureDimensions(info.handle, info.width, info.height);
+ } catch (err) {
+ console.warn(`[EditorSceneManager] Failed to load tileset texture: ${imagePath}`, err);
+ }
+ tilesets.push({ textureHandle, columns: ts.columns });
+ }
+
+ registerTilemapSource(tmjPath, {
+ tileWidth: mapData.tileWidth,
+ tileHeight: mapData.tileHeight,
+ layers: mapData.layers.map(l => ({
+ name: l.name,
+ width: l.width,
+ height: l.height,
+ tiles: l.tiles,
+ })),
+ tilesets,
+ });
+ }
+
// =========================================================================
// Spine Instance Sync (post-load hook)
// =========================================================================
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.ts
index 5f9495357..66b22fad9 100644
--- a/editor/src/schemas/ComponentSchemas.ts
+++ b/editor/src/schemas/ComponentSchemas.ts
@@ -17,6 +17,8 @@ export interface ComponentSchema {
category: ComponentCategory;
properties: PropertyMeta[];
removable?: boolean;
+ hidden?: boolean;
+ displayName?: string;
}
// =============================================================================
@@ -802,6 +804,29 @@ export const UIInteractionSchema: ComponentSchema = {
properties: [],
};
+export const TilemapSchema: ComponentSchema = {
+ name: 'Tilemap',
+ category: 'builtin',
+ properties: [
+ { name: 'source', type: 'tilemap-file' },
+ ],
+};
+
+export const TilemapLayerSchema: ComponentSchema = {
+ name: 'TilemapLayer',
+ category: 'builtin',
+ hidden: true,
+ properties: [
+ { name: 'width', type: 'number', min: 1, max: 1000 },
+ { name: 'height', type: 'number', min: 1, max: 1000 },
+ { name: 'tileWidth', type: 'number', min: 1, max: 512 },
+ { name: 'tileHeight', type: 'number', min: 1, max: 512 },
+ { name: 'texture', type: 'number' },
+ { name: 'tilesetColumns', type: 'number', min: 1, max: 256 },
+ { name: 'layer', type: 'number', min: -1000, max: 1000 },
+ ],
+};
+
// =============================================================================
// Registry
// =============================================================================
@@ -898,6 +923,12 @@ function exposeRegistrationAPI(): void {
}
}
+export const PostProcessVolumeSchema: ComponentSchema = {
+ name: 'PostProcessVolume',
+ category: 'builtin',
+ properties: [],
+};
+
// =============================================================================
// Initialization
// =============================================================================
@@ -948,6 +979,9 @@ export function registerBuiltinSchemas(options?: BuiltinSchemaOptions): void {
registerComponentSchema(CircleColliderSchema);
registerComponentSchema(CapsuleColliderSchema);
registerComponentSchema(ParticleEmitterSchema);
+ registerComponentSchema(TilemapSchema);
+ registerComponentSchema(TilemapLayerSchema);
+ registerComponentSchema(PostProcessVolumeSchema);
if (enableSpine) {
registerComponentSchema(SpineAnimationSchema);
}
diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.ts
index 7f9d87196..3d7d4ccca 100644
--- a/sdk/src/assetTypes.ts
+++ b/sdk/src/assetTypes.ts
@@ -6,7 +6,9 @@ export type AddressableAssetType =
export type EditorAssetType =
| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'
- | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'scene' | 'anim-clip' | 'unknown';
+ | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'scene' | 'anim-clip'
+ | 'tilemap'
+ | 'unknown';
export type AssetBuildTransform = (content: string, context: unknown) => string;
@@ -33,6 +35,7 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [
{ extensions: ['esprefab'], contentType: 'json', editorType: 'prefab', addressableType: 'prefab', wechatPackInclude: true, hasTransitiveDeps: true },
{ extensions: ['esscene'], contentType: 'json', editorType: 'scene', addressableType: null, wechatPackInclude: false, hasTransitiveDeps: false },
{ extensions: ['esanim'], contentType: 'json', editorType: 'anim-clip', addressableType: null, wechatPackInclude: true, hasTransitiveDeps: true },
+ { extensions: ['tmj'], contentType: 'json', editorType: 'tilemap', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },
];
const MIME_MAP: Record<string, string> = {
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 9c05f86ad..85a002051 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -528,6 +528,14 @@ export const SceneOwner = defineComponent<SceneOwnerData>('SceneOwner', {
persistent: false,
});
+export interface PostProcessVolumeData {
+ effects: { type: string; enabled: boolean; uniforms: Record<string, number> }[];
+}
+
+export const PostProcessVolume = defineComponent<PostProcessVolumeData>('PostProcessVolume', {
+ effects: [],
+});
+
export type {
RigidBodyData, BoxColliderData, CircleColliderData, CapsuleColliderData,
};
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 781fe12e1..b3b5e4486 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -105,6 +105,8 @@ export {
SimulationSpace,
ParticleEasing,
type ParticleEmitterData,
+ PostProcessVolume,
+ type PostProcessVolumeData,
} from './component';
export {
@@ -524,8 +526,18 @@ export {
export {
PostProcess,
+ PostProcessStack,
initPostProcessAPI,
shutdownPostProcessAPI,
+ type EffectDef,
+ type EffectUniformDef,
+ type PostProcessEffectData,
+ getEffectDef,
+ getEffectTypes,
+ getAllEffectDefs,
+ syncPostProcessVolume,
+ cleanupPostProcessVolume,
+ cleanupAllPostProcessVolumes,
} from './postprocess';
// =============================================================================
@@ -705,6 +717,39 @@ export {
particlePlugin,
} from './particle';
+// =============================================================================
+// Tilemap
+// =============================================================================
+
+export {
+ Tilemap,
+ TilemapLayer,
+ TilemapAPI,
+ initTilemapAPI,
+ shutdownTilemapAPI,
+ TilemapPlugin,
+ tilemapPlugin,
+ parseTiledMap,
+ parseTmjJson,
+ loadTiledMap,
+ resolveRelativePath,
+ registerTextureDimensions,
+ getTextureDimensions,
+ clearTextureDimensionsCache,
+ registerTilemapSource,
+ getTilemapSource,
+ clearTilemapSourceCache,
+ type TilemapData,
+ type TilemapLayerData,
+ type TiledMapData,
+ type TiledLayerData,
+ type TiledTilesetData,
+ type TextureDimensions,
+ type LoadedTilemapSource,
+ type LoadedTilemapLayer,
+ type LoadedTilemapTileset,
+} from './tilemap';
+
// =============================================================================
// Stats
// =============================================================================
diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.ts
index 802ad0e62..fea7597a4 100644
--- a/sdk/src/renderPipeline.ts
+++ b/sdk/src/renderPipeline.ts
@@ -4,6 +4,7 @@
*/
import type { CppRegistry } from './wasm';
+import type { Entity } from './types';
import { Renderer } from './renderer';
import { PostProcess } from './postprocess';
import { Draw } from './draw';
@@ -23,10 +24,13 @@ export interface CameraRenderParams {
viewportPixels: { x: number; y: number; w: number; h: number };
clearFlags: number;
elapsed: number;
+ cameraEntity?: Entity;
}
export type SpineRendererFn = (registry: { _cpp: CppRegistry }, elapsed: number) => void;
+export type TilemapRendererFn = () => void;
+
export type MaskProcessorFn = (
registry: CppRegistry,
vp: Float32Array,
@@ -36,6 +40,7 @@ export type MaskProcessorFn = (
export class RenderPipeline {
private spineRenderer_: SpineRendererFn | null = null;
+ private tilemapRenderer_: TilemapRendererFn | null = null;
private maskProcessor_: MaskProcessorFn | null = null;
private lastWidth_ = 0;
private lastHeight_ = 0;
@@ -49,6 +54,10 @@ export class RenderPipeline {
this.spineRenderer_ = fn;
}
+ setTilemapRenderer(fn: TilemapRendererFn | null): void {
+ this.tilemapRenderer_ = fn;
+ }
+
get maskProcessor(): MaskProcessorFn | null {
return this.maskProcessor_;
}
@@ -66,9 +75,6 @@ export class RenderPipeline {
if (width !== this.lastWidth_ || height !== this.lastHeight_) {
Renderer.resize(width, height);
- if (PostProcess.isInitialized() && PostProcess.getPassCount() > 0) {
- PostProcess.resize(width, height);
- }
this.lastWidth_ = width;
this.lastHeight_ = height;
}
@@ -79,6 +85,9 @@ export class RenderPipeline {
if (this.maskProcessor_) {
this.maskProcessor_(registry._cpp, viewProjection, 0, 0, width, height);
}
+ if (this.tilemapRenderer_) {
+ this.tilemapRenderer_();
+ }
Renderer.submitSprites(registry);
Renderer.submitBitmapText(registry);
if (this.spineRenderer_) {
@@ -95,7 +104,15 @@ export class RenderPipeline {
}
renderCamera(params: CameraRenderParams): void {
- const { registry, viewProjection, viewportPixels: vp, clearFlags, elapsed } = params;
+ const { registry, viewProjection, viewportPixels: vp, clearFlags, elapsed, cameraEntity } = params;
+
+ const hasPostProcess = cameraEntity !== undefined && PostProcess.getStack(cameraEntity) !== null;
+
+ if (hasPostProcess) {
+ PostProcess._applyForCamera(cameraEntity!);
+ PostProcess.resize(vp.w, vp.h);
+ PostProcess.setOutputViewport(vp.x, vp.y, vp.w, vp.h);
+ }
Renderer.setViewport(vp.x, vp.y, vp.w, vp.h);
Renderer.setScissor(vp.x, vp.y, vp.w, vp.h, true);
@@ -106,6 +123,9 @@ export class RenderPipeline {
if (this.maskProcessor_) {
this.maskProcessor_(registry._cpp, viewProjection, vp.x, vp.y, vp.w, vp.h);
}
+ if (this.tilemapRenderer_) {
+ this.tilemapRenderer_();
+ }
Renderer.submitSprites(registry);
Renderer.submitBitmapText(registry);
if (this.spineRenderer_) {
@@ -119,6 +139,10 @@ export class RenderPipeline {
this.executeDrawCallbacks(viewProjection, elapsed);
Renderer.end();
+
+ if (hasPostProcess) {
+ PostProcess._resetAfterCamera();
+ }
}
private executeDrawCallbacks(viewProjection: Float32Array, elapsed: number): void {
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index d795a83ec..37f4d3ca7 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -10,6 +10,8 @@ import type { AssetServer } from './asset/AssetServer';
import { extractAnimClipTexturePaths, parseAnimClipData, type AnimClipAssetData } from './animation/AnimClipLoader';
import { registerAnimClip } from './animation/SpriteAnimator';
import { Audio } from './audio/Audio';
+import { registerTextureDimensions, registerTilemapSource } from './tilemap/tilesetCache';
+import { parseTmjJson, resolveRelativePath } from './tilemap/tiledLoader';
// =============================================================================
// Types
@@ -66,7 +68,7 @@ export interface SceneLoadOptions {
// Component Asset Field Registry
// =============================================================================
-export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio';
+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap';
interface AssetFieldDescriptor {
field: string;
@@ -123,6 +125,11 @@ const COMPONENT_ASSET_FIELDS = new Map<string, ComponentAssetFields>([
{ field: 'material', type: 'material' },
],
}],
+ ['Tilemap', {
+ fields: [
+ { field: 'source', type: 'tilemap' },
+ ],
+ }],
]);
export function registerComponentAssetFields(
@@ -290,6 +297,7 @@ const ASSET_FIELD_HANDLERS = new Map<AssetFieldType, AssetFieldHandler>([
const info = await assetServer.loadTexture(url);
handles.set(texturePath, info.handle);
texturePathToUrl.set(texturePath, url);
+ registerTextureDimensions(info.handle, info.width, info.height);
} catch (err) {
console.warn(`Failed to load texture: ${texturePath}`, err);
handles.set(texturePath, 0);
@@ -371,6 +379,52 @@ const ASSET_FIELD_HANDLERS = new Map<AssetFieldType, AssetFieldHandler>([
return new Map();
},
}],
+ ['tilemap', {
+ async load(paths, assetServer, baseUrl, texturePathToUrl) {
+ const promises = [...paths].map(async (tmjPath) => {
+ try {
+ const json = await assetServer.loadJson<Record<string, unknown>>(tmjPath);
+ const mapData = parseTmjJson(json);
+ if (!mapData) {
+ console.warn(`Failed to parse tilemap: ${tmjPath}`);
+ return;
+ }
+
+ const tilesets = [];
+ for (const ts of mapData.tilesets) {
+ const imagePath = resolveRelativePath(tmjPath, ts.image);
+ let textureHandle = 0;
+ try {
+ const url = baseUrl ? `${baseUrl}/${imagePath}` : `/${imagePath}`;
+ const info = await assetServer.loadTexture(url);
+ textureHandle = info.handle;
+ texturePathToUrl.set(imagePath, url);
+ registerTextureDimensions(info.handle, info.width, info.height);
+ } catch (err) {
+ console.warn(`Failed to load tileset texture: ${imagePath}`, err);
+ }
+ tilesets.push({ textureHandle, columns: ts.columns });
+ }
+
+ registerTilemapSource(tmjPath, {
+ tileWidth: mapData.tileWidth,
+ tileHeight: mapData.tileHeight,
+ layers: mapData.layers.map(l => ({
+ name: l.name,
+ width: l.width,
+ height: l.height,
+ tiles: l.tiles,
+ })),
+ tilesets,
+ });
+ } catch (err) {
+ console.warn(`Failed to load tilemap: ${tmjPath}`, err);
+ }
+ });
+ await Promise.all(promises);
+ return new Map();
+ },
+ }],
]);
async function preloadSceneAssets(
diff --git a/sdk/src/tilemap/components.ts b/sdk/src/tilemap/components.ts
new file mode 100644
index 000000000..93b4fef7e
--- /dev/null
+++ b/sdk/src/tilemap/components.ts
@@ -0,0 +1,31 @@
+import { defineComponent } 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[];
+}
+
+export const Tilemap = defineComponent<TilemapData>('Tilemap', {
+ source: '',
+});
+
+export const TilemapLayer = defineComponent<TilemapLayerData>('TilemapLayer', {
+ width: 10,
+ height: 10,
+ tileWidth: 32,
+ tileHeight: 32,
+ texture: 0,
+ tilesetColumns: 1,
+ layer: 0,
+ tiles: [],
+});
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
new file mode 100644
index 000000000..c6303b576
--- /dev/null
+++ b/sdk/src/tilemap/index.ts
@@ -0,0 +1,12 @@
+export { Tilemap, TilemapLayer, type TilemapData, type TilemapLayerData } from './components';
+export { TilemapAPI, initTilemapAPI, shutdownTilemapAPI } from './tilemapAPI';
+export { TilemapPlugin, tilemapPlugin } from './tilemapPlugin';
+export {
+ parseTiledMap, parseTmjJson, loadTiledMap, resolveRelativePath,
+ type TiledMapData, type TiledLayerData, type TiledTilesetData,
+} from './tiledLoader';
+export {
+ registerTextureDimensions, getTextureDimensions, clearTextureDimensionsCache,
+ registerTilemapSource, getTilemapSource, clearTilemapSourceCache,
+ type TextureDimensions, type LoadedTilemapSource, type LoadedTilemapLayer, type LoadedTilemapTileset,
+} from './tilesetCache';
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
new file mode 100644
index 000000000..c0d2ffd5a
--- /dev/null
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -0,0 +1,252 @@
+import { getTiledAPI } from './tilemapAPI';
+import type { World } from '../world';
+import type { Entity } from '../types';
+import { TilemapLayer } from './components';
+import { Transform } from '../component';
+
+export interface TiledLayerData {
+ name: string;
+ width: number;
+ height: number;
+ visible: boolean;
+ tiles: Uint16Array;
+}
+
+export interface TiledTilesetData {
+ name: string;
+ image: string;
+ tileWidth: number;
+ tileHeight: number;
+ columns: number;
+ tileCount: number;
+}
+
+export interface TiledMapData {
+ width: number;
+ height: number;
+ tileWidth: number;
+ tileHeight: number;
+ layers: TiledLayerData[];
+ tilesets: TiledTilesetData[];
+}
+
+const TILED_FLIP_H = 0x80000000;
+const TILED_FLIP_V = 0x40000000;
+const TILED_FLIP_D = 0x20000000;
+const TILED_GID_MASK = 0x1FFFFFFF;
+const ENGINE_FLIP_H = 0x2000;
+const ENGINE_FLIP_V = 0x4000;
+const ENGINE_FLIP_D = 0x8000;
+
+function convertGid(gid: number, firstGid: number): number {
+ if (gid === 0) return 0;
+ let flags = 0;
+ if (gid & TILED_FLIP_H) flags |= ENGINE_FLIP_H;
+ if (gid & TILED_FLIP_V) flags |= ENGINE_FLIP_V;
+ if (gid & TILED_FLIP_D) flags |= ENGINE_FLIP_D;
+ const localId = (gid & TILED_GID_MASK) - firstGid;
+ return (localId + 1) | flags;
+}
+
+export function parseTmjJson(json: Record<string, unknown>): TiledMapData | null {
+ const width = json.width as number;
+ const height = json.height as number;
+ const tileWidth = (json.tilewidth as number) ?? 0;
+ const tileHeight = (json.tileheight as number) ?? 0;
+ if (!width || !height || !tileWidth || !tileHeight) return null;
+
+ const rawTilesets = json.tilesets as Array<Record<string, unknown>> | undefined;
+ const tilesets: TiledTilesetData[] = [];
+ const firstGids: number[] = [];
+
+ if (rawTilesets) {
+ for (const ts of rawTilesets) {
+ const firstGid = (ts.firstgid as number) ?? 1;
+ firstGids.push(firstGid);
+ tilesets.push({
+ name: (ts.name as string) ?? '',
+ image: (ts.image as string) ?? '',
+ tileWidth: (ts.tilewidth as number) ?? tileWidth,
+ tileHeight: (ts.tileheight as number) ?? tileHeight,
+ columns: (ts.columns as number) ?? 1,
+ tileCount: (ts.tilecount as number) ?? 0,
+ });
+ }
+ }
+
+ const rawLayers = json.layers as Array<Record<string, unknown>> | undefined;
+ const layers: TiledLayerData[] = [];
+
+ if (rawLayers) {
+ for (const layer of rawLayers) {
+ if (layer.type !== 'tilelayer') continue;
+ const lw = (layer.width as number) ?? width;
+ const lh = (layer.height as number) ?? height;
+ const visible = layer.visible !== false;
+ const rawData = layer.data as number[] | undefined;
+
+ const tiles = new Uint16Array(lw * lh);
+ if (rawData) {
+ const firstGid = firstGids[0] ?? 1;
+ for (let i = 0; i < rawData.length && i < tiles.length; i++) {
+ tiles[i] = convertGid(rawData[i], firstGid);
+ }
+ }
+
+ layers.push({
+ name: (layer.name as string) ?? '',
+ width: lw,
+ height: lh,
+ visible,
+ tiles,
+ });
+ }
+ }
+
+ return { width, height, tileWidth, tileHeight, layers, tilesets };
+}
+
+export function resolveRelativePath(basePath: string, relativePath: string): string {
+ const lastSlash = basePath.lastIndexOf('/');
+ const baseDir = lastSlash >= 0 ? basePath.substring(0, lastSlash + 1) : '';
+ const parts = (baseDir + relativePath).split('/');
+ const resolved: string[] = [];
+ for (const part of parts) {
+ if (part === '..') {
+ resolved.pop();
+ } else if (part !== '.' && part !== '') {
+ resolved.push(part);
+ }
+ }
+ return resolved.join('/');
+}
+
+export async function parseTiledMap(
+ jsonString: string,
+ resolveExternal?: (source: string) => Promise<string>
+): Promise<TiledMapData | null> {
+ const api = getTiledAPI();
+ if (!api) return null;
+
+ const encoder = new TextEncoder();
+ const encoded = encoder.encode(jsonString);
+ const ptr = api._malloc(encoded.byteLength);
+ api.HEAPU8.set(encoded, ptr);
+
+ const handle = api.tiled_loadMap(ptr, encoded.byteLength);
+ api._free(ptr);
+
+ if (handle === 0) return null;
+
+ try {
+ const extCount = api.tiled_getExternalTilesetCount(handle);
+ for (let i = 0; i < extCount; i++) {
+ const source = api.tiled_getExternalTilesetSource(handle, i);
+ if (!resolveExternal) {
+ api.tiled_freeMap(handle);
+ return null;
+ }
+ const tsjContent = await resolveExternal(source);
+ const tsjEncoded = encoder.encode(tsjContent);
+ const tsjPtr = api._malloc(tsjEncoded.byteLength);
+ api.HEAPU8.set(tsjEncoded, tsjPtr);
+ const ok = api.tiled_loadExternalTileset(handle, i, tsjPtr, tsjEncoded.byteLength);
+ api._free(tsjPtr);
+ if (!ok) {
+ api.tiled_freeMap(handle);
+ return null;
+ }
+ }
+
+ if (!api.tiled_finalize(handle)) {
+ api.tiled_freeMap(handle);
+ return null;
+ }
+
+ const result: TiledMapData = {
+ width: api.tiled_getMapWidth(handle),
+ height: api.tiled_getMapHeight(handle),
+ tileWidth: api.tiled_getMapTileWidth(handle),
+ tileHeight: api.tiled_getMapTileHeight(handle),
+ layers: [],
+ tilesets: [],
+ };
+
+ const layerCount = api.tiled_getLayerCount(handle);
+ for (let i = 0; i < layerCount; i++) {
+ const w = api.tiled_getLayerWidth(handle, i);
+ const h = api.tiled_getLayerHeight(handle, i);
+ const tileCount = w * h;
+ const tileBytes = tileCount * 2;
+ const tilePtr = api._malloc(tileBytes);
+ api.tiled_getLayerTiles(handle, i, tilePtr, tileCount);
+ const tiles = new Uint16Array(tileCount);
+ tiles.set(new Uint16Array(api.HEAPU8.buffer, tilePtr, tileCount));
+ api._free(tilePtr);
+
+ result.layers.push({
+ name: api.tiled_getLayerName(handle, i),
+ width: w,
+ height: h,
+ visible: api.tiled_getLayerVisible(handle, i),
+ tiles,
+ });
+ }
+
+ const tilesetCount = api.tiled_getTilesetCount(handle);
+ for (let i = 0; i < tilesetCount; i++) {
+ result.tilesets.push({
+ name: api.tiled_getTilesetName(handle, i),
+ image: api.tiled_getTilesetImage(handle, i),
+ tileWidth: api.tiled_getTilesetTileWidth(handle, i),
+ tileHeight: api.tiled_getTilesetTileHeight(handle, i),
+ columns: api.tiled_getTilesetColumns(handle, i),
+ tileCount: api.tiled_getTilesetTileCount(handle, i),
+ });
+ }
+
+ api.tiled_freeMap(handle);
+ return result;
+ } catch {
+ api.tiled_freeMap(handle);
+ return null;
+ }
+}
+
+export function loadTiledMap(
+ world: World,
+ mapData: TiledMapData,
+ textureHandles: Map<string, number>,
+): Entity[] {
+ const entities: Entity[] = [];
+ const firstTileset = mapData.tilesets[0];
+
+ let layerIndex = 0;
+ for (const layer of mapData.layers) {
+ if (!layer.visible) continue;
+
+ const entity = world.spawn();
+ world.insert(entity, Transform, {});
+
+ const textureHandle = firstTileset
+ ? (textureHandles.get(firstTileset.image) ?? 0)
+ : 0;
+ const columns = firstTileset?.columns ?? 1;
+
+ world.insert(entity, TilemapLayer, {
+ width: layer.width,
+ height: layer.height,
+ tileWidth: mapData.tileWidth,
+ tileHeight: mapData.tileHeight,
+ texture: textureHandle,
+ tilesetColumns: columns,
+ layer: layerIndex,
+ tiles: Array.from(layer.tiles),
+ });
+
+ entities.push(entity);
+ layerIndex++;
+ }
+
+ return entities;
+}
diff --git a/sdk/src/tilemap/tilemapAPI.ts b/sdk/src/tilemap/tilemapAPI.ts
new file mode 100644
index 000000000..b6e45b128
--- /dev/null
+++ b/sdk/src/tilemap/tilemapAPI.ts
@@ -0,0 +1,117 @@
+import type { ESEngineModule } from '../wasm';
+
+interface TilemapModule {
+ tilemap_initLayer(entity: number, width: number, height: number,
+ tileWidth: number, tileHeight: number): void;
+ tilemap_destroyLayer(entity: number): void;
+ tilemap_setTile(entity: number, x: number, y: number, tileId: number): void;
+ tilemap_getTile(entity: number, x: number, y: number): number;
+ tilemap_fillRect(entity: number, x: number, y: number,
+ w: number, h: number, tileId: number): void;
+ tilemap_setTiles(entity: number, tilesPtr: number, count: number): void;
+ tilemap_hasLayer(entity: number): boolean;
+ tilemap_submitLayer(entity: number, textureId: number,
+ sortLayer: number, depth: number,
+ tilesetColumns: number,
+ uvTileWidth: number, uvTileHeight: number,
+ originX: number, originY: number,
+ camLeft: number, camBottom: number,
+ camRight: number, camTop: number): void;
+
+ tiled_loadMap(dataPtr: number, dataSize: number): number;
+ tiled_freeMap(handle: number): void;
+ tiled_getExternalTilesetCount(handle: number): number;
+ tiled_getExternalTilesetSource(handle: number, index: number): string;
+ tiled_loadExternalTileset(handle: number, index: number,
+ dataPtr: number, dataSize: number): boolean;
+ tiled_finalize(handle: number): boolean;
+ tiled_getMapWidth(handle: number): number;
+ tiled_getMapHeight(handle: number): number;
+ tiled_getMapTileWidth(handle: number): number;
+ tiled_getMapTileHeight(handle: number): number;
+ tiled_getLayerCount(handle: number): number;
+ tiled_getLayerName(handle: number, index: number): string;
+ tiled_getLayerWidth(handle: number, index: number): number;
+ tiled_getLayerHeight(handle: number, index: number): number;
+ tiled_getLayerVisible(handle: number, index: number): boolean;
+ tiled_getLayerTiles(handle: number, index: number,
+ outPtr: number, maxCount: number): number;
+ tiled_getTilesetCount(handle: number): number;
+ tiled_getTilesetName(handle: number, index: number): string;
+ tiled_getTilesetImage(handle: number, index: number): string;
+ tiled_getTilesetTileWidth(handle: number, index: number): number;
+ tiled_getTilesetTileHeight(handle: number, index: number): number;
+ tiled_getTilesetColumns(handle: number, index: number): number;
+ tiled_getTilesetTileCount(handle: number, index: number): number;
+
+ HEAPU8: Uint8Array;
+ _malloc(size: number): number;
+ _free(ptr: number): void;
+}
+
+let module_: TilemapModule | null = null;
+
+export function initTilemapAPI(m: ESEngineModule): void {
+ module_ = m as unknown as TilemapModule;
+}
+
+export function shutdownTilemapAPI(): void {
+ module_ = null;
+}
+
+export function getTiledAPI(): TilemapModule | null {
+ return module_;
+}
+
+export const TilemapAPI = {
+ initLayer(entity: number, width: number, height: number,
+ tileWidth: number, tileHeight: number): void {
+ module_?.tilemap_initLayer(entity, width, height, tileWidth, tileHeight);
+ },
+
+ destroyLayer(entity: number): void {
+ module_?.tilemap_destroyLayer(entity);
+ },
+
+ setTile(entity: number, x: number, y: number, tileId: number): void {
+ module_?.tilemap_setTile(entity, x, y, tileId);
+ },
+
+ getTile(entity: number, x: number, y: number): number {
+ if (!module_) return 0;
+ return module_.tilemap_getTile(entity, x, y);
+ },
+
+ fillRect(entity: number, x: number, y: number,
+ w: number, h: number, tileId: number): void {
+ module_?.tilemap_fillRect(entity, x, y, w, h, tileId);
+ },
+
+ setTiles(entity: number, tiles: Uint16Array): void {
+ if (!module_) return;
+ const bytes = tiles.byteLength;
+ const ptr = module_._malloc(bytes);
+ new Uint16Array(module_.HEAPU8.buffer, ptr, tiles.length).set(tiles);
+ module_.tilemap_setTiles(entity, ptr, tiles.length);
+ module_._free(ptr);
+ },
+
+ hasLayer(entity: number): boolean {
+ if (!module_) return false;
+ return module_.tilemap_hasLayer(entity);
+ },
+
+ submitLayer(entity: number, textureId: number,
+ sortLayer: number, depth: number,
+ tilesetColumns: number,
+ uvTileWidth: number, uvTileHeight: number,
+ originX: number, originY: number,
+ camLeft: number, camBottom: number,
+ camRight: number, camTop: number): void {
+ module_?.tilemap_submitLayer(
+ entity, textureId, sortLayer, depth,
+ tilesetColumns, uvTileWidth, uvTileHeight,
+ originX, originY, camLeft, camBottom, camRight, camTop
+ );
+ },
+};
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
new file mode 100644
index 000000000..61b52f74f
--- /dev/null
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -0,0 +1,160 @@
+import type { App, Plugin } from '../app';
+import type { ESEngineModule } from '../wasm';
+import { Transform, type TransformData } from '../component';
+import { UICameraInfo, type UICameraData } from '../ui/UICameraInfo';
+import { initTilemapAPI, shutdownTilemapAPI, TilemapAPI } from './tilemapAPI';
+import { Tilemap, TilemapLayer } from './components';
+import { getTextureDimensions, clearTextureDimensionsCache, getTilemapSource } from './tilesetCache';
+
+const MAX_CAMERA_EXTENT = 1e6;
+const SYNTHETIC_KEY_BASE = 0x40000000;
+const MAX_LAYERS_PER_ENTITY = 256;
+
+export class TilemapPlugin implements Plugin {
+ name = 'TilemapPlugin';
+
+ private initializedLayers_ = new Set<number>();
+ private sourceEntityKeys_ = new Map<number, number[]>();
+
+ build(app: App): void {
+ const module = app.wasmModule as ESEngineModule;
+ initTilemapAPI(module);
+
+ const world = app.world;
+ const initializedLayers = this.initializedLayers_;
+ const sourceEntityKeys = this.sourceEntityKeys_;
+
+ app.pipeline?.setTilemapRenderer(() => {
+ const cam = app.getResource<UICameraData>(UICameraInfo);
+ const camLeft = cam?.valid ? cam.worldLeft : -MAX_CAMERA_EXTENT;
+ const camBottom = cam?.valid ? cam.worldBottom : -MAX_CAMERA_EXTENT;
+ const camRight = cam?.valid ? cam.worldRight : MAX_CAMERA_EXTENT;
+ const camTop = cam?.valid ? cam.worldTop : MAX_CAMERA_EXTENT;
+
+ const layerEntities = world.getEntitiesWithComponents(
+ [TilemapLayer, Transform],
+ );
+ for (const entity of layerEntities) {
+ const layerData = world.tryGet(entity, TilemapLayer) as {
+ width: number;
+ height: number;
+ tileWidth: number;
+ tileHeight: number;
+ texture: number;
+ tilesetColumns: number;
+ layer: number;
+ tiles: number[];
+ } | null;
+ const transform = world.tryGet(entity, Transform) as TransformData | null;
+ if (!layerData || !transform) continue;
+
+ const textureHandle = layerData.texture;
+ if (!textureHandle) continue;
+
+ const dims = getTextureDimensions(textureHandle);
+ if (!dims) continue;
+
+ if (!initializedLayers.has(entity)) {
+ 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);
+ }
+ initializedLayers.add(entity);
+ }
+
+ const uvTileWidth = layerData.tileWidth / dims.width;
+ const uvTileHeight = layerData.tileHeight / dims.height;
+
+ TilemapAPI.submitLayer(
+ entity,
+ textureHandle,
+ layerData.layer,
+ 0,
+ layerData.tilesetColumns,
+ uvTileWidth,
+ uvTileHeight,
+ transform.worldPosition.x,
+ transform.worldPosition.y,
+ camLeft, camBottom, camRight, camTop,
+ );
+ }
+
+ const tilemapEntities = world.getEntitiesWithComponents(
+ [Tilemap, Transform],
+ );
+ for (const entity of tilemapEntities) {
+ if (world.tryGet(entity, TilemapLayer)) continue;
+
+ const tilemap = world.tryGet(entity, Tilemap) as { source: string } | null;
+ const transform = world.tryGet(entity, Transform) as TransformData | null;
+ if (!tilemap?.source || !transform) continue;
+
+ const cached = getTilemapSource(tilemap.source);
+ if (!cached) continue;
+
+ if (!sourceEntityKeys.has(entity)) {
+ const keys: number[] = [];
+ for (let i = 0; i < cached.layers.length; i++) {
+ const key = SYNTHETIC_KEY_BASE + entity * MAX_LAYERS_PER_ENTITY + i;
+ const layer = cached.layers[i];
+ TilemapAPI.initLayer(
+ key, layer.width, layer.height,
+ cached.tileWidth, cached.tileHeight,
+ );
+ if (layer.tiles.length > 0) {
+ TilemapAPI.setTiles(key, layer.tiles);
+ }
+ keys.push(key);
+ initializedLayers.add(key);
+ }
+ sourceEntityKeys.set(entity, keys);
+ }
+
+ const keys = sourceEntityKeys.get(entity)!;
+ for (let i = 0; i < cached.layers.length && i < keys.length; i++) {
+ const key = keys[i];
+ const tileset = cached.tilesets[0];
+ if (!tileset) continue;
+
+ const dims = getTextureDimensions(tileset.textureHandle);
+ if (!dims) continue;
+
+ const uvTileWidth = cached.tileWidth / dims.width;
+ const uvTileHeight = cached.tileHeight / dims.height;
+
+ TilemapAPI.submitLayer(
+ key,
+ tileset.textureHandle,
+ i,
+ 0,
+ tileset.columns,
+ uvTileWidth,
+ uvTileHeight,
+ transform.worldPosition.x,
+ transform.worldPosition.y,
+ camLeft, camBottom, camRight, camTop,
+ );
+ }
+ }
+ });
+ }
+
+ cleanup(): void {
+ for (const entity of this.initializedLayers_) {
+ TilemapAPI.destroyLayer(entity);
+ }
+ this.initializedLayers_.clear();
+ this.sourceEntityKeys_.clear();
+ clearTextureDimensionsCache();
+ shutdownTilemapAPI();
+ }
+}
+
+export const tilemapPlugin = new TilemapPlugin();
diff --git a/sdk/src/tilemap/tilesetCache.ts b/sdk/src/tilemap/tilesetCache.ts
new file mode 100644
index 000000000..bbc84003b
--- /dev/null
+++ b/sdk/src/tilemap/tilesetCache.ts
@@ -0,0 +1,50 @@
+export interface TextureDimensions {
+ width: number;
+ height: number;
+}
+
+export interface LoadedTilemapLayer {
+ name: string;
+ width: number;
+ height: number;
+ tiles: Uint16Array;
+}
+
+export interface LoadedTilemapTileset {
+ textureHandle: number;
+ columns: number;
+}
+
+export interface LoadedTilemapSource {
+ tileWidth: number;
+ tileHeight: number;
+ layers: LoadedTilemapLayer[];
+ tilesets: LoadedTilemapTileset[];
+}
+
+const texDimsCache_ = new Map<number, TextureDimensions>();
+const tilemapCache_ = new Map<string, LoadedTilemapSource>();
+
+export function registerTextureDimensions(handle: number, width: number, height: number): void {
+ texDimsCache_.set(handle, { width, height });
+}
+
+export function getTextureDimensions(handle: number): TextureDimensions | undefined {
+ return texDimsCache_.get(handle);
+}
+
+export function clearTextureDimensionsCache(): void {
+ texDimsCache_.clear();
+}
+
+export function registerTilemapSource(path: string, data: LoadedTilemapSource): void {
+ tilemapCache_.set(path, data);
+}
+
+export function getTilemapSource(path: string): LoadedTilemapSource | undefined {
+ return tilemapCache_.get(path);
+}
+
+export function clearTilemapSourceCache(): void {
+ tilemapCache_.clear();
+}
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index be901e364..a101ded00 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -145,6 +145,9 @@ export interface ESEngineModule {
postprocess_isInitialized(): boolean;
postprocess_setBypass(bypass: boolean): void;
postprocess_isBypassed(): boolean;
+ postprocess_clearPasses(): void;
+ postprocess_setOutputTarget(fboId: number): void;
+ postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
// Renderer API (RenderFrame)
renderer_init(width: number, height: number): void;
@@ -166,6 +169,24 @@ export interface ESEngineModule {
particle_stop?(registry: CppRegistry, entity: number): void;
particle_reset?(registry: CppRegistry, entity: number): void;
particle_getAliveCount?(entity: number): number;
+
+ // Tilemap API
+ tilemap_initLayer?(entity: number, width: number, height: number,
+ tileWidth: number, tileHeight: number): void;
+ tilemap_destroyLayer?(entity: number): void;
+ tilemap_setTile?(entity: number, x: number, y: number, tileId: number): void;
+ tilemap_getTile?(entity: number, x: number, y: number): number;
+ tilemap_fillRect?(entity: number, x: number, y: number,
+ w: number, h: number, tileId: number): void;
+ tilemap_setTiles?(entity: number, tilesPtr: number, count: number): void;
+ tilemap_hasLayer?(entity: number): boolean;
+ tilemap_submitLayer?(entity: number, textureId: number,
+ sortLayer: number, depth: number,
+ tilesetColumns: number,
+ uvTileWidth: number, uvTileHeight: number,
+ originX: number, originY: number,
+ camLeft: number, camBottom: number,
+ camRight: number, camTop: number): void;
renderer_setStage(stage: number): void;
renderer_createTarget(width: number, height: number, flags: number): number;
renderer_releaseTarget(handle: number): void;
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index e572499dd..6f23399c0 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -5,6 +5,7 @@ import { uiPlugins } from './uiPlugins';
import { animationPlugin } from './animation';
import { audioPlugin } from './audio';
import { particlePlugin } from './particle';
+import { tilemapPlugin } from './tilemap';
export { uiPlugins };
export { textPlugin, TextPlugin } from './ui/TextPlugin';
@@ -31,7 +32,7 @@ export { AnimationPlugin, animationPlugin } from './animation';
export { AudioPlugin, audioPlugin } from './audio';
export { ParticlePlugin, particlePlugin } from './particle';
-const defaultPlugins = [...uiPlugins, animationPlugin, audioPlugin, particlePlugin];
+const defaultPlugins = [...uiPlugins, animationPlugin, audioPlugin, particlePlugin, tilemapPlugin];
export function createWebApp(module: ESEngineModule, options?: WebAppOptions): App {
return _createWebApp(module, { plugins: defaultPlugins, ...options });
diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.ts
new file mode 100644
index 000000000..5bd9f270e
--- /dev/null
+++ b/sdk/tests/tilemap.test.ts
@@ -0,0 +1,453 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import {
+ Tilemap,
+ TilemapLayer,
+ TilemapAPI,
+ initTilemapAPI,
+ shutdownTilemapAPI,
+} from '../src/tilemap';
+import {
+ registerTextureDimensions,
+ getTextureDimensions,
+ clearTextureDimensionsCache,
+ registerTilemapSource,
+ getTilemapSource,
+ clearTilemapSourceCache,
+} from '../src/tilemap/tilesetCache';
+import { loadTiledMap, parseTmjJson, resolveRelativePath } from '../src/tilemap/tiledLoader';
+import type { TiledMapData } from '../src/tilemap/tiledLoader';
+import { clearUserComponents } from '../src/component';
+import type { World } from '../src/world';
+import type { Entity } from '../src/types';
+
+describe('Tilemap Components', () => {
+ beforeEach(() => {
+ clearUserComponents();
+ });
+
+ describe('Tilemap component', () => {
+ it('should be defined with correct name', () => {
+ expect(Tilemap._name).toBe('Tilemap');
+ });
+
+ it('should have correct defaults', () => {
+ expect(Tilemap._default).toEqual({
+ source: '',
+ });
+ });
+
+ it('should not be a builtin', () => {
+ expect(Tilemap._builtin).toBe(false);
+ });
+ });
+
+ describe('TilemapLayer component', () => {
+ it('should be defined with correct name', () => {
+ expect(TilemapLayer._name).toBe('TilemapLayer');
+ });
+
+ it('should have texture field defaulting to 0', () => {
+ expect(TilemapLayer._default.texture).toBe(0);
+ });
+
+ it('should have tilesetColumns field defaulting to 1', () => {
+ expect(TilemapLayer._default.tilesetColumns).toBe(1);
+ });
+
+ it('should have tileWidth and tileHeight defaults', () => {
+ expect(TilemapLayer._default.tileWidth).toBe(32);
+ expect(TilemapLayer._default.tileHeight).toBe(32);
+ });
+
+ it('should have correct defaults', () => {
+ expect(TilemapLayer._default).toEqual({
+ width: 10,
+ height: 10,
+ tileWidth: 32,
+ tileHeight: 32,
+ texture: 0,
+ tilesetColumns: 1,
+ layer: 0,
+ tiles: [],
+ });
+ });
+
+ 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([]);
+ });
+ });
+});
+
+describe('TextureDimensions cache', () => {
+ beforeEach(() => {
+ clearTextureDimensionsCache();
+ });
+
+ it('should register and retrieve dimensions', () => {
+ registerTextureDimensions(42, 256, 512);
+ const dims = getTextureDimensions(42);
+ expect(dims).toEqual({ width: 256, height: 512 });
+ });
+
+ it('should return undefined for unregistered handle', () => {
+ expect(getTextureDimensions(99)).toBeUndefined();
+ });
+
+ it('should overwrite existing entry', () => {
+ registerTextureDimensions(42, 100, 100);
+ registerTextureDimensions(42, 200, 300);
+ expect(getTextureDimensions(42)).toEqual({ width: 200, height: 300 });
+ });
+
+ it('should clear all entries', () => {
+ registerTextureDimensions(1, 64, 64);
+ registerTextureDimensions(2, 128, 128);
+ clearTextureDimensionsCache();
+ expect(getTextureDimensions(1)).toBeUndefined();
+ expect(getTextureDimensions(2)).toBeUndefined();
+ });
+});
+
+describe('TilemapSource cache', () => {
+ beforeEach(() => {
+ clearTilemapSourceCache();
+ });
+
+ it('should register and retrieve tilemap source', () => {
+ const source = {
+ tileWidth: 16,
+ tileHeight: 16,
+ layers: [{ name: 'Ground', width: 10, height: 10, tiles: new Uint16Array([1, 2, 3]) }],
+ tilesets: [{ textureHandle: 42, columns: 8 }],
+ };
+ registerTilemapSource('maps/level1.tmj', source);
+ expect(getTilemapSource('maps/level1.tmj')).toBe(source);
+ });
+
+ it('should return undefined for unregistered path', () => {
+ expect(getTilemapSource('nonexistent.tmj')).toBeUndefined();
+ });
+
+ it('should clear all entries', () => {
+ const source = {
+ tileWidth: 16, tileHeight: 16,
+ layers: [], tilesets: [],
+ };
+ registerTilemapSource('a.tmj', source);
+ registerTilemapSource('b.tmj', source);
+ clearTilemapSourceCache();
+ expect(getTilemapSource('a.tmj')).toBeUndefined();
+ expect(getTilemapSource('b.tmj')).toBeUndefined();
+ });
+});
+
+describe('parseTmjJson', () => {
+ it('should parse a valid tmj json', () => {
+ const json = {
+ width: 20,
+ height: 15,
+ tilewidth: 16,
+ tileheight: 16,
+ tilesets: [{
+ firstgid: 1,
+ name: 'terrain',
+ image: 'terrain.png',
+ tilewidth: 16,
+ tileheight: 16,
+ columns: 8,
+ tilecount: 64,
+ }],
+ layers: [{
+ type: 'tilelayer',
+ name: 'Ground',
+ width: 20,
+ height: 15,
+ visible: true,
+ data: [0, 1, 2, 3],
+ }],
+ };
+
+ const result = parseTmjJson(json);
+ expect(result).not.toBeNull();
+ expect(result!.width).toBe(20);
+ expect(result!.height).toBe(15);
+ expect(result!.tileWidth).toBe(16);
+ expect(result!.tileHeight).toBe(16);
+ expect(result!.layers).toHaveLength(1);
+ expect(result!.layers[0].name).toBe('Ground');
+ expect(result!.tilesets).toHaveLength(1);
+ expect(result!.tilesets[0].name).toBe('terrain');
+ });
+
+ it('should return null for invalid json', () => {
+ expect(parseTmjJson({})).toBeNull();
+ expect(parseTmjJson({ width: 10, height: 0, tilewidth: 16, tileheight: 16 })).toBeNull();
+ });
+
+ it('should convert GIDs to local tile IDs', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 32, tileheight: 32,
+ tilesets: [{ firstgid: 1, name: 'ts', image: 'ts.png', tilewidth: 32, tileheight: 32, columns: 4, tilecount: 16 }],
+ layers: [{ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true, data: [0, 3] }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers[0].tiles[0]).toBe(0);
+ expect(result!.layers[0].tiles[1]).toBe(3);
+ });
+
+ it('should skip non-tilelayer layers', () => {
+ const json = {
+ width: 10, height: 10, tilewidth: 32, tileheight: 32,
+ layers: [
+ { type: 'objectgroup', name: 'Objects' },
+ { type: 'tilelayer', name: 'Ground', width: 10, height: 10, visible: true, data: [] },
+ ],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers).toHaveLength(1);
+ expect(result!.layers[0].name).toBe('Ground');
+ });
+});
+
+describe('resolveRelativePath', () => {
+ it('should resolve relative path from base', () => {
+ expect(resolveRelativePath('maps/level1.tmj', 'tileset.png')).toBe('maps/tileset.png');
+ });
+
+ it('should resolve parent directory references', () => {
+ expect(resolveRelativePath('maps/level1.tmj', '../images/tileset.png')).toBe('images/tileset.png');
+ });
+
+ it('should handle base path without directory', () => {
+ expect(resolveRelativePath('level1.tmj', 'tileset.png')).toBe('tileset.png');
+ });
+});
+
+describe('TilemapAPI', () => {
+ const mockModule = {
+ tilemap_initLayer: vi.fn(),
+ tilemap_destroyLayer: vi.fn(),
+ tilemap_setTile: vi.fn(),
+ tilemap_getTile: vi.fn().mockReturnValue(5),
+ tilemap_fillRect: vi.fn(),
+ tilemap_setTiles: vi.fn(),
+ tilemap_hasLayer: vi.fn().mockReturnValue(true),
+ tilemap_submitLayer: vi.fn(),
+ HEAPU8: new Uint8Array(1024),
+ _malloc: vi.fn().mockReturnValue(256),
+ _free: vi.fn(),
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ shutdownTilemapAPI();
+ });
+
+ it('should not call wasm before init', () => {
+ TilemapAPI.initLayer(1, 10, 8, 32, 32);
+ expect(mockModule.tilemap_initLayer).not.toHaveBeenCalled();
+ });
+
+ it('should delegate initLayer to wasm', () => {
+ initTilemapAPI(mockModule as any);
+ TilemapAPI.initLayer(1, 10, 8, 32, 32);
+ expect(mockModule.tilemap_initLayer).toHaveBeenCalledWith(1, 10, 8, 32, 32);
+ });
+
+ it('should delegate destroyLayer to wasm', () => {
+ initTilemapAPI(mockModule as any);
+ TilemapAPI.destroyLayer(1);
+ expect(mockModule.tilemap_destroyLayer).toHaveBeenCalledWith(1);
+ });
+
+ it('should delegate setTile to wasm', () => {
+ initTilemapAPI(mockModule as any);
+ TilemapAPI.setTile(1, 3, 4, 42);
+ expect(mockModule.tilemap_setTile).toHaveBeenCalledWith(1, 3, 4, 42);
+ });
+
+ it('should delegate getTile to wasm', () => {
+ initTilemapAPI(mockModule as any);
+ const result = TilemapAPI.getTile(1, 3, 4);
+ expect(mockModule.tilemap_getTile).toHaveBeenCalledWith(1, 3, 4);
+ expect(result).toBe(5);
+ });
+
+ it('should return 0 for getTile before init', () => {
+ expect(TilemapAPI.getTile(1, 0, 0)).toBe(0);
+ });
+
+ it('should delegate fillRect to wasm', () => {
+ initTilemapAPI(mockModule as any);
+ TilemapAPI.fillRect(1, 2, 3, 5, 4, 7);
+ expect(mockModule.tilemap_fillRect).toHaveBeenCalledWith(1, 2, 3, 5, 4, 7);
+ });
+
+ it('should delegate hasLayer to wasm', () => {
+ initTilemapAPI(mockModule as any);
+ const result = TilemapAPI.hasLayer(1);
+ expect(mockModule.tilemap_hasLayer).toHaveBeenCalledWith(1);
+ expect(result).toBe(true);
+ });
+
+ it('should return false for hasLayer before init', () => {
+ expect(TilemapAPI.hasLayer(1)).toBe(false);
+ });
+
+ it('should be safe to call after shutdown', () => {
+ initTilemapAPI(mockModule as any);
+ shutdownTilemapAPI();
+ TilemapAPI.initLayer(1, 10, 8, 32, 32);
+ expect(mockModule.tilemap_initLayer).not.toHaveBeenCalled();
+ });
+});
+
+describe('loadTiledMap', () => {
+ function createMockWorld(): World {
+ let nextId = 1;
+ const components = new Map<number, Map<string, any>>();
+
+ return {
+ spawn: vi.fn(() => {
+ const id = nextId++ as Entity;
+ components.set(id, new Map());
+ return id;
+ }),
+ insert: vi.fn((entity: Entity, comp: any, data: any) => {
+ const map = components.get(entity)!;
+ map.set(comp._name, data);
+ }),
+ setParent: vi.fn(),
+ get: vi.fn((entity: Entity, comp: any) => {
+ return components.get(entity)?.get(comp._name) ?? null;
+ }),
+ } as unknown as World;
+ }
+
+ const sampleMapData: TiledMapData = {
+ width: 20,
+ height: 15,
+ tileWidth: 16,
+ tileHeight: 16,
+ layers: [
+ {
+ name: 'Ground',
+ width: 20,
+ height: 15,
+ visible: true,
+ tiles: new Uint16Array([1, 2, 3, 0, 0]),
+ },
+ {
+ name: 'Objects',
+ width: 20,
+ height: 15,
+ visible: true,
+ tiles: new Uint16Array([0, 0, 5, 6, 7]),
+ },
+ ],
+ tilesets: [
+ {
+ name: 'terrain',
+ image: 'terrain.png',
+ tileWidth: 16,
+ tileHeight: 16,
+ columns: 8,
+ tileCount: 64,
+ },
+ ],
+ };
+
+ it('should create one entity per visible layer', () => {
+ const world = createMockWorld();
+ const textureHandles = new Map([['terrain.png', 42]]);
+
+ const entities = loadTiledMap(world, sampleMapData, textureHandles);
+
+ expect(entities).toHaveLength(2);
+ expect(world.spawn).toHaveBeenCalledTimes(2);
+ });
+
+ it('should skip invisible layers', () => {
+ const world = createMockWorld();
+ const textureHandles = new Map([['terrain.png', 42]]);
+ const mapData: TiledMapData = {
+ ...sampleMapData,
+ layers: [
+ { ...sampleMapData.layers[0], visible: false },
+ sampleMapData.layers[1],
+ ],
+ };
+
+ const entities = loadTiledMap(world, mapData, textureHandles);
+
+ expect(entities).toHaveLength(1);
+ });
+
+ it('should insert TilemapLayer with correct texture handle and columns', () => {
+ const world = createMockWorld();
+ const textureHandles = new Map([['terrain.png', 42]]);
+
+ loadTiledMap(world, sampleMapData, textureHandles);
+
+ const insertCalls = (world.insert as any).mock.calls;
+ 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].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);
+ });
+
+ it('should assign incremental layer sort order', () => {
+ const world = createMockWorld();
+ const textureHandles = new Map([['terrain.png', 42]]);
+
+ loadTiledMap(world, sampleMapData, textureHandles);
+
+ 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]);
+ });
+
+ it('should use texture handle 0 when tileset image is not in textureHandles', () => {
+ const world = createMockWorld();
+ const textureHandles = new Map<string, number>();
+
+ loadTiledMap(world, sampleMapData, textureHandles);
+
+ const insertCalls = (world.insert as any).mock.calls;
+ const layerInsert = insertCalls.find((c: any) => c[1]._name === 'TilemapLayer');
+ expect(layerInsert[2].texture).toBe(0);
+ });
+
+ it('should return empty array for map with no layers', () => {
+ const world = createMockWorld();
+ const textureHandles = new Map([['terrain.png', 42]]);
+ const emptyMap: TiledMapData = { ...sampleMapData, layers: [] };
+
+ const entities = loadTiledMap(world, emptyMap, textureHandles);
+
+ expect(entities).toHaveLength(0);
+ expect(world.spawn).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/esengine/tilemap/TiledMapLoader.cpp b/src/esengine/tilemap/TiledMapLoader.cpp
new file mode 100644
index 000000000..44608d3bb
--- /dev/null
+++ b/src/esengine/tilemap/TiledMapLoader.cpp
@@ -0,0 +1,237 @@
+#define CUTE_TILED_NO_EXTERNAL_TILESET_WARNING
+#define CUTE_TILED_IMPLEMENTATION
+#include "cute_tiled.h"
+
+#include "TiledMapLoader.hpp"
+#include "TilemapSystem.hpp"
+
+#include <cstring>
+
+namespace esengine {
+namespace tilemap {
+
+u32 TiledMapLoader::loadFromMemory(const char* data, u32 size) {
+ auto* map = cute_tiled_load_map_from_memory(data, static_cast<int>(size), nullptr);
+ if (!map) {
+ return 0;
+ }
+
+ u32 handle = next_handle_++;
+ auto& pending = maps_[handle];
+ pending.raw_map = map;
+ pending.finalized = false;
+
+ pending.result.width = static_cast<u32>(map->width);
+ pending.result.height = static_cast<u32>(map->height);
+ pending.result.tile_width = static_cast<u32>(map->tilewidth);
+ pending.result.tile_height = static_cast<u32>(map->tileheight);
+
+ for (auto* ts = map->tilesets; ts; ts = ts->next) {
+ TiledTilesetInfo info;
+ info.first_gid = static_cast<u32>(ts->firstgid);
+
+ if (ts->source.ptr && ts->source.ptr[0] != '\0') {
+ info.name = "";
+ info.image = "";
+ info.tile_width = 0;
+ info.tile_height = 0;
+ info.columns = 0;
+ info.tile_count = 0;
+
+ ExternalTilesetEntry entry;
+ entry.map_tileset = ts;
+ entry.loaded = nullptr;
+ entry.source = ts->source.ptr;
+ pending.external_tilesets.push_back(std::move(entry));
+ } else {
+ info.name = ts->name.ptr ? ts->name.ptr : "";
+ info.image = ts->image.ptr ? ts->image.ptr : "";
+ info.tile_width = static_cast<u32>(ts->tilewidth);
+ info.tile_height = static_cast<u32>(ts->tileheight);
+ info.columns = static_cast<u32>(ts->columns);
+ info.tile_count = static_cast<u32>(ts->tilecount);
+ }
+
+ pending.result.tilesets.push_back(std::move(info));
+ }
+
+ return handle;
+}
+
+u32 TiledMapLoader::getExternalTilesetCount(u32 handle) const {
+ auto it = maps_.find(handle);
+ if (it == maps_.end()) {
+ return 0;
+ }
+ return static_cast<u32>(it->second.external_tilesets.size());
+}
+
+std::string TiledMapLoader::getExternalTilesetSource(u32 handle, u32 index) const {
+ auto it = maps_.find(handle);
+ if (it == maps_.end() || index >= it->second.external_tilesets.size()) {
+ return "";
+ }
+ return it->second.external_tilesets[index].source;
+}
+
+bool TiledMapLoader::loadExternalTileset(u32 handle, u32 index,
+ const char* data, u32 size) {
+ auto it = maps_.find(handle);
+ if (it == maps_.end() || index >= it->second.external_tilesets.size()) {
+ return false;
+ }
+
+ auto& entry = it->second.external_tilesets[index];
+ if (entry.loaded) {
+ return true;
+ }
+
+ auto* tileset = cute_tiled_load_external_tileset_from_memory(
+ data, static_cast<int>(size), nullptr);
+ if (!tileset) {
+ return false;
+ }
+
+ entry.loaded = tileset;
+
+ u32 firstGid = static_cast<u32>(entry.map_tileset->firstgid);
+ for (auto& tsInfo : it->second.result.tilesets) {
+ if (tsInfo.first_gid == firstGid && tsInfo.tile_count == 0) {
+ tsInfo.name = tileset->name.ptr ? tileset->name.ptr : "";
+ tsInfo.image = tileset->image.ptr ? tileset->image.ptr : "";
+ tsInfo.tile_width = static_cast<u32>(tileset->tilewidth);
+ tsInfo.tile_height = static_cast<u32>(tileset->tileheight);
+ tsInfo.columns = static_cast<u32>(tileset->columns);
+ tsInfo.tile_count = static_cast<u32>(tileset->tilecount);
+ break;
+ }
+ }
+
+ return true;
+}
+
+u16 TiledMapLoader::convertGid(int gid, const std::vector<TiledTilesetInfo>& tilesets) {
+ if (gid == 0) {
+ return EMPTY_TILE;
+ }
+
+ int flipH = 0, flipV = 0, flipD = 0;
+ cute_tiled_get_flags(gid, &flipH, &flipV, &flipD);
+ int rawGid = cute_tiled_unset_flags(gid);
+
+ u16 localId = 0;
+ for (auto it = tilesets.rbegin(); it != tilesets.rend(); ++it) {
+ if (static_cast<u32>(rawGid) >= it->first_gid) {
+ localId = static_cast<u16>(rawGid - static_cast<int>(it->first_gid) + 1);
+ break;
+ }
+ }
+
+ if (localId == 0) {
+ return EMPTY_TILE;
+ }
+
+ u16 result = localId & TILE_ID_MASK;
+ if (flipH) { result |= TILE_FLIP_H; }
+ if (flipV) { result |= TILE_FLIP_V; }
+ if (flipD) { result |= TILE_FLIP_D; }
+
+ return result;
+}
+
+void TiledMapLoader::collectLayers(cute_tiled_map_t* map, TiledMapData& result,
+ const std::vector<TiledTilesetInfo>& tilesets) {
+ auto processLayer = [&](auto& self, auto* layer) -> void {
+ for (; layer; layer = layer->next) {
+ if (layer->type.ptr && std::strcmp(layer->type.ptr, "group") == 0) {
+ self(self, layer->layers);
+ continue;
+ }
+
+ if (!layer->type.ptr || std::strcmp(layer->type.ptr, "tilelayer") != 0) {
+ continue;
+ }
+
+ if (!layer->data || layer->data_count <= 0) {
+ continue;
+ }
+
+ TiledLayerInfo info;
+ info.name = layer->name.ptr ? layer->name.ptr : "";
+ info.width = static_cast<u32>(layer->width);
+ info.height = static_cast<u32>(layer->height);
+ info.visible = layer->visible != 0;
+
+ auto tileCount = static_cast<u32>(layer->data_count);
+ info.tiles.resize(tileCount);
+ for (u32 i = 0; i < tileCount; ++i) {
+ info.tiles[i] = convertGid(layer->data[i], tilesets);
+ }
+
+ result.layers.push_back(std::move(info));
+ }
+ };
+
+ processLayer(processLayer, map->layers);
+}
+
+bool TiledMapLoader::finalize(u32 handle) {
+ auto it = maps_.find(handle);
+ if (it == maps_.end() || it->second.finalized) {
+ return false;
+ }
+
+ auto& pending = it->second;
+
+ for (const auto& ext : pending.external_tilesets) {
+ if (!ext.loaded) {
+ return false;
+ }
+ }
+
+ collectLayers(pending.raw_map, pending.result, pending.result.tilesets);
+
+ for (auto& ext : pending.external_tilesets) {
+ if (ext.loaded) {
+ cute_tiled_free_external_tileset(ext.loaded);
+ ext.loaded = nullptr;
+ }
+ }
+ cute_tiled_free_map(pending.raw_map);
+ pending.raw_map = nullptr;
+ pending.finalized = true;
+
+ return true;
+}
+
+void TiledMapLoader::freeMap(u32 handle) {
+ auto it = maps_.find(handle);
+ if (it == maps_.end()) {
+ return;
+ }
+
+ auto& pending = it->second;
+ if (!pending.finalized) {
+ for (auto& ext : pending.external_tilesets) {
+ if (ext.loaded) {
+ cute_tiled_free_external_tileset(ext.loaded);
+ }
+ }
+ if (pending.raw_map) {
+ cute_tiled_free_map(pending.raw_map);
+ }
+ }
+
+ maps_.erase(it);
+}
+
+const TiledMapData* TiledMapLoader::getMap(u32 handle) const {
+ auto it = maps_.find(handle);
+ if (it == maps_.end() || !it->second.finalized) {
+ return nullptr;
+ }
+ return &it->second.result;
+}
+
+} // namespace tilemap
+} // namespace esengine
diff --git a/src/esengine/tilemap/TiledMapLoader.hpp b/src/esengine/tilemap/TiledMapLoader.hpp
new file mode 100644
index 000000000..6bf632623
--- /dev/null
+++ b/src/esengine/tilemap/TiledMapLoader.hpp
@@ -0,0 +1,80 @@
+#pragma once
+
+#include "../core/Types.hpp"
+
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+struct cute_tiled_map_t;
+struct cute_tiled_tileset_t;
+
+namespace esengine {
+namespace tilemap {
+
+struct TiledLayerInfo {
+ std::string name;
+ u32 width;
+ u32 height;
+ bool visible;
+ std::vector<u16> tiles;
+};
+
+struct TiledTilesetInfo {
+ std::string name;
+ std::string image;
+ u32 first_gid;
+ u32 tile_width;
+ u32 tile_height;
+ u32 columns;
+ u32 tile_count;
+};
+
+struct TiledMapData {
+ u32 width;
+ u32 height;
+ u32 tile_width;
+ u32 tile_height;
+ std::vector<TiledLayerInfo> layers;
+ std::vector<TiledTilesetInfo> tilesets;
+};
+
+class TiledMapLoader {
+public:
+ u32 loadFromMemory(const char* data, u32 size);
+
+ u32 getExternalTilesetCount(u32 handle) const;
+ std::string getExternalTilesetSource(u32 handle, u32 index) const;
+
+ bool loadExternalTileset(u32 handle, u32 index,
+ const char* data, u32 size);
+
+ bool finalize(u32 handle);
+
+ void freeMap(u32 handle);
+ const TiledMapData* getMap(u32 handle) const;
+
+private:
+ struct ExternalTilesetEntry {
+ cute_tiled_tileset_t* map_tileset;
+ cute_tiled_tileset_t* loaded;
+ std::string source;
+ };
+
+ struct PendingMap {
+ cute_tiled_map_t* raw_map;
+ TiledMapData result;
+ bool finalized;
+ std::vector<ExternalTilesetEntry> external_tilesets;
+ };
+
+ std::unordered_map<u32, PendingMap> maps_;
+ u32 next_handle_ = 1;
+
+ static u16 convertGid(int gid, const std::vector<TiledTilesetInfo>& tilesets);
+ static void collectLayers(cute_tiled_map_t* map, TiledMapData& result,
+ const std::vector<TiledTilesetInfo>& tilesets);
+};
+
+} // namespace tilemap
+} // namespace esengine
diff --git a/src/esengine/tilemap/TilemapSystem.cpp b/src/esengine/tilemap/TilemapSystem.cpp
new file mode 100644
index 000000000..585aae8a9
--- /dev/null
+++ b/src/esengine/tilemap/TilemapSystem.cpp
@@ -0,0 +1,112 @@
+#include "TilemapSystem.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+
+namespace esengine::tilemap {
+
+TileRange computeVisibleRange(f32 camLeft, f32 camBottom, f32 camRight, f32 camTop,
+ f32 originX, f32 originY,
+ f32 tileWidth, f32 tileHeight,
+ u32 mapWidth, u32 mapHeight) {
+ f32 localLeft = camLeft - originX;
+ f32 localBottom = camBottom - originY;
+ f32 localRight = camRight - originX;
+ f32 localTop = camTop - originY;
+
+ i32 minX = static_cast<i32>(std::floor(localLeft / tileWidth));
+ i32 minY = static_cast<i32>(std::floor(localBottom / tileHeight));
+ i32 maxX = static_cast<i32>(std::ceil(localRight / tileWidth));
+ i32 maxY = static_cast<i32>(std::ceil(localTop / tileHeight));
+
+ minX = std::max(minX, 0);
+ minY = std::max(minY, 0);
+ maxX = std::min(maxX, static_cast<i32>(mapWidth));
+ maxY = std::min(maxY, static_cast<i32>(mapHeight));
+
+ return {minX, minY, maxX, maxY};
+}
+
+void TilemapSystem::initLayer(Entity entity, u32 width, u32 height,
+ f32 tileWidth, f32 tileHeight) {
+ LayerData layer;
+ layer.width = width;
+ layer.height = height;
+ layer.tile_width = tileWidth;
+ layer.tile_height = tileHeight;
+ layer.tiles.resize(static_cast<usize>(width) * height, EMPTY_TILE);
+ layers_[entity] = std::move(layer);
+}
+
+void TilemapSystem::destroyLayer(Entity entity) {
+ layers_.erase(entity);
+}
+
+bool TilemapSystem::hasLayer(Entity entity) const {
+ return layers_.count(entity) > 0;
+}
+
+const TilemapSystem::LayerData* TilemapSystem::getLayerData(Entity entity) const {
+ auto it = layers_.find(entity);
+ if (it == layers_.end()) return nullptr;
+ return &it->second;
+}
+
+void TilemapSystem::setTile(Entity entity, i32 x, i32 y, u16 tileId) {
+ auto it = layers_.find(entity);
+ if (it == layers_.end()) return;
+
+ auto& layer = it->second;
+ if (x < 0 || y < 0 ||
+ static_cast<u32>(x) >= layer.width ||
+ static_cast<u32>(y) >= layer.height) {
+ return;
+ }
+
+ layer.tiles[static_cast<usize>(y) * layer.width + static_cast<usize>(x)] = tileId;
+}
+
+u16 TilemapSystem::getTile(Entity entity, i32 x, i32 y) const {
+ auto it = layers_.find(entity);
+ if (it == layers_.end()) return EMPTY_TILE;
+
+ const auto& layer = it->second;
+ if (x < 0 || y < 0 ||
+ static_cast<u32>(x) >= layer.width ||
+ static_cast<u32>(y) >= layer.height) {
+ return EMPTY_TILE;
+ }
+
+ return layer.tiles[static_cast<usize>(y) * layer.width + static_cast<usize>(x)];
+}
+
+void TilemapSystem::fillRect(Entity entity, i32 x, i32 y,
+ u32 w, u32 h, u16 tileId) {
+ auto it = layers_.find(entity);
+ if (it == layers_.end()) return;
+
+ auto& layer = it->second;
+ i32 x0 = std::max(x, 0);
+ i32 y0 = std::max(y, 0);
+ i32 x1 = std::min(x + static_cast<i32>(w), static_cast<i32>(layer.width));
+ i32 y1 = std::min(y + static_cast<i32>(h), static_cast<i32>(layer.height));
+
+ for (i32 ty = y0; ty < y1; ++ty) {
+ for (i32 tx = x0; tx < x1; ++tx) {
+ layer.tiles[static_cast<usize>(ty) * layer.width + static_cast<usize>(tx)] = tileId;
+ }
+ }
+}
+
+void TilemapSystem::setTiles(Entity entity, const u16* tiles, u32 count) {
+ auto it = layers_.find(entity);
+ if (it == layers_.end()) return;
+
+ auto& layer = it->second;
+ u32 copyCount = std::min(count,
+ static_cast<u32>(layer.tiles.size()));
+ std::memcpy(layer.tiles.data(), tiles, copyCount * sizeof(u16));
+}
+
+} // namespace esengine::tilemap
diff --git a/src/esengine/tilemap/TilemapSystem.hpp b/src/esengine/tilemap/TilemapSystem.hpp
new file mode 100644
index 000000000..c75e6d749
--- /dev/null
+++ b/src/esengine/tilemap/TilemapSystem.hpp
@@ -0,0 +1,60 @@
+#pragma once
+
+#include "../core/Types.hpp"
+
+#include <glm/glm.hpp>
+#include <unordered_map>
+#include <vector>
+
+namespace esengine {
+namespace tilemap {
+
+static constexpr u16 EMPTY_TILE = 0;
+static constexpr u32 CHUNK_SIZE = 16;
+
+static constexpr u16 TILE_ID_MASK = 0x1FFF;
+static constexpr u16 TILE_FLIP_H = 0x2000;
+static constexpr u16 TILE_FLIP_V = 0x4000;
+static constexpr u16 TILE_FLIP_D = 0x8000;
+
+struct TileRange {
+ i32 min_x = 0;
+ i32 min_y = 0;
+ i32 max_x = 0;
+ i32 max_y = 0;
+ bool empty() const { return min_x >= max_x || min_y >= max_y; }
+};
+
+TileRange computeVisibleRange(f32 camLeft, f32 camBottom, f32 camRight, f32 camTop,
+ f32 originX, f32 originY,
+ f32 tileWidth, f32 tileHeight,
+ u32 mapWidth, u32 mapHeight);
+
+class TilemapSystem {
+public:
+ void initLayer(Entity entity, u32 width, u32 height,
+ f32 tileWidth, f32 tileHeight);
+ void destroyLayer(Entity entity);
+ bool hasLayer(Entity entity) const;
+
+ void setTile(Entity entity, i32 x, i32 y, u16 tileId);
+ u16 getTile(Entity entity, i32 x, i32 y) const;
+ void fillRect(Entity entity, i32 x, i32 y, u32 w, u32 h, u16 tileId);
+ void setTiles(Entity entity, const u16* tiles, u32 count);
+
+ struct LayerData {
+ u32 width = 0;
+ u32 height = 0;
+ f32 tile_width = 0;
+ f32 tile_height = 0;
+ std::vector<u16> tiles;
+ };
+
+ const LayerData* getLayerData(Entity entity) const;
+
+private:
+ std::unordered_map<Entity, LayerData> layers_;
+};
+
+} // namespace tilemap
+} // namespace esengine
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index a1f442fa6..9dd1969f5 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -23,3 +23,10 @@ add_executable(test_particle
)
target_link_libraries(test_particle PRIVATE esengine)
add_test(NAME test_particle COMMAND test_particle)
+
+# Tilemap system tests
+add_executable(test_tilemap
+ tilemap/test_tilemap.cpp
+)
+target_link_libraries(test_tilemap PRIVATE esengine)
+add_test(NAME test_tilemap COMMAND test_tilemap)
diff --git a/tests/tilemap/test_tilemap.cpp b/tests/tilemap/test_tilemap.cpp
new file mode 100644
index 000000000..b667ca4ce
--- /dev/null
+++ b/tests/tilemap/test_tilemap.cpp
@@ -0,0 +1,192 @@
+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
+#include <doctest.h>
+
+#include <esengine/tilemap/TilemapSystem.hpp>
+
+using namespace esengine;
+using namespace esengine::tilemap;
+
+TEST_CASE("tilemap_init_layer") {
+ TilemapSystem sys;
+
+ SUBCASE("layer does not exist before init") {
+ CHECK_FALSE(sys.hasLayer(0));
+ }
+
+ SUBCASE("layer exists after init") {
+ sys.initLayer(0, 10, 8, 32.0f, 32.0f);
+ CHECK(sys.hasLayer(0));
+ }
+
+ SUBCASE("layer destroyed after destroy") {
+ sys.initLayer(0, 10, 8, 32.0f, 32.0f);
+ sys.destroyLayer(0);
+ CHECK_FALSE(sys.hasLayer(0));
+ }
+
+ SUBCASE("multiple layers") {
+ sys.initLayer(1, 10, 10, 32.0f, 32.0f);
+ sys.initLayer(2, 20, 20, 16.0f, 16.0f);
+ CHECK(sys.hasLayer(1));
+ CHECK(sys.hasLayer(2));
+ sys.destroyLayer(1);
+ CHECK_FALSE(sys.hasLayer(1));
+ CHECK(sys.hasLayer(2));
+ }
+}
+
+TEST_CASE("tilemap_set_get_tile") {
+ TilemapSystem sys;
+ sys.initLayer(0, 10, 8, 32.0f, 32.0f);
+
+ SUBCASE("all tiles start empty") {
+ CHECK_EQ(sys.getTile(0, 0, 0), EMPTY_TILE);
+ CHECK_EQ(sys.getTile(0, 5, 3), EMPTY_TILE);
+ CHECK_EQ(sys.getTile(0, 9, 7), EMPTY_TILE);
+ }
+
+ SUBCASE("set and get single tile") {
+ sys.setTile(0, 3, 4, 42);
+ CHECK_EQ(sys.getTile(0, 3, 4), 42);
+ CHECK_EQ(sys.getTile(0, 3, 3), EMPTY_TILE);
+ }
+
+ SUBCASE("overwrite tile") {
+ sys.setTile(0, 0, 0, 10);
+ sys.setTile(0, 0, 0, 20);
+ CHECK_EQ(sys.getTile(0, 0, 0), 20);
+ }
+
+ SUBCASE("out of bounds returns EMPTY_TILE") {
+ CHECK_EQ(sys.getTile(0, -1, 0), EMPTY_TILE);
+ CHECK_EQ(sys.getTile(0, 10, 0), EMPTY_TILE);
+ CHECK_EQ(sys.getTile(0, 0, 8), EMPTY_TILE);
+ CHECK_EQ(sys.getTile(0, 0, -1), EMPTY_TILE);
+ }
+
+ SUBCASE("set out of bounds is no-op") {
+ sys.setTile(0, -1, 0, 99);
+ sys.setTile(0, 10, 0, 99);
+ CHECK_EQ(sys.getTile(0, 0, 0), EMPTY_TILE);
+ }
+
+ SUBCASE("non-existent layer returns EMPTY_TILE") {
+ CHECK_EQ(sys.getTile(999, 0, 0), EMPTY_TILE);
+ }
+}
+
+TEST_CASE("tilemap_fill_rect") {
+ TilemapSystem sys;
+ sys.initLayer(0, 10, 8, 32.0f, 32.0f);
+
+ SUBCASE("fill 3x2 region") {
+ sys.fillRect(0, 2, 1, 3, 2, 5);
+ CHECK_EQ(sys.getTile(0, 2, 1), 5);
+ CHECK_EQ(sys.getTile(0, 3, 1), 5);
+ CHECK_EQ(sys.getTile(0, 4, 1), 5);
+ CHECK_EQ(sys.getTile(0, 2, 2), 5);
+ CHECK_EQ(sys.getTile(0, 3, 2), 5);
+ CHECK_EQ(sys.getTile(0, 4, 2), 5);
+ CHECK_EQ(sys.getTile(0, 1, 1), EMPTY_TILE);
+ CHECK_EQ(sys.getTile(0, 5, 1), EMPTY_TILE);
+ CHECK_EQ(sys.getTile(0, 2, 0), EMPTY_TILE);
+ CHECK_EQ(sys.getTile(0, 2, 3), EMPTY_TILE);
+ }
+
+ SUBCASE("fill clamps to bounds") {
+ sys.fillRect(0, 8, 6, 5, 5, 7);
+ CHECK_EQ(sys.getTile(0, 8, 6), 7);
+ CHECK_EQ(sys.getTile(0, 9, 7), 7);
+ CHECK_EQ(sys.getTile(0, 9, 6), 7);
+ CHECK_EQ(sys.getTile(0, 8, 7), 7);
+ }
+}
+
+TEST_CASE("tilemap_set_tiles_bulk") {
+ TilemapSystem sys;
+ sys.initLayer(0, 4, 3, 32.0f, 32.0f);
+
+ std::vector<u16> tiles = {
+ 1, 2, 3, 4,
+ 5, 0, 0, 8,
+ 9, 10, 11, 12
+ };
+
+ sys.setTiles(0, tiles.data(), static_cast<u32>(tiles.size()));
+
+ CHECK_EQ(sys.getTile(0, 0, 0), 1);
+ CHECK_EQ(sys.getTile(0, 3, 0), 4);
+ CHECK_EQ(sys.getTile(0, 1, 1), EMPTY_TILE);
+ CHECK_EQ(sys.getTile(0, 3, 1), 8);
+ CHECK_EQ(sys.getTile(0, 0, 2), 9);
+ CHECK_EQ(sys.getTile(0, 3, 2), 12);
+}
+
+TEST_CASE("tilemap_set_tiles_partial") {
+ TilemapSystem sys;
+ sys.initLayer(0, 4, 3, 32.0f, 32.0f);
+
+ std::vector<u16> partial = {1, 2, 3};
+ sys.setTiles(0, partial.data(), static_cast<u32>(partial.size()));
+
+ CHECK_EQ(sys.getTile(0, 0, 0), 1);
+ CHECK_EQ(sys.getTile(0, 1, 0), 2);
+ CHECK_EQ(sys.getTile(0, 2, 0), 3);
+ CHECK_EQ(sys.getTile(0, 3, 0), EMPTY_TILE);
+}
+
+TEST_CASE("tilemap_compute_visible_range") {
+ // Map: 20x15 tiles, 32x32 px each, origin at (0,0)
+ // Map covers world (0,0) to (640,480)
+ constexpr f32 TW = 32.0f;
+ constexpr f32 TH = 32.0f;
+ constexpr u32 MW = 20;
+ constexpr u32 MH = 15;
+
+ SUBCASE("camera covers full map") {
+ auto r = computeVisibleRange(-100, -100, 800, 600,
+ 0, 0, TW, TH, MW, MH);
+ CHECK_EQ(r.min_x, 0);
+ CHECK_EQ(r.min_y, 0);
+ CHECK_EQ(r.max_x, 20);
+ CHECK_EQ(r.max_y, 15);
+ CHECK_FALSE(r.empty());
+ }
+
+ SUBCASE("camera partially overlaps") {
+ // Camera from (64,96) to (256,288) -> tiles (2,3) to (8,9)
+ auto r = computeVisibleRange(64, 96, 256, 288,
+ 0, 0, TW, TH, MW, MH);
+ CHECK_EQ(r.min_x, 2);
+ CHECK_EQ(r.min_y, 3);
+ CHECK_EQ(r.max_x, 8);
+ CHECK_EQ(r.max_y, 9);
+ }
+
+ SUBCASE("camera fully outside map returns empty") {
+ auto r = computeVisibleRange(700, 500, 900, 700,
+ 0, 0, TW, TH, MW, MH);
+ CHECK(r.empty());
+ }
+
+ SUBCASE("camera with origin offset") {
+ // Origin at (100, 200), camera at (100,200)-(228,328)
+ // World (100,200) = tile (0,0), world (228,328) = tile (4,4)
+ auto r = computeVisibleRange(100, 200, 228, 328,
+ 100, 200, TW, TH, MW, MH);
+ CHECK_EQ(r.min_x, 0);
+ CHECK_EQ(r.min_y, 0);
+ CHECK_EQ(r.max_x, 4);
+ CHECK_EQ(r.max_y, 4);
+ }
+
+ SUBCASE("fractional tile alignment") {
+ // Camera from (16,16) to (80,80) -> covers tiles 0..2 in both axes
+ auto r = computeVisibleRange(16, 16, 80, 80,
+ 0, 0, TW, TH, MW, MH);
+ CHECK_EQ(r.min_x, 0);
+ CHECK_EQ(r.min_y, 0);
+ CHECK_EQ(r.max_x, 3);
+ CHECK_EQ(r.max_y, 3);
+ }
+}
diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt
index 319681af0..5206230e7 100644
--- a/third_party/CMakeLists.txt
+++ b/third_party/CMakeLists.txt
@@ -47,6 +47,13 @@ target_compile_definitions(glm INTERFACE
GLM_ENABLE_EXPERIMENTAL
)
+# =============================================================================
+# cute_tiled - Tiled JSON map parser
+# =============================================================================
+
+add_library(cute_tiled INTERFACE)
+target_include_directories(cute_tiled INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/cute_tiled)
+
# =============================================================================
# Native Platform Dependencies
# =============================================================================
diff --git a/third_party/cute_tiled/cute_tiled.h b/third_party/cute_tiled/cute_tiled.h
new file mode 100644
index 000000000..eaa6d7d33
--- /dev/null
+++ b/third_party/cute_tiled/cute_tiled.h
@@ -0,0 +1,3218 @@
+/*
+ ------------------------------------------------------------------------------
+ Licensing information can be found at the end of the file.
+ ------------------------------------------------------------------------------
+
+ cute_tiled.h - v1.06
+
+ To create implementation (the function definitions)
+ #define CUTE_TILED_IMPLEMENTATION
+ in *one* C/CPP file (translation unit) that includes this file
+
+ SUMMARY
+
+ Parses Tiled (http://www.mapeditor.org/) files saved as the JSON file
+ format. See http://doc.mapeditor.org/en/latest/reference/json-map-format/
+ for a complete description of the JSON Tiled format. An entire map file
+ is loaded up in entirety and used to fill in a set of structs. The entire
+ struct collection is then handed to the user.
+
+ This header is up to date with Tiled's documentation Revision 40049fd5 and
+ verified to work with Tiled stable version 1.4.1.
+ http://doc.mapeditor.org/en/latest/reference/json-map-format/
+
+ Here is a past discussion thread on this header:
+ https://www.reddit.com/r/gamedev/comments/87680n/cute_tiled_tiled_json_map_parserloader_in_c/
+
+ Revision history:
+ 1.00 (03/24/2018) initial release
+ 1.01 (05/04/2018) tile descriptors in tilesets for collision geometry
+ 1.02 (05/07/2018) reverse lists for ease of use, incorporate fixes by ZenToad
+ 1.03 (01/11/2019) support for Tiled 1.2.1 with the help of dpeter99 and tanis2000
+ 1.04 (04/30/2020) support for Tiled 1.3.3 with the help of aganm
+ 1.05 (07/19/2020) support for Tiled 1.4.1 and tileset tile animations
+ 1.06 (04/05/2021) support for Tiled 1.5.0 parallax
+ 1.07 (03/01/2022) support for c89
+ 1.08 (25/01/2026) added chunks for infinite maps
+*/
+
+/*
+ Contributors:
+ ZenToad 1.02 - Bug reports and goto statement errors for g++
+ dpeter99 1.03 - Help with updating to Tiled 1.2.1 JSON format
+ tanis2000 1.03 - Help with updating to Tiled 1.2.1 JSON format
+ aganm 1.04 - Help with updating to Tiled 1.3.3 JSON format
+ mupf 1.07 - Adding support for C89
+ Ghoose 1.08 - Adding infinite map support
+*/
+
+/*
+ DOCUMENTATION
+
+ Load up a Tiled json exported file, either from disk or memory, like so:
+
+ cute_tiled_map_t* map = cute_tiled_load_map_from_memory(memory, size, 0);
+
+ Then simply access the map's fields like so:
+
+ // get map width and height
+ int w = map->width;
+ int h = map->height;
+
+ // loop over the map's layers
+ cute_tiled_layer_t* layer = map->layers;
+ while (layer)
+ {
+ int* data = layer->data;
+ int data_count = layer->data_count;
+
+ // do something with the tile data
+ UserFunction_HandleTiles(data, data_count);
+
+ layer = layer->next;
+ }
+
+ Finally, free it like so:
+
+ cute_tiled_free_map(map);
+
+ To access fields in infinite maps you will need to loop through the chunks in each layer, e.g.:
+
+ // get map width and height
+ int w = map->width;
+ int h = map->height;
+
+ // loop over the map's layers
+ cute_tiled_layer_t* layer = map->layers;
+ while (layer)
+ {
+ cute_tiled_chunk_t* chunk = layer->chunks;
+ while (chunk)
+ {
+ int* data = chunk->data;
+ int data_count = chunk->data_count;
+
+ // do something with the tile data
+ UserFunction_HandleTiles(data, data_count);
+
+ chunk = chunk->next;
+ }
+
+ layer = layer->next;
+ }
+
+
+ LIMITATIONS
+
+ More uncommon fields are not supported, and are annotated in this header.
+ Search for "Not currently supported." without quotes to find them. cute_tiled
+ logs a warning whenever a known unsupported field is encountered, and will
+ attempt to gracefully skip the field. If a field with completely unknown
+ syntax is encountered (which can happen if cute_tiled is used on a newer
+ and unsupported version of Tiled), undefined behavior may occur (crashes).
+
+ If you would like a certain feature to be supported simply open an issue on
+ GitHub and provide a JSON exported map with the unsupported features. Changing
+ the parser to support new fields and objects is quite easy, as long as a map
+ file is provided for debugging and testing!
+
+ GitHub : https://github.com/RandyGaul/cute_headers/
+
+ Compression of the tile GIDs is *not* supported in this header. Exporting
+ a map from Tiled will create a JSON file. This JSON file itself can very
+ trivially be compressed in its entirety, thus making Tiled's internal
+ compression exporting not a useful feature for this header to support.
+ Simply wrap calls to `cute_tiled_load_map_from_file` in a decompression
+ routine. Here is an example (assuming `zlib_uncompress` is already imp-
+ lemented somewhere in the user's codebase):
+
+ int size;
+ void* uncompressed_data = zlib_uncompress(path_to_zipped_map_file, &size);
+ cute_tiled_map_t* map = cute_tiled_load_map_from_memory(uncompressed_data, size, 0);
+*/
+
+#if !defined(CUTE_TILED_H)
+
+#include <stdint.h> // uint32_t
+
+// Read this in the event of errors
+extern const char* cute_tiled_error_reason;
+extern int cute_tiled_error_line;
+
+
+typedef struct cute_tiled_map_t cute_tiled_map_t;
+typedef struct cute_tiled_tileset_t cute_tiled_tileset_t;
+
+/*!
+ * Load a map from disk, placed into heap allocated memory. \p mem_ctx can be
+ * NULL. It is used for custom allocations.
+ */
+cute_tiled_map_t* cute_tiled_load_map_from_file(const char* path, void* mem_ctx);
+
+/*!
+ * Load a map from memory. \p mem_ctx can be NULL. It is used for custom allocations.
+ */
+cute_tiled_map_t* cute_tiled_load_map_from_memory(const void* memory, int size_in_bytes, void* mem_ctx);
+
+/*!
+ * Reverses the layers order, so they appear in reverse-order from what is shown in the Tiled editor.
+ */
+void cute_tiled_reverse_layers(cute_tiled_map_t* map);
+
+/*!
+ * Free all dynamic memory associated with this map.
+ */
+void cute_tiled_free_map(cute_tiled_map_t* map);
+
+/*!
+ * Load an external tileset from disk, placed into heap allocated memory. \p mem_ctx can be
+ * NULL. It is used for custom allocations.
+ *
+ * Please note this function is *entirely optional*, and only useful if you want to intentionally
+ * load tilesets externally from your map. If so, please also consider defining
+ * `CUTE_TILED_NO_EXTERNAL_TILESET_WARNING` to disable warnings about missing embedded tilesets.
+ */
+cute_tiled_tileset_t* cute_tiled_load_external_tileset(const char* path, void* mem_ctx);
+
+/*!
+ * Load an external tileset from memory. \p mem_ctx can be NULL. It is used for custom allocations.
+ *
+ * Please note this function is *entirely optional*, and only useful if you want to intentionally
+ * load tilesets externally from your map. If so, please also consider defining
+ * `CUTE_TILED_NO_EXTERNAL_TILESET_WARNING` to disable warnings about missing embedded tilesets.
+ */
+cute_tiled_tileset_t* cute_tiled_load_external_tileset_from_memory(const void* memory, int size_in_bytes, void* mem_ctx);
+
+/*!
+ * Free all dynamic memory associated with this external tileset.
+ */
+void cute_tiled_free_external_tileset(cute_tiled_tileset_t* tileset);
+
+#if !defined(CUTE_TILED_U64)
+ #define CUTE_TILED_U64 unsigned long long
+#endif
+
+#if !defined(CUTE_TILED_INLINE)
+ #if defined(_MSC_VER)
+ #define CUTE_TILED_INLINE __inline
+ #else
+ #define CUTE_TILED_INLINE __inline__
+ #endif
+#endif
+
+typedef struct cute_tiled_layer_t cute_tiled_layer_t;
+typedef struct cute_tiled_object_t cute_tiled_object_t;
+typedef struct cute_tiled_frame_t cute_tiled_frame_t;
+typedef struct cute_tiled_tile_descriptor_t cute_tiled_tile_descriptor_t;
+typedef struct cute_tiled_property_t cute_tiled_property_t;
+typedef union cute_tiled_string_t cute_tiled_string_t;
+
+/*!
+ * To access a string, simply do: object->name.ptr; this union is needed
+ * as a workaround for 32-bit builds where the size of a pointer is only
+ * 32 bits.
+ *
+ * More info:
+ * This unions is needed to support a single-pass parser, with string
+ * interning, where the parser copies value directly into the user-facing
+ * structures. As opposed to the parser copying values into an intermediate
+ * structure, and finally copying the intermediate values into the
+ * user-facing struct at the end. The latter option requires more code!
+ */
+union cute_tiled_string_t
+{
+ const char* ptr;
+ CUTE_TILED_U64 hash_id;
+};
+
+typedef enum CUTE_TILED_PROPERTY_TYPE
+{
+ CUTE_TILED_PROPERTY_NONE,
+ CUTE_TILED_PROPERTY_INT,
+ CUTE_TILED_PROPERTY_BOOL,
+ CUTE_TILED_PROPERTY_FLOAT,
+ CUTE_TILED_PROPERTY_STRING,
+
+ // Note: currently unused! File properties are reported as strings in
+ // this header, and it is up to users to know a-priori which strings
+ // contain file paths.
+ CUTE_TILED_PROPERTY_FILE,
+
+ CUTE_TILED_PROPERTY_COLOR,
+} CUTE_TILED_PROPERTY_TYPE;
+
+struct cute_tiled_property_t
+{
+ union
+ {
+ int integer;
+ int boolean;
+ float floating;
+ cute_tiled_string_t string;
+ cute_tiled_string_t file;
+ uint32_t color;
+ } data;
+ CUTE_TILED_PROPERTY_TYPE type;
+ cute_tiled_string_t name;
+};
+
+struct cute_tiled_object_t
+{
+ int ellipse; // 0 or 1. Used to mark an object as an ellipse.
+ int gid; // GID, only if object comes from a Tilemap.
+ float height; // Height in pixels. Ignored if using a gid.
+ int id; // Incremental id - unique across all objects.
+ cute_tiled_string_t name; // String assigned to name field in editor.
+ int point; // 0 or 1. Used to mark an object as a point.
+
+ // Example to index each vert of a polygon/polyline:
+ /*
+ float x, y;
+ for(int i = 0; i < vert_count * 2; i += 2)
+ {
+ x = vertices[i];
+ y = vertices[i + 1];
+ }
+ */
+ int vert_count;
+ float* vertices; // Represents both type `polyline` and `polygon`.
+ int vert_type; // 1 for `polygon` and 0 for `polyline`.
+
+ int property_count; // Number of elements in the `properties` array.
+ cute_tiled_property_t* properties; // Array of properties.
+ float rotation; // Angle in degrees clockwise.
+ /* template */ // Not currently supported.
+ /* text */ // Not currently supported.
+ cute_tiled_string_t type; // String assigned to type field in editor.
+ /* class */ // Not currently supported.
+ int visible; // 0 or 1. Whether object is shown in editor.
+ float width; // Width in pixels. Ignored if using a gid.
+ float x; // x coordinate in pixels.
+ float y; // y coordinate in pixels.
+ cute_tiled_object_t* next; // Pointer to next object. NULL if final object.
+};
+
+/*!
+ * Example of using both helper functions below to process the `data` pointer of a layer,
+ * containing an array of `GID`s.
+ *
+ * for (int i = 0; i < layer->data_count; i++)
+ * {
+ * int hflip, vflip, dflip;
+ * int tile_id = layer->data[i];
+ * cute_tiled_get_flags(tile_id, &hflip, &vflip, &dflip);
+ * tile_id = cute_tiled_unset_flags(tile_id);
+ * DoSomethingWithFlags(tile_id, flip, vflip, dlfip);
+ * DoSomethingWithTileID(tile_id);
+ * }
+ */
+
+#define CUTE_TILED_FLIPPED_HORIZONTALLY_FLAG 0x80000000
+#define CUTE_TILED_FLIPPED_VERTICALLY_FLAG 0x40000000
+#define CUTE_TILED_FLIPPED_DIAGONALLY_FLAG 0x20000000
+
+/*!
+ * Helper for processing tile data in /ref `cute_tiled_layer_t` `data`. Unsets all of
+ * the image flipping flags in the higher bit of /p `tile_data_gid`.
+ */
+static CUTE_TILED_INLINE int cute_tiled_unset_flags(int tile_data_gid)
+{
+ const int flags = ~(CUTE_TILED_FLIPPED_HORIZONTALLY_FLAG | CUTE_TILED_FLIPPED_VERTICALLY_FLAG | CUTE_TILED_FLIPPED_DIAGONALLY_FLAG);
+ return tile_data_gid & flags;
+}
+
+/*!
+ * Helper for processing tile data in /ref `cute_tiled_layer_t` `data`. Flags are
+ * stored in the GID array `data` for flipping the image. Retrieves all three flag types.
+ */
+static CUTE_TILED_INLINE void cute_tiled_get_flags(int tile_data_gid, int* flip_horizontal, int* flip_vertical, int* flip_diagonal)
+{
+ *flip_horizontal = !!(tile_data_gid & CUTE_TILED_FLIPPED_HORIZONTALLY_FLAG);
+ *flip_vertical = !!(tile_data_gid & CUTE_TILED_FLIPPED_VERTICALLY_FLAG);
+ *flip_diagonal = !!(tile_data_gid & CUTE_TILED_FLIPPED_DIAGONALLY_FLAG);
+}
+
+struct cute_tiled_chunk_t
+{
+ int data_count; // number of integers in `data`
+ int* data; // Array of GIDs. `tilelayer` only. Only support CSV style exports.
+ int width; // Column count
+ int height; // Row count
+ int x; // Horizontal offset in tiles, aka the chunk's horizontal position
+ int y; // Vertical offset in tiles, aka the chunk's vertical position
+
+ cute_tiled_chunk_t* next; // Pointer to the next chunk, NULL if final chunk
+};
+
+struct cute_tiled_layer_t
+{
+ cute_tiled_chunk_t* chunks; // Linked list of chunks. NULL if map is not infinite
+ cute_tiled_string_t class_; // The class of the layer (since 1.9, optional).
+ /* compression; */ // Not currently supported.
+ int data_count; // Number of integers in `data`.
+ int* data; // Array of GIDs. `tilelayer` only. Only support CSV style exports.
+ cute_tiled_string_t draworder; // `topdown` (default) or `index`. `objectgroup` only.
+ /* encoding; */ // Not currently supported.
+ int height; // Row count. Same as map height for fixed-size maps.
+ cute_tiled_layer_t* layers; // Linked list of layers. Only appears if `type` is `group`.
+ cute_tiled_string_t name; // Name assigned to this layer.
+ cute_tiled_object_t* objects; // Linked list of objects. `objectgroup` only.
+ float offsetx; // Horizontal layer offset.
+ float offsety; // Vertical layer offset.
+ float opacity; // Value between 0 and 1.
+ int startx; // X coordinate where layer content starts (for infinite maps)
+ int starty; // Y coordinate where layer content starts (for infinite maps)
+ int property_count; // Number of elements in the `properties` array.
+ cute_tiled_property_t* properties; // Array of properties.
+ uint32_t transparentcolor; // Hex-formatted color (#AARRGGBB) (optional).
+ uint32_t tintcolor; // Hex-formatted color (#AARRGGBB) (optional).
+ cute_tiled_string_t type; // `tilelayer`, `objectgroup`, `imagelayer` or `group`.
+ cute_tiled_string_t image; // An image filepath. Used if layer is type `imagelayer`.
+ int visible; // 0 or 1. Whether layer is shown or hidden in editor.
+ int width; // Column count. Same as map width for fixed-size maps.
+ int x; // Horizontal layer offset in tiles. Always 0.
+ int y; // Vertical layer offset in tiles. Always 0.
+ float parallaxx; // X axis parallax factor.
+ float parallaxy; // Y axis parallax factor.
+ int repeatx; // Repeat image in the X direction
+ int repeaty; // Repeat image in the Y direction
+ int id; // ID of the layer.
+
+ // used for image-layer
+ int imagewidth;
+ int imageheight;
+
+ cute_tiled_layer_t* next; // Pointer to the next layer. NULL if final layer.
+};
+
+struct cute_tiled_frame_t
+{
+ int duration; // Frame duration in milliseconds.
+ int tileid; // Local tile ID representing this frame.
+};
+
+struct cute_tiled_tile_descriptor_t
+{
+ int tile_index; // ID of the tile local to the associated tileset.
+ cute_tiled_string_t type; // String assigned to type field in editor.
+ int frame_count; // The number of animation frames in the `animation` array.
+ cute_tiled_frame_t* animation; // An array of `cute_tiled_frame_t`'s. Can be NULL.
+ cute_tiled_string_t image; // Image used for a tile in a tileset of type collection of images (relative path from map file to source image).
+ // Tileset is a collection of images if image.ptr isn't NULL.
+ int imageheight; // Image height of a tile in a tileset of type collection of images.
+ int imagewidth; // Image width of a tile in a tileset of type collection of images.
+ cute_tiled_layer_t* objectgroup; // Linked list of layers of type `objectgroup` only. Useful for holding collision info.
+ int property_count; // Number of elements in the `properties` array.
+ cute_tiled_property_t* properties; // Array of properties.
+ /* terrain */ // Not currently supported.
+ float probability; // The probability used when painting with the terrain brush in `Random Mode`.
+ cute_tiled_tile_descriptor_t* next; // Pointer to the next tile descriptor. NULL if final tile descriptor.
+};
+
+// IMPORTANT NOTE
+// If your tileset is not embedded you will get a warning -- to disable this warning simply define
+// this macro CUTE_TILED_NO_EXTERNAL_TILESET_WARNING.
+//
+// Here is an example.
+//
+// #define CUTE_TILED_NO_EXTERNAL_TILESET_WARNING
+// #define CUTE_TILED_IMPLEMENTATION
+// #include <cute_tiled.h>
+struct cute_tiled_tileset_t
+{
+ uint32_t backgroundcolor; // Hex-formatted color (#RRGGBB or #AARRGGBB) (optional).
+ cute_tiled_string_t class_; // The class of the tileset (since 1.9, optional).
+ int columns; // The number of tile columns in the tileset.
+ int firstgid; // GID corresponding to the first tile in the set.
+ /* grid */ // Not currently supported.
+ cute_tiled_string_t image; // Image used for tiles in this set (relative path from map file to source image).
+ int imagewidth; // Width of source image in pixels.
+ int imageheight; // Height of source image in pixels.
+ int margin; // Buffer between image edge and first tile (pixels).
+ cute_tiled_string_t name; // Name given to this tileset.
+ cute_tiled_string_t objectalignment; // Alignment to use for tile objects (unspecified (default), topleft, top, topright, left, center, right, bottomleft, bottom or bottomright) (since 1.4).
+ int property_count; // Number of elements in the `properties` array.
+ cute_tiled_property_t* properties; // Array of properties.
+ int spacing; // Spacing between adjacent tiles in image (pixels).
+ /* terrains */ // Not currently supported.
+ int tilecount; // The number of tiles in this tileset.
+ cute_tiled_string_t tiledversion; // The Tiled version used to save the tileset.
+ int tileheight; // Maximum height of tiles in this set.
+ int tileoffset_x; // Pixel offset to align tiles to the grid.
+ int tileoffset_y; // Pixel offset to align tiles to the grid.
+ cute_tiled_tile_descriptor_t* tiles; // Linked list of tile descriptors. Can be NULL.
+ int tilewidth; // Maximum width of tiles in this set.
+ uint32_t transparentcolor; // Hex-formatted color (#AARRGGBB) (optional).
+ cute_tiled_string_t type; // `tileset` (for tileset files, since 1.0).
+ cute_tiled_string_t source; // Relative path to tileset, when saved externally from the map file.
+ cute_tiled_tileset_t* next; // Pointer to next tileset. NULL if final tileset.
+ float version; // The JSON format version (like 1.2).
+ void* _internal; // For internal use only. Don't touch.
+};
+
+struct cute_tiled_map_t
+{
+ uint32_t backgroundcolor; // Hex-formatted color (#RRGGBB or #AARRGGBB) (optional).
+ cute_tiled_string_t class_; // The class of the map (since 1.9, optional).
+ int height; // Number of tile rows.
+ /* hexsidelength */ // Not currently supported.
+ int infinite; // Whether the map has infinite dimensions.
+ cute_tiled_layer_t* layers; // Linked list of layers. Can be NULL.
+ int nextobjectid; // Auto-increments for each placed object.
+ cute_tiled_string_t orientation; // `orthogonal`, `isometric`, `staggered` or `hexagonal`.
+ int property_count; // Number of elements in the `properties` array.
+ cute_tiled_property_t* properties; // Array of properties.
+ cute_tiled_string_t renderorder; // Rendering direction (orthogonal maps only).
+ /* staggeraxis */ // Not currently supported.
+ /* staggerindex */ // Not currently supported.
+ cute_tiled_string_t tiledversion; // The Tiled version used to save the file.
+ int tileheight; // Map grid height.
+ cute_tiled_tileset_t* tilesets; // Linked list of tilesets.
+ int tilewidth; // Map grid width.
+ cute_tiled_string_t type; // `map` (since 1.0).
+ float version; // The JSON format version (like 1.2).
+ int width; // Number of tile columns.
+ int nextlayerid; // The ID of the following layer.
+};
+
+#define CUTE_TILED_H
+#endif
+
+#ifdef CUTE_TILED_IMPLEMENTATION
+#ifndef CUTE_TILED_IMPLEMENTATION_ONCE
+#define CUTE_TILED_IMPLEMENTATION_ONCE
+
+#ifndef _CRT_SECURE_NO_WARNINGS
+ #define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#ifndef _CRT_NONSTDC_NO_DEPRECATE
+ #define _CRT_NONSTDC_NO_DEPRECATE
+#endif
+
+#if !defined(CUTE_TILED_ALLOC)
+ #include <stdlib.h>
+ #define CUTE_TILED_ALLOC(size, ctx) malloc(size)
+ #define CUTE_TILED_FREE(mem, ctx) free(mem)
+#endif
+
+
+#ifndef STRPOOL_EMBEDDED_MALLOC
+ #define STRPOOL_EMBEDDED_MALLOC(ctx, size) CUTE_TILED_ALLOC(size, ctx)
+#endif
+
+#ifndef STRPOOL_EMBEDDED_FREE
+ #define STRPOOL_EMBEDDED_FREE(ctx, ptr) CUTE_TILED_FREE(ptr, ctx)
+#endif
+
+#define STRPOOL_EMBEDDED_IMPLEMENTATION
+
+/*
+ begin embedding modified strpool.h
+*/
+
+/*
+------------------------------------------------------------------------------
+ Licensing information can be found at the end of the file.
+------------------------------------------------------------------------------
+
+strpool.h - v1.4 - Highly efficient string pool for C/C++.
+
+Do this:
+ #define STRPOOL_EMBEDDED_IMPLEMENTATION
+before you include this file in *one* C/C++ file to create the implementation.
+*/
+
+#ifndef strpool_embedded_h
+#define strpool_embedded_h
+
+#ifndef STRPOOL_EMBEDDED_U32
+ #define STRPOOL_EMBEDDED_U32 unsigned int
+#endif
+#ifndef STRPOOL_EMBEDDED_U64
+ #define STRPOOL_EMBEDDED_U64 unsigned long long
+#endif
+
+typedef struct strpool_embedded_t strpool_embedded_t;
+
+typedef struct strpool_embedded_config_t
+ {
+ void* memctx;
+ int ignore_case;
+ int counter_bits;
+ int index_bits;
+ int entry_capacity;
+ int block_capacity;
+ int block_size;
+ int min_length;
+ } strpool_embedded_config_t;
+
+extern strpool_embedded_config_t const strpool_embedded_default_config;
+
+void strpool_embedded_init( strpool_embedded_t* pool, strpool_embedded_config_t const* config );
+void strpool_embedded_term( strpool_embedded_t* pool );
+
+STRPOOL_EMBEDDED_U64 strpool_embedded_inject( strpool_embedded_t* pool, char const* string, int length );
+char const* strpool_embedded_cstr( strpool_embedded_t const* pool, STRPOOL_EMBEDDED_U64 handle );
+
+#endif /* strpool_embedded_h */
+
+/*
+----------------------
+ IMPLEMENTATION
+----------------------
+*/
+
+#ifndef strpool_embedded_impl
+#define strpool_embedded_impl
+
+struct strpool_embedded_internal_hash_slot_t;
+struct strpool_embedded_internal_entry_t;
+struct strpool_embedded_internal_handle_t;
+struct strpool_embedded_internal_block_t;
+
+struct strpool_embedded_t
+ {
+ void* memctx;
+ int ignore_case;
+ int counter_shift;
+ STRPOOL_EMBEDDED_U64 counter_mask;
+ STRPOOL_EMBEDDED_U64 index_mask;
+
+ int initial_entry_capacity;
+ int initial_block_capacity;
+ int block_size;
+ int min_data_size;
+
+ struct strpool_embedded_internal_hash_slot_t* hash_table;
+ int hash_capacity;
+
+ struct strpool_embedded_internal_entry_t* entries;
+ int entry_capacity;
+ int entry_count;
+
+ struct strpool_embedded_internal_handle_t* handles;
+ int handle_capacity;
+ int handle_count;
+ int handle_freelist_head;
+ int handle_freelist_tail;
+
+ struct strpool_embedded_internal_block_t* blocks;
+ int block_capacity;
+ int block_count;
+ int current_block;
+ };
+
+
+#endif /* strpool_embedded_impl */
+
+
+#ifdef STRPOOL_EMBEDDED_IMPLEMENTATION
+#ifndef STRPOOL_EMBEDDED_IMPLEMENTATION_ONCE
+#define STRPOOL_EMBEDDED_IMPLEMENTATION_ONCE
+
+#include <stddef.h>
+
+#ifndef STRPOOL_EMBEDDED_ASSERT
+ #include <assert.h>
+ #define STRPOOL_EMBEDDED_ASSERT( x ) assert( x )
+#endif
+
+#ifndef STRPOOL_EMBEDDED_MEMSET
+ #include <string.h>
+ #define STRPOOL_EMBEDDED_MEMSET( ptr, val, cnt ) ( memset( ptr, val, cnt ) )
+#endif
+
+#ifndef STRPOOL_EMBEDDED_MEMCPY
+ #include <string.h>
+ #define STRPOOL_EMBEDDED_MEMCPY( dst, src, cnt ) ( memcpy( dst, src, cnt ) )
+#endif
+
+#ifndef STRPOOL_EMBEDDED_MEMCMP
+ #include <string.h>
+ #define STRPOOL_EMBEDDED_MEMCMP( pr1, pr2, cnt ) ( memcmp( pr1, pr2, cnt ) )
+#endif
+
+#ifndef STRPOOL_EMBEDDED_STRNICMP
+ #ifdef _WIN32
+ #include <string.h>
+ #define STRPOOL_EMBEDDED_STRNICMP( s1, s2, len ) ( _strnicmp( s1, s2, len ) )
+ #else
+ #include <string.h>
+ #include <strings.h>
+ #define STRPOOL_EMBEDDED_STRNICMP( s1, s2, len ) ( strncasecmp( s1, s2, len ) )
+ #endif
+#endif
+
+#ifndef STRPOOL_EMBEDDED_MALLOC
+ #include <stdlib.h>
+ #define STRPOOL_EMBEDDED_MALLOC( ctx, size ) ( malloc( size ) )
+ #define STRPOOL_EMBEDDED_FREE( ctx, ptr ) ( free( ptr ) )
+#endif
+
+
+typedef struct strpool_embedded_internal_hash_slot_t
+ {
+ STRPOOL_EMBEDDED_U32 hash_key;
+ int entry_index;
+ int base_count;
+ } strpool_embedded_internal_hash_slot_t;
+
+
+typedef struct strpool_embedded_internal_entry_t
+ {
+ int hash_slot;
+ int handle_index;
+ char* data;
+ int size;
+ int length;
+ int refcount;
+ } strpool_embedded_internal_entry_t;
+
+
+typedef struct strpool_embedded_internal_handle_t
+ {
+ int entry_index;
+ int counter;
+ } strpool_embedded_internal_handle_t;
+
+
+typedef struct strpool_embedded_internal_block_t
+ {
+ int capacity;
+ char* data;
+ char* tail;
+ int free_list;
+ } strpool_embedded_internal_block_t;
+
+
+typedef struct strpool_embedded_internal_free_block_t
+ {
+ int size;
+ int next;
+ } strpool_embedded_internal_free_block_t;
+
+
+strpool_embedded_config_t const strpool_embedded_default_config =
+ {
+ /* memctx = */ 0,
+ /* ignore_case = */ 0,
+ /* counter_bits = */ 32,
+ /* index_bits = */ 32,
+ /* entry_capacity = */ 4096,
+ /* block_capacity = */ 32,
+ /* block_size = */ 256 * 1024,
+ /* min_length = */ 23,
+ };
+
+
+
+static STRPOOL_EMBEDDED_U32 strpool_embedded_internal_pow2ceil( STRPOOL_EMBEDDED_U32 v )
+ {
+ --v;
+ v |= v >> 1;
+ v |= v >> 2;
+ v |= v >> 4;
+ v |= v >> 8;
+ v |= v >> 16;
+ ++v;
+ v += ( v == 0 );
+ return v;
+ }
+
+
+static int strpool_embedded_internal_add_block( strpool_embedded_t* pool, int size )
+ {
+ if( pool->block_count >= pool->block_capacity )
+ {
+ strpool_embedded_internal_block_t* new_blocks;
+ pool->block_capacity *= 2;
+ new_blocks = (strpool_embedded_internal_block_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
+ pool->block_capacity * sizeof( *pool->blocks ) );
+ STRPOOL_EMBEDDED_ASSERT( new_blocks );
+ STRPOOL_EMBEDDED_MEMCPY( new_blocks, pool->blocks, pool->block_count * sizeof( *pool->blocks ) );
+ STRPOOL_EMBEDDED_FREE( pool->memctx, pool->blocks );
+ pool->blocks = new_blocks;
+ }
+ pool->blocks[ pool->block_count ].capacity = size;
+ pool->blocks[ pool->block_count ].data = (char*) STRPOOL_EMBEDDED_MALLOC( pool->memctx, (size_t) size );
+ STRPOOL_EMBEDDED_ASSERT( pool->blocks[ pool->block_count ].data );
+ pool->blocks[ pool->block_count ].tail = pool->blocks[ pool->block_count ].data;
+ pool->blocks[ pool->block_count ].free_list = -1;
+ return pool->block_count++;
+ }
+
+
+void strpool_embedded_init( strpool_embedded_t* pool, strpool_embedded_config_t const* config )
+ {
+ if( !config ) config = &strpool_embedded_default_config;
+
+ pool->memctx = config->memctx;
+ pool->ignore_case = config->ignore_case;
+
+ STRPOOL_EMBEDDED_ASSERT( config->counter_bits + config->index_bits <= 64 );
+ pool->counter_shift = config->index_bits;
+ pool->counter_mask = ( 1ULL << (STRPOOL_EMBEDDED_U64) config->counter_bits ) - 1;
+ pool->index_mask = ( 1ULL << (STRPOOL_EMBEDDED_U64) config->index_bits ) - 1;
+
+ pool->initial_entry_capacity =
+ (int) strpool_embedded_internal_pow2ceil( config->entry_capacity > 1 ? (STRPOOL_EMBEDDED_U32)config->entry_capacity : 2U );
+ pool->initial_block_capacity =
+ (int) strpool_embedded_internal_pow2ceil( config->block_capacity > 1 ? (STRPOOL_EMBEDDED_U32)config->block_capacity : 2U );
+ pool->block_size =
+ (int) strpool_embedded_internal_pow2ceil( config->block_size > 256 ? (STRPOOL_EMBEDDED_U32)config->block_size : 256U );
+ pool->min_data_size =
+ (int) ( sizeof( int ) * 2 + 1 + ( config->min_length > 8 ? (STRPOOL_EMBEDDED_U32)config->min_length : 8U ) );
+
+ pool->hash_capacity = pool->initial_entry_capacity * 2;
+ pool->entry_capacity = pool->initial_entry_capacity;
+ pool->handle_capacity = pool->initial_entry_capacity;
+ pool->block_capacity = pool->initial_block_capacity;
+
+ pool->handle_freelist_head = -1;
+ pool->handle_freelist_tail = -1;
+ pool->block_count = 0;
+ pool->handle_count = 0;
+ pool->entry_count = 0;
+
+ pool->hash_table = (strpool_embedded_internal_hash_slot_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
+ pool->hash_capacity * sizeof( *pool->hash_table ) );
+ STRPOOL_EMBEDDED_ASSERT( pool->hash_table );
+ STRPOOL_EMBEDDED_MEMSET( pool->hash_table, 0, pool->hash_capacity * sizeof( *pool->hash_table ) );
+ pool->entries = (strpool_embedded_internal_entry_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
+ pool->entry_capacity * sizeof( *pool->entries ) );
+ STRPOOL_EMBEDDED_ASSERT( pool->entries );
+ pool->handles = (strpool_embedded_internal_handle_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
+ pool->handle_capacity * sizeof( *pool->handles ) );
+ STRPOOL_EMBEDDED_ASSERT( pool->handles );
+ pool->blocks = (strpool_embedded_internal_block_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
+ pool->block_capacity * sizeof( *pool->blocks ) );
+ STRPOOL_EMBEDDED_ASSERT( pool->blocks );
+
+ pool->current_block = strpool_embedded_internal_add_block( pool, pool->block_size );
+ }
+
+
+void strpool_embedded_term( strpool_embedded_t* pool )
+ {
+ int i;
+#if 0
+ // Debug statistics
+ printf( "\n\n" );
+ printf( "Handles: %d/%d\n", pool->handle_count, pool->handle_capacity );
+ printf( "Entries: %d/%d\n", pool->entry_count, pool->entry_capacity );
+ printf( "Hashtable: %d/%d\n", pool->entry_count, pool->hash_capacity );
+ printf( "Blocks: %d/%d\n", pool->block_count, pool->block_capacity );
+ for( int i = 0; i < pool->block_count; ++i )
+ {
+ printf( "\n" );
+ printf( "BLOCK: %d\n", i );
+ printf( "Capacity: %d\n", pool->blocks[ i ].capacity );
+ printf( "Free: [ %d ]", pool->blocks[ i ].capacity - ( pool->blocks[ i ].tail - pool->blocks[ i ].data ) );
+ int fl = pool->blocks[ i ].free_list;
+ int count = 0;
+ int size = 0;
+ int total = 0;
+ while( fl >= 0 )
+ {
+ strpool_embedded_free_block_t* free_entry = (strpool_embedded_free_block_t*) ( pool->blocks[ i ].data + fl );
+ total += free_entry->size;
+ if( size == 0 ) { size = free_entry->size; }
+ if( size != free_entry->size )
+ {
+ printf( ", %dx%d", count, size );
+ count = 1;
+ size = free_entry->size;
+ }
+ else
+ {
+ ++count;
+ }
+ fl = free_entry->next;
+ }
+ if( size != 0 ) printf( ", %dx%d", count, size );
+ printf( ", { %d }\n", total );
+ }
+ printf( "\n\n" );
+#endif
+
+ for( i = 0; i < pool->block_count; ++i ) STRPOOL_EMBEDDED_FREE( pool->memctx, pool->blocks[ i ].data );
+ STRPOOL_EMBEDDED_FREE( pool->memctx, pool->blocks );
+ STRPOOL_EMBEDDED_FREE( pool->memctx, pool->handles );
+ STRPOOL_EMBEDDED_FREE( pool->memctx, pool->entries );
+ STRPOOL_EMBEDDED_FREE( pool->memctx, pool->hash_table );
+ }
+
+
+static STRPOOL_EMBEDDED_U64 strpool_embedded_internal_make_handle( int index, int counter, STRPOOL_EMBEDDED_U64 index_mask, int counter_shift,
+ STRPOOL_EMBEDDED_U64 counter_mask )
+ {
+ STRPOOL_EMBEDDED_U64 i = (STRPOOL_EMBEDDED_U64) ( index + 1 );
+ STRPOOL_EMBEDDED_U64 c = (STRPOOL_EMBEDDED_U64) counter;
+ return ( ( c & counter_mask ) << counter_shift ) | ( i & index_mask );
+ }
+
+
+static int strpool_embedded_internal_counter_from_handle( STRPOOL_EMBEDDED_U64 handle, int counter_shift, STRPOOL_EMBEDDED_U64 counter_mask )
+ {
+ return (int) ( ( handle >> counter_shift ) & counter_mask ) ;
+ }
+
+
+static int strpool_embedded_internal_index_from_handle( STRPOOL_EMBEDDED_U64 handle, STRPOOL_EMBEDDED_U64 index_mask )
+ {
+ return ( (int) ( handle & index_mask ) ) - 1;
+ }
+
+
+static strpool_embedded_internal_entry_t* strpool_embedded_internal_get_entry( strpool_embedded_t const* pool, STRPOOL_EMBEDDED_U64 handle )
+ {
+ int index = strpool_embedded_internal_index_from_handle( handle, pool->index_mask );
+ int counter = strpool_embedded_internal_counter_from_handle( handle, pool->counter_shift, pool->counter_mask );
+
+ if( index >= 0 && index < pool->handle_count &&
+ counter == (int) ( pool->handles[ index ].counter & pool->counter_mask ) )
+ return &pool->entries[ pool->handles[ index ].entry_index ];
+
+ return 0;
+ }
+
+
+static STRPOOL_EMBEDDED_U32 strpool_embedded_internal_find_in_blocks( strpool_embedded_t const* pool, char const* string, int length )
+ {
+ int i;
+ for( i = 0; i < pool->block_count; ++i )
+ {
+ strpool_embedded_internal_block_t* block = &pool->blocks[ i ];
+ // Check if string comes from pool
+ if( string >= block->data + 2 * sizeof( STRPOOL_EMBEDDED_U32 ) && string < block->data + block->capacity )
+ {
+ STRPOOL_EMBEDDED_U32* ptr = (STRPOOL_EMBEDDED_U32*) string;
+ int stored_length = (int)( *( ptr - 1 ) ); // Length is stored immediately before string
+ STRPOOL_EMBEDDED_U32 hash;
+ if( stored_length != length || string[ length ] != '\0' ) return 0; // Invalid string
+ hash = *( ptr - 2 ); // Hash is stored before the length field
+ return hash;
+ }
+ }
+
+ return 0;
+ }
+
+
+static STRPOOL_EMBEDDED_U32 strpool_embedded_internal_calculate_hash( char const* string, int length, int ignore_case )
+ {
+ STRPOOL_EMBEDDED_U32 hash = 5381U;
+ int i;
+
+ if( ignore_case)
+ {
+ for( i = 0; i < length; ++i )
+ {
+ char c = string[ i ];
+ c = ( c <= 'z' && c >= 'a' ) ? c - ( 'a' - 'A' ) : c;
+ hash = ( ( hash << 5U ) + hash) ^ c;
+ }
+ }
+ else
+ {
+ for( i = 0; i < length; ++i )
+ {
+ char c = string[ i ];
+ hash = ( ( hash << 5U ) + hash) ^ c;
+ }
+ }
+
+ hash = ( hash == 0 ) ? 1 : hash; // We can't allow 0-value hash keys, but dupes are ok
+ return hash;
+ }
+
+
+static void strpool_embedded_internal_expand_hash_table( strpool_embedded_t* pool )
+ {
+ int old_capacity = pool->hash_capacity;
+ strpool_embedded_internal_hash_slot_t* old_table = pool->hash_table;
+ int i;
+
+ pool->hash_capacity *= 2;
+
+ pool->hash_table = (strpool_embedded_internal_hash_slot_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
+ pool->hash_capacity * sizeof( *pool->hash_table ) );
+ STRPOOL_EMBEDDED_ASSERT( pool->hash_table );
+ STRPOOL_EMBEDDED_MEMSET( pool->hash_table, 0, pool->hash_capacity * sizeof( *pool->hash_table ) );
+
+ for( i = 0; i < old_capacity; ++i )
+ {
+ STRPOOL_EMBEDDED_U32 hash_key = old_table[ i ].hash_key;
+ if( hash_key )
+ {
+ int base_slot = (int)( hash_key & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
+ int slot = base_slot;
+ while( pool->hash_table[ slot ].hash_key )
+ slot = ( slot + 1 ) & ( pool->hash_capacity - 1 );
+ STRPOOL_EMBEDDED_ASSERT( hash_key );
+ pool->hash_table[ slot ].hash_key = hash_key;
+ pool->hash_table[ slot ].entry_index = old_table[ i ].entry_index;
+ pool->entries[ pool->hash_table[ slot ].entry_index ].hash_slot = slot;
+ ++pool->hash_table[ base_slot ].base_count;
+ }
+ }
+
+ STRPOOL_EMBEDDED_FREE( pool->memctx, old_table );
+ }
+
+
+static void strpool_embedded_internal_expand_entries( strpool_embedded_t* pool )
+ {
+ strpool_embedded_internal_entry_t* new_entries;
+ pool->entry_capacity *= 2;
+ new_entries = (strpool_embedded_internal_entry_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
+ pool->entry_capacity * sizeof( *pool->entries ) );
+ STRPOOL_EMBEDDED_ASSERT( new_entries );
+ STRPOOL_EMBEDDED_MEMCPY( new_entries, pool->entries, pool->entry_count * sizeof( *pool->entries ) );
+ STRPOOL_EMBEDDED_FREE( pool->memctx, pool->entries );
+ pool->entries = new_entries;
+ }
+
+
+static void strpool_embedded_internal_expand_handles( strpool_embedded_t* pool )
+ {
+ strpool_embedded_internal_handle_t* new_handles;
+ pool->handle_capacity *= 2;
+ new_handles = (strpool_embedded_internal_handle_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
+ pool->handle_capacity * sizeof( *pool->handles ) );
+ STRPOOL_EMBEDDED_ASSERT( new_handles );
+ STRPOOL_EMBEDDED_MEMCPY( new_handles, pool->handles, pool->handle_count * sizeof( *pool->handles ) );
+ STRPOOL_EMBEDDED_FREE( pool->memctx, pool->handles );
+ pool->handles = new_handles;
+ }
+
+
+static char* strpool_embedded_internal_get_data_storage( strpool_embedded_t* pool, int size, int* alloc_size )
+ {
+ char* data;
+ int i;
+ int offset;
+ if( size < (int)sizeof( strpool_embedded_internal_free_block_t ) ) size = sizeof( strpool_embedded_internal_free_block_t );
+ if( size < pool->min_data_size ) size = pool->min_data_size;
+ size = (int)strpool_embedded_internal_pow2ceil( (STRPOOL_EMBEDDED_U32)size );
+
+ // Try to find a large enough free slot in existing blocks
+ for( i = 0; i < pool->block_count; ++i )
+ {
+ int free_list = pool->blocks[ i ].free_list;
+ int prev_list = -1;
+ while( free_list >= 0 )
+ {
+ strpool_embedded_internal_free_block_t* free_entry =
+ (strpool_embedded_internal_free_block_t*) ( pool->blocks[ i ].data + free_list );
+ if( free_entry->size / 2 < size )
+ {
+ // At this point, all remaining slots are too small, so bail out if the current slot is not large enough
+ if( free_entry->size < size ) break;
+
+ if( prev_list < 0 )
+ {
+ pool->blocks[ i ].free_list = free_entry->next;
+ }
+ else
+ {
+ strpool_embedded_internal_free_block_t* prev_entry =
+ (strpool_embedded_internal_free_block_t*) ( pool->blocks[ i ].data + prev_list );
+ prev_entry->next = free_entry->next;
+ }
+ *alloc_size = free_entry->size;
+ return (char*) free_entry;
+ }
+ prev_list = free_list;
+ free_list = free_entry->next;
+ }
+ }
+
+ // Use current block, if enough space left
+ offset = (int) ( pool->blocks[ pool->current_block ].tail - pool->blocks[ pool->current_block ].data );
+ if( size <= pool->blocks[ pool->current_block ].capacity - offset )
+ {
+ char* data = pool->blocks[ pool->current_block ].tail;
+ pool->blocks[ pool->current_block ].tail += size;
+ *alloc_size = size;
+ return data;
+ }
+
+ // Allocate a new block
+ pool->current_block = strpool_embedded_internal_add_block( pool, size > pool->block_size ? size : pool->block_size );
+ data = pool->blocks[ pool->current_block ].tail;
+ pool->blocks[ pool->current_block ].tail += size;
+ *alloc_size = size;
+ return data;
+ }
+
+
+STRPOOL_EMBEDDED_U64 strpool_embedded_inject( strpool_embedded_t* pool, char const* string, int length )
+ {
+ STRPOOL_EMBEDDED_U32 hash;
+ int base_slot;
+ int base_count;
+ int slot;
+ int first_free;
+ int handle_index;
+ strpool_embedded_internal_entry_t* entry;
+ int data_size;
+ char* data;
+ if( !string || length < 0 ) return 0;
+
+ hash = strpool_embedded_internal_find_in_blocks( pool, string, length );
+ // If no stored hash, calculate it from data
+ if( !hash ) hash = strpool_embedded_internal_calculate_hash( string, length, pool->ignore_case );
+
+ // Return handle to existing string, if it is already in pool
+ base_slot = (int)( hash & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
+ base_count = pool->hash_table[ base_slot ].base_count;
+ slot = base_slot;
+ first_free = slot;
+ while( base_count > 0 )
+ {
+ STRPOOL_EMBEDDED_U32 slot_hash = pool->hash_table[ slot ].hash_key;
+ int slot_base;
+ if( slot_hash == 0 && pool->hash_table[ first_free ].hash_key != 0 ) first_free = slot;
+ slot_base = (int)( slot_hash & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
+ if( slot_base == base_slot )
+ {
+ STRPOOL_EMBEDDED_ASSERT( base_count > 0 );
+ --base_count;
+ if( slot_hash == hash )
+ {
+ int index = pool->hash_table[ slot ].entry_index;
+ strpool_embedded_internal_entry_t* entry = &pool->entries[ index ];
+ if( entry->length == length &&
+ (
+ ( !pool->ignore_case && STRPOOL_EMBEDDED_MEMCMP( entry->data + 2 * sizeof( STRPOOL_EMBEDDED_U32 ), string, (size_t)length ) == 0 )
+ || ( pool->ignore_case && STRPOOL_EMBEDDED_STRNICMP( entry->data + 2 * sizeof( STRPOOL_EMBEDDED_U32 ), string, (size_t)length ) == 0 )
+ )
+ )
+ {
+ int handle_index = entry->handle_index;
+ return strpool_embedded_internal_make_handle( handle_index, pool->handles[ handle_index ].counter,
+ pool->index_mask, pool->counter_shift, pool->counter_mask );
+ }
+ }
+ }
+ slot = ( slot + 1 ) & ( pool->hash_capacity - 1 );
+ }
+
+ // This is a new string, so let's add it
+
+ if( pool->entry_count >= ( pool->hash_capacity - pool->hash_capacity / 3 ) )
+ {
+ strpool_embedded_internal_expand_hash_table( pool );
+
+ base_slot = (int)( hash & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
+ slot = base_slot;
+ first_free = slot;
+ while( base_count )
+ {
+ STRPOOL_EMBEDDED_U32 slot_hash = pool->hash_table[ slot ].hash_key;
+ int slot_base;
+ if( slot_hash == 0 && pool->hash_table[ first_free ].hash_key != 0 ) first_free = slot;
+ slot_base = (int)( slot_hash & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
+ if( slot_base == base_slot ) --base_count;
+ slot = ( slot + 1 ) & ( pool->hash_capacity - 1 );
+ }
+ }
+
+ slot = first_free;
+ while( pool->hash_table[ slot ].hash_key )
+ slot = ( slot + 1 ) & ( pool->hash_capacity - 1 );
+
+ if( pool->entry_count >= pool->entry_capacity )
+ strpool_embedded_internal_expand_entries( pool );
+
+ STRPOOL_EMBEDDED_ASSERT( !pool->hash_table[ slot ].hash_key && ( hash & ( (STRPOOL_EMBEDDED_U32) pool->hash_capacity - 1 ) ) == (STRPOOL_EMBEDDED_U32) base_slot );
+ STRPOOL_EMBEDDED_ASSERT( hash );
+ pool->hash_table[ slot ].hash_key = hash;
+ pool->hash_table[ slot ].entry_index = pool->entry_count;
+ ++pool->hash_table[ base_slot ].base_count;
+
+ if( pool->handle_count < pool->handle_capacity )
+ {
+ handle_index = pool->handle_count;
+ pool->handles[ pool->handle_count ].counter = 1;
+ ++pool->handle_count;
+ }
+ else if( pool->handle_freelist_head >= 0 )
+ {
+ handle_index = pool->handle_freelist_head;
+ if( pool->handle_freelist_tail == pool->handle_freelist_head )
+ pool->handle_freelist_tail = pool->handles[ pool->handle_freelist_head ].entry_index;
+ pool->handle_freelist_head = pool->handles[ pool->handle_freelist_head ].entry_index;
+ }
+ else
+ {
+ strpool_embedded_internal_expand_handles( pool );
+ handle_index = pool->handle_count;
+ pool->handles[ pool->handle_count ].counter = 1;
+ ++pool->handle_count;
+ }
+
+ pool->handles[ handle_index ].entry_index = pool->entry_count;
+
+ entry = &pool->entries[ pool->entry_count ];
+ ++pool->entry_count;
+
+ data_size = length + 1 + (int) ( 2 * sizeof( STRPOOL_EMBEDDED_U32 ) );
+ data = strpool_embedded_internal_get_data_storage( pool, data_size, &data_size );
+ entry->hash_slot = slot;
+ entry->handle_index = handle_index;
+ entry->data = data;
+ entry->size = data_size;
+ entry->length = length;
+ entry->refcount = 0;
+
+ *(STRPOOL_EMBEDDED_U32*)(data) = hash;
+ data += sizeof( STRPOOL_EMBEDDED_U32 );
+ *(STRPOOL_EMBEDDED_U32*)(data) = (STRPOOL_EMBEDDED_U32) length;
+ data += sizeof( STRPOOL_EMBEDDED_U32 );
+ STRPOOL_EMBEDDED_MEMCPY( data, string, (size_t) length );
+ data[ length ] = 0; // Ensure trailing zero
+
+ return strpool_embedded_internal_make_handle( handle_index, pool->handles[ handle_index ].counter, pool->index_mask,
+ pool->counter_shift, pool->counter_mask );
+ }
+
+
+char const* strpool_embedded_cstr( strpool_embedded_t const* pool, STRPOOL_EMBEDDED_U64 handle )
+ {
+ strpool_embedded_internal_entry_t const* entry = strpool_embedded_internal_get_entry( pool, handle );
+ if( entry ) return entry->data + 2 * sizeof( STRPOOL_EMBEDDED_U32 ); // Skip leading hash value
+ return NULL;
+ }
+
+#endif // STRPOOL_EMBEDDED_IMPLEMENTATION_ONCE
+#endif /* STRPOOL_EMBEDDED_IMPLEMENTATION */
+
+
+/*
+revision history:
+ 1.4 fixed find_in_blocks substring bug, removed realloc, added docs
+ 1.3 fixed typo in mask bit shift
+ 1.2 made it possible to override standard library functions
+ 1.1 added is_valid function to query a handles validity
+ 1.0 first released version
+*/
+
+
+/*
+------------------------------------------------------------------------------
+
+This software is available under 2 licenses - you may choose the one you like.
+
+------------------------------------------------------------------------------
+
+ALTERNATIVE A - MIT License
+
+Copyright (c) 2015 Mattias Gustavsson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+------------------------------------------------------------------------------
+
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+------------------------------------------------------------------------------
+*/
+
+/*
+ end embedding strpool.h
+*/
+
+#if !defined(CUTE_TILED_WARNING)
+ #define CUTE_TILED_DEFAULT_WARNING
+ #define CUTE_TILED_WARNING(msg) cute_tiled_warning(msg, __LINE__)
+#endif
+
+#if !defined(CUTE_TILED_MEMCPY)
+ #include <string.h> // memcpy
+ #define CUTE_TILED_MEMCPY memcpy
+#endif
+
+#if !defined(CUTE_TILED_MEMSET)
+ #include <string.h> // memset
+ #define CUTE_TILED_MEMSET memset
+#endif
+
+#if !defined(CUTE_TILED_UNUSED)
+ #if defined(_MSC_VER)
+ #define CUTE_TILED_UNUSED(x) (void)x
+ #else
+ #define CUTE_TILED_UNUSED(x) (void)(sizeof(x))
+ #endif
+#endif
+
+#if !defined(CUTE_TILED_SNPRINTF)
+ #include <stdio.h> // snprintf
+ #define CUTE_TILED_SNPRINTF snprintf
+#endif
+
+#if !defined(CUTE_TILED_SEEK_SET)
+ #include <stdio.h> // SEEK_SET
+ #define CUTE_TILED_SEEK_SET SEEK_SET
+#endif
+
+#if !defined(CUTE_TILED_SEEK_END)
+ #include <stdio.h> // SEEK_END
+ #define CUTE_TILED_SEEK_END SEEK_END
+#endif
+
+#if !defined(CUTE_TILED_FILE)
+ #include <stdio.h> // FILE
+ #define CUTE_TILED_FILE FILE
+#endif
+
+#if !defined(CUTE_TILED_FOPEN)
+ #include <stdio.h> // fopen
+ #define CUTE_TILED_FOPEN fopen
+#endif
+
+#if !defined(CUTE_TILED_FSEEK)
+ #include <stdio.h> // fseek
+ #define CUTE_TILED_FSEEK fseek
+#endif
+
+#if !defined(CUTE_TILED_FREAD)
+ #include <stdio.h> // fread
+ #define CUTE_TILED_FREAD fread
+#endif
+
+#if !defined(CUTE_TILED_FTELL)
+ #include <stdio.h> // ftell
+ #define CUTE_TILED_FTELL ftell
+#endif
+
+#if !defined(CUTE_TILED_FCLOSE)
+ #include <stdio.h> // fclose
+ #define CUTE_TILED_FCLOSE fclose
+#endif
+
+int cute_tiled_error_cline; // The line in cute_tiled.h where the error was triggered.
+const char* cute_tiled_error_reason; // The error message.
+int cute_tiled_error_line; // The line where the error happened in the json.
+const char* cute_tiled_error_file = NULL; // The filepath of the file being parsed. NULL if from memory.
+
+#ifdef CUTE_TILED_DEFAULT_WARNING
+ #include <stdio.h>
+
+ void cute_tiled_warning(const char* warning, int line)
+ {
+ const char *error_file = cute_tiled_error_file ? cute_tiled_error_file : "MEMORY";
+ cute_tiled_error_cline = line;
+ printf("WARNING (cute_tiled.h:%i): %s (%s:%i)\n", cute_tiled_error_cline, warning, error_file, cute_tiled_error_line);
+ }
+#endif
+
+#include <stdlib.h>
+
+#if !defined(CUTE_TILED_STRTOLL)
+ #define CUTE_TILED_STRTOLL strtoll
+#endif
+
+#if !defined(CUTE_TILED_STRTOULL)
+ #define CUTE_TILED_STRTOULL strtoull
+#endif
+
+#if !defined(CUTE_TILED_STRTOD)
+ #define CUTE_TILED_STRTOD strtod
+#endif
+
+typedef struct cute_tiled_page_t cute_tiled_page_t;
+typedef struct cute_tiled_map_internal_t cute_tiled_map_internal_t;
+
+struct cute_tiled_page_t
+{
+ cute_tiled_page_t* next;
+ void* data;
+};
+
+#define CUTE_TILED_INTERNAL_BUFFER_MAX 1024
+
+struct cute_tiled_map_internal_t
+{
+ char* in;
+ char* end;
+ cute_tiled_map_t map;
+ strpool_embedded_t strpool;
+ void* mem_ctx;
+ int page_size;
+ int bytes_left_on_page;
+ cute_tiled_page_t* pages;
+ int scratch_len;
+ char scratch[CUTE_TILED_INTERNAL_BUFFER_MAX];
+};
+
+void* cute_tiled_alloc(cute_tiled_map_internal_t* m, int size)
+{
+ void* data;
+ if (size > m->page_size) return NULL; // Should never happen.
+ if (m->bytes_left_on_page < size)
+ {
+ cute_tiled_page_t* page = (cute_tiled_page_t*)CUTE_TILED_ALLOC(sizeof(cute_tiled_page_t) + m->page_size, m->mem_ctx);
+ if (!page) return 0;
+ page->next = m->pages;
+ page->data = page + 1;
+ m->pages = page;
+ m->bytes_left_on_page = m->page_size;
+ }
+
+ data = ((char*)m->pages->data) + (m->page_size - m->bytes_left_on_page);
+ m->bytes_left_on_page -= size;
+ return data;
+}
+
+CUTE_TILED_U64 cute_tiled_FNV1a(const void* buf, int len)
+{
+ CUTE_TILED_U64 h = (CUTE_TILED_U64)14695981039346656037U;
+ const char* str = (const char*)buf;
+
+ while (len--)
+ {
+ char c = *str++;
+ h = h ^ (CUTE_TILED_U64)c;
+ h = h * (CUTE_TILED_U64)1099511628211;
+ }
+
+ return h;
+}
+
+static char* cute_tiled_read_file_to_memory_and_null_terminate(const char* path, int* size, void* mem_ctx)
+{
+ char* data = 0;
+ CUTE_TILED_FILE* fp = CUTE_TILED_FOPEN(path, "rb");
+ int sz = 0;
+ CUTE_TILED_UNUSED(mem_ctx);
+
+ if (fp)
+ {
+ CUTE_TILED_FSEEK(fp, 0, CUTE_TILED_SEEK_END);
+ sz = CUTE_TILED_FTELL(fp);
+ CUTE_TILED_FSEEK(fp, 0, CUTE_TILED_SEEK_SET);
+ data = (char*)CUTE_TILED_ALLOC(sz + 1, mem_ctx);
+ CUTE_TILED_FREAD(data, sz, 1, fp);
+ data[sz] = 0;
+ CUTE_TILED_FCLOSE(fp);
+ }
+
+ if (size) *size = sz;
+ return data;
+}
+
+cute_tiled_map_t* cute_tiled_load_map_from_file(const char* path, void* mem_ctx)
+{
+ int size;
+ void* file;
+ cute_tiled_map_t* map;
+ cute_tiled_error_file = path;
+
+ file = cute_tiled_read_file_to_memory_and_null_terminate(path, &size, mem_ctx);
+ if (!file) CUTE_TILED_WARNING("Unable to find map file.");
+ map = cute_tiled_load_map_from_memory(file, size, mem_ctx);
+ CUTE_TILED_FREE(file, mem_ctx);
+
+ cute_tiled_error_file = NULL;
+
+ return map;
+}
+
+#define CUTE_TILED_CHECK(X, Y) do { if (!(X)) { cute_tiled_error_reason = Y; cute_tiled_error_cline = __LINE__; goto cute_tiled_err; } } while (0)
+#define CUTE_TILED_FAIL_IF(X) do { if (X) { goto cute_tiled_err; } } while (0)
+
+static int cute_tiled_isspace(char c)
+{
+ cute_tiled_error_line += c == '\n';
+
+ return (c == ' ') |
+ (c == '\t') |
+ (c == '\n') |
+ (c == '\v') |
+ (c == '\f') |
+ (c == '\r');
+}
+
+static char cute_tiled_peak(cute_tiled_map_internal_t* m)
+{
+ while (cute_tiled_isspace(*m->in)) m->in++;
+ return *m->in;
+}
+
+#ifdef __clang__
+ #define CUTE_TILED_CRASH() __builtin_trap()
+#else
+ #define CUTE_TILED_CRASH() *(int*)0 = 0
+#endif
+
+static char cute_tiled_next(cute_tiled_map_internal_t* m)
+{
+ char c;
+ if (m->in == m->end) CUTE_TILED_CRASH();
+ while (cute_tiled_isspace(c = *m->in++));
+ return c;
+}
+
+static char cute_tiled_string_next(cute_tiled_map_internal_t* m)
+{
+ char c;
+ if (m->in == m->end) CUTE_TILED_CRASH();
+ c = *m->in++;
+ return c;
+}
+
+static int cute_tiled_try(cute_tiled_map_internal_t* m, char expect)
+{
+ if (m->in == m->end) CUTE_TILED_CRASH();
+ if (cute_tiled_peak(m) == expect)
+ {
+ m->in++;
+ return 1;
+ }
+ return 0;
+}
+
+#define cute_tiled_expect(m, expect) \
+ do { \
+ static char error[128]; \
+ CUTE_TILED_SNPRINTF(error, sizeof(error), "Found unexpected token '%c', expected '%c' (is this a valid JSON file?).", *m->in, expect); \
+ CUTE_TILED_CHECK(cute_tiled_next(m) == (expect), error); \
+ } while (0)
+
+char cute_tiled_parse_char(char c)
+{
+ switch (c)
+ {
+ case '\\': return '\\';
+ case '\'': return '\'';
+ case '"': return '"';
+ case 't': return '\t';
+ case 'f': return '\f';
+ case 'n': return '\n';
+ case 'r': return '\r';
+ case '0': return '\0';
+ default: return c;
+ }
+}
+
+static int cute_tiled_skip_object_internal(cute_tiled_map_internal_t* m)
+{
+ int depth = 1;
+ cute_tiled_expect(m, '{');
+
+ while (depth) {
+ char c;
+ CUTE_TILED_CHECK(m->in <= m->end, "Attempted to read passed input buffer (is this a valid JSON file?).");
+
+ c = cute_tiled_next(m);
+
+ switch(c)
+ {
+ case '{':
+ depth += 1;
+ break;
+
+ case '}':
+ depth -= 1;
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_skip_object(m) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_skip_object_internal(m)); \
+ } while (0)
+
+static int cute_tiled_skip_array_internal(cute_tiled_map_internal_t* m)
+{
+ int depth = 1;
+ cute_tiled_expect(m, '[');
+
+ while (depth)
+ {
+ char c;
+ CUTE_TILED_CHECK(m->in <= m->end, "Attempted to read passed input buffer (is this a valid JSON file?).");
+
+ c = cute_tiled_next(m);
+
+ switch(c)
+ {
+ case '[':
+ depth += 1;
+ break;
+
+ case ']':
+ depth -= 1;
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_skip_array(m) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_skip_array_internal(m)); \
+ } while (0)
+
+static int cute_tiled_read_string_internal(cute_tiled_map_internal_t* m)
+{
+ int count = 0;
+ int done = 0;
+ cute_tiled_expect(m, '"');
+
+ while (!done)
+ {
+ char c;
+ CUTE_TILED_CHECK(count < CUTE_TILED_INTERNAL_BUFFER_MAX, "String exceeded max length of CUTE_TILED_INTERNAL_BUFFER_MAX.");
+ c = cute_tiled_string_next(m);
+
+ switch (c)
+ {
+ case '"':
+ m->scratch[count] = 0;
+ done = 1;
+ break;
+
+ case '\\':
+ {
+ char the_char = cute_tiled_parse_char(cute_tiled_string_next(m));
+ m->scratch[count++] = the_char;
+ } break;
+
+ default:
+ m->scratch[count++] = c;
+ break;
+ }
+ }
+
+ m->scratch_len = count;
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_string(m) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_string_internal(m)); \
+ } while (0)
+
+static int cute_tiled_read_int_internal(cute_tiled_map_internal_t* m, int* out)
+{
+ char* end;
+ int val = (int)CUTE_TILED_STRTOLL(m->in, &end, 10);
+ if (*end == '.') CUTE_TILED_STRTOD(m->in, &end); // If we're reading a float as an int, then just skip the decimal part.
+ CUTE_TILED_CHECK(m->in != end, "Invalid integer found during parse.");
+ m->in = end;
+ *out = val;
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_int(m, num) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_int_internal(m, num)); \
+ } while (0)
+
+static uint32_t cute_tiled_read_hex_int_internal(cute_tiled_map_internal_t* m, uint32_t* out)
+{
+ char* end;
+ unsigned long long int val;
+ int val_length = 0;
+ switch (cute_tiled_peak(m))
+ {
+ case '#':
+ cute_tiled_next(m);
+ break;
+
+ case '0':
+ {
+ char c;
+ cute_tiled_next(m);
+ c = cute_tiled_next(m);
+ CUTE_TILED_CHECK((c == 'x') | (c == 'X'), "Expected 'x' or 'X' while parsing a hex number.");
+ } break;
+ }
+
+ val = CUTE_TILED_STRTOULL(m->in, &end, 16);
+ CUTE_TILED_CHECK(m->in != end, "Invalid integer found during parse.");
+
+ // Count the length of the value to determine if we need to force AARRGGBB, instead of RRGGBB.
+ while (m->in != end) {
+ m->in++;
+ val_length++;
+ }
+ *out = (uint32_t)val;
+
+ // When less than 6 characters, force an alpha channel of 255.
+ if (val_length <= 6) {
+ uint32_t alpha = 0xFFu << 24;
+ *out = (*out & 0x00FFFFFF) | alpha;
+ }
+
+ m->in = end;
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_hex_int(m, num) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_hex_int_internal(m, num)); \
+ } while (0)
+
+static int cute_tiled_read_float_internal(cute_tiled_map_internal_t* m, float* out)
+{
+ char* end;
+ float val = (float)strtod(m->in, &end);
+ CUTE_TILED_CHECK(m->in != end, "Invalid integer found during parse.");
+ m->in = end;
+ *out = val;
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_float(m, num) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_float_internal(m, num)); \
+ } while (0)
+
+static int cute_tiled_read_bool_internal(cute_tiled_map_internal_t* m, int* out)
+{
+ if ((cute_tiled_peak(m) == 't') | (cute_tiled_peak(m) == 'T'))
+ {
+ m->in += 4;
+ *out = 1;
+ }
+
+ else if ((cute_tiled_peak(m) == 'f') | (cute_tiled_peak(m) == 'F'))
+ {
+ m->in += 5;
+ *out = 0;
+ }
+
+ else goto cute_tiled_err;
+
+ CUTE_TILED_CHECK(m->in <= m->end, "Attempted to read passed input buffer (is this a valid JSON file?).");
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_bool(m, b) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_bool_internal(m, b)); \
+ } while (0)
+
+int cute_tiled_read_csv_integers_internal(cute_tiled_map_internal_t* m, int* count_out, int** out)
+{
+ int count = 0;
+ int capacity = 1024;
+ int* integers = (int*)CUTE_TILED_ALLOC(capacity * sizeof(int), m->mem_ctx);
+
+ char c;
+ do
+ {
+ int val;
+ cute_tiled_read_int(m, &val);
+ if (count == capacity)
+ {
+ int* new_integers;
+ capacity *= 2;
+ new_integers = (int*)CUTE_TILED_ALLOC(capacity * sizeof(int), m->mem_ctx);
+ CUTE_TILED_MEMCPY(new_integers, integers, sizeof(int) * count);
+ CUTE_TILED_FREE(integers, m->mem_ctx);
+ integers = new_integers;
+ }
+ integers[count++] = val;
+ c = cute_tiled_next(m);
+ }
+ while (c != ']');
+
+ *count_out = count;
+ *out = integers;
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_csv_integers(m, count_out, out) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_csv_integers_internal(m, count_out, out)); \
+ } while (0)
+
+int cute_tiled_intern_string_internal(cute_tiled_map_internal_t* m, cute_tiled_string_t* out)
+{
+ STRPOOL_EMBEDDED_U64 id;
+ cute_tiled_read_string(m);
+
+ // Store string id inside the memory of the pointer. This is important since
+ // the string pool can relocate strings while parsing the map file at any
+ // time.
+
+ // Later there will be a second pass to patch all these string
+ // pointers by doing: *out = (const char*)strpool_embedded_cstr(&m->strpool, id);
+
+ id = strpool_embedded_inject(&m->strpool, m->scratch, m->scratch_len);
+ // if (sizeof(const char*) < sizeof(STRPOOL_EMBEDDED_U64)) *(int*)0 = 0; // sanity check
+ out->hash_id = id;
+
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_intern_string(m, out) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_intern_string_internal(m, out)); \
+ } while (0)
+
+int cute_tiled_read_vertex_array_internal(cute_tiled_map_internal_t* m, int* out_count, float** out_verts)
+{
+ int vert_count = 0;
+ int capacity = 32;
+ float *verts;
+ cute_tiled_expect(m, '[');
+
+ verts = (float*)CUTE_TILED_ALLOC(sizeof(float) * capacity * 2, m->mem_ctx);
+
+ while (cute_tiled_peak(m) != ']')
+ {
+ int swap;
+ float x = 0, y = 0;
+ cute_tiled_expect(m, '{');
+ cute_tiled_expect(m, '"');
+
+ swap = cute_tiled_try(m, 'x') ? 0 : 1;
+
+ cute_tiled_expect(m, '"');
+ cute_tiled_expect(m, ':');
+ cute_tiled_read_float(m, swap ? &y : &x);
+ cute_tiled_expect(m, ',');
+ cute_tiled_expect(m, '"');
+ cute_tiled_expect(m, swap ? 'x' : 'y');
+ cute_tiled_expect(m, '"');
+ cute_tiled_expect(m, ':');
+ cute_tiled_read_float(m, swap ? &x : &y);
+ cute_tiled_expect(m, '}');
+ cute_tiled_try(m, ',');
+
+ if (vert_count == capacity)
+ {
+ float* new_verts;
+ capacity *= 2;
+ new_verts = (float*)CUTE_TILED_ALLOC(sizeof(float) * capacity * 2, m->mem_ctx);
+ CUTE_TILED_MEMCPY(new_verts, verts, sizeof(float) * 2 * vert_count);
+ CUTE_TILED_FREE(verts, m->mem_ctx);
+ verts = new_verts;
+ }
+
+ verts[vert_count * 2] = x;
+ verts[vert_count * 2 + 1] = y;
+ ++vert_count;
+ }
+
+ cute_tiled_expect(m, ']');
+ *out_count = vert_count;
+ *out_verts = verts;
+
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_vertex_array(m, out_count, out_verts) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_vertex_array_internal(m, out_count, out_verts)); \
+ } while (0)
+
+int cute_tiled_skip_until_after_internal(cute_tiled_map_internal_t* m, char c)
+{
+ while (*m->in != c) {
+ cute_tiled_error_line += *m->in == '\n';
+ m->in++;
+ }
+ cute_tiled_expect(m, c);
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_skip_until_after(m, c) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_skip_until_after_internal(m, c)); \
+ } while (0)
+
+int cute_tiled_read_properties_internal(cute_tiled_map_internal_t* m, cute_tiled_property_t** out_properties, int* out_count)
+{
+ int count = 0;
+ int capacity = 32;
+ cute_tiled_property_t* props = (cute_tiled_property_t*)CUTE_TILED_ALLOC(capacity * sizeof(cute_tiled_property_t), m->mem_ctx);
+
+ cute_tiled_expect(m, '[');
+
+ while (cute_tiled_peak(m) != ']')
+ {
+ cute_tiled_property_t prop;
+ char type_char;
+ char c;
+ cute_tiled_expect(m, '{');
+
+ prop.type = CUTE_TILED_PROPERTY_NONE;
+
+ // Read in the property name.
+ cute_tiled_skip_until_after(m, ':');
+ cute_tiled_intern_string(m, &prop.name);
+
+ // Read in the property type. The value type is deduced while parsing, this is only used for float because the JSON format omits decimals on round floats.
+ cute_tiled_skip_until_after(m, ':');
+ cute_tiled_expect(m, '"');
+ type_char = cute_tiled_next(m);
+
+ // Skip extraneous JSON information and go find the actual value data.
+ cute_tiled_skip_until_after(m, ':');
+
+ c = cute_tiled_peak(m);
+
+ if (((c == 't') | (c == 'T')) | ((c == 'f') | (c == 'F')))
+ {
+ cute_tiled_read_bool(m, &prop.data.boolean);
+ prop.type = CUTE_TILED_PROPERTY_BOOL;
+ }
+
+ else if (c == '"')
+ {
+ char* s = m->in + 1;
+ int is_hex_color = 1;
+
+ if (*s++ != '#') is_hex_color = 0;
+ else
+ {
+ while ((c = *s++) != '"')
+ {
+ switch (c)
+ {
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6':
+ case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd':
+ case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
+ break;
+
+ case '\\':
+ ++s;
+ break;
+
+ default:
+ is_hex_color = 0;
+ break;
+ }
+
+ if (!is_hex_color) break;
+ }
+ }
+
+ if (is_hex_color)
+ {
+ cute_tiled_expect(m, '"');
+ cute_tiled_read_hex_int(m, &prop.data.color);
+ cute_tiled_expect(m, '"');
+ prop.type = CUTE_TILED_PROPERTY_COLOR;
+ }
+
+ else
+ {
+ cute_tiled_intern_string(m, &prop.data.string);
+ prop.type = CUTE_TILED_PROPERTY_STRING;
+ }
+ }
+
+ else
+ {
+ char* s = m->in;
+ int is_float = 0;
+ while ((c = *s++) != ',')
+ {
+ if (c == '.')
+ {
+ is_float = 1;
+ break;
+ }
+ }
+
+ if (is_float || type_char == 'f')
+ {
+ cute_tiled_read_float(m, &prop.data.floating);
+ prop.type = CUTE_TILED_PROPERTY_FLOAT;
+ }
+
+ else
+ {
+ cute_tiled_read_int(m, &prop.data.integer);
+ prop.type = CUTE_TILED_PROPERTY_INT;
+ }
+ }
+
+ if (count == capacity)
+ {
+ cute_tiled_property_t* new_props;
+ capacity *= 2;
+ new_props = (cute_tiled_property_t*)CUTE_TILED_ALLOC(capacity * sizeof(cute_tiled_property_t), m->mem_ctx);
+ CUTE_TILED_MEMCPY(new_props, props, sizeof(cute_tiled_property_t) * count);
+ CUTE_TILED_FREE(props, m->mem_ctx);
+ props = new_props;
+ }
+ props[count++] = prop;
+
+ cute_tiled_expect(m, '}');
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, ']');
+ cute_tiled_try(m, ',');
+
+ *out_properties = count ? props : NULL;
+ if (!count) CUTE_TILED_FREE(props, m->mem_ctx);
+ *out_count = count;
+
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_properties(m, out_properties, out_count) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_properties_internal(m, out_properties, out_count)); \
+ } while (0)
+
+cute_tiled_object_t* cute_tiled_read_object(cute_tiled_map_internal_t* m)
+{
+ cute_tiled_object_t* object = (cute_tiled_object_t*)cute_tiled_alloc(m, sizeof(cute_tiled_object_t));
+ CUTE_TILED_MEMSET(object, 0, sizeof(cute_tiled_object_t));
+ cute_tiled_expect(m, '{');
+
+ while (cute_tiled_peak(m) != '}')
+ {
+ CUTE_TILED_U64 h;
+ cute_tiled_read_string(m);
+ cute_tiled_expect(m, ':');
+ h = cute_tiled_FNV1a(m->scratch, m->scratch_len + 1);
+
+ switch (h)
+ {
+ case 14479365350473253539U: // ellipse
+ cute_tiled_read_bool(m, &object->ellipse);
+ break;
+
+ case 14992147199312073281U: // gid
+ cute_tiled_read_int(m, &object->gid);
+ break;
+
+ case 809651598226485190U: // height
+ cute_tiled_read_float(m, &object->height);
+ break;
+
+ case 3133932603199444032U: // id
+ cute_tiled_read_int(m, &object->id);
+ break;
+
+ case 12661511911333414066U: // name
+ cute_tiled_intern_string(m, &object->name);
+ break;
+
+ case 15925463322410838979U: // point
+ cute_tiled_read_bool(m, &object->point);
+ break;
+
+ case 11191351929714760271U: // polyline
+ cute_tiled_read_vertex_array(m, &object->vert_count, &object->vertices);
+ object->vert_type = 0;
+ break;
+
+ case 6623316362411997547U: // polygon
+ cute_tiled_read_vertex_array(m, &object->vert_count, &object->vertices);
+ object->vert_type = 1;
+ break;
+
+ case 8368542207491637236U: // properties
+ cute_tiled_read_properties(m, &object->properties, &object->property_count);
+ break;
+
+ case 17386473859969670701U: // rotation
+ cute_tiled_read_float(m, &object->rotation);
+ break;
+
+ case 7758770083360183834U: // text
+ CUTE_TILED_WARNING("Text field of Tiled objects is not yet supported. Ignoring field.");
+ while (cute_tiled_peak(m) != ',' && cute_tiled_peak(m) != '}') cute_tiled_next(m);
+ if (cute_tiled_peak(m) == '}') continue;
+ break;
+
+ case 13509284784451838071U: // type
+ cute_tiled_intern_string(m, &object->type);
+ break;
+
+ case 128234417907068947U: // visible
+ cute_tiled_read_bool(m, &object->visible);
+ break;
+
+ case 7400839267610537869U: // width
+ cute_tiled_read_float(m, &object->width);
+ break;
+
+ case 644252274336276709U: // x
+ cute_tiled_read_float(m, &object->x);
+ break;
+
+ case 643295699219922364U: // y
+ cute_tiled_read_float(m, &object->y);
+ break;
+
+ case 1485919047363370797U: // class
+ // This is technically different than type, but it used the same way in newer versions of Tiled
+ cute_tiled_intern_string(m, &object->type);
+ break;
+
+ default:
+ CUTE_TILED_CHECK(0, "Unknown identifier found.");
+ }
+
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, '}');
+ return object;
+
+cute_tiled_err:
+ return 0;
+}
+
+cute_tiled_chunk_t* cute_tiled_chunks(cute_tiled_map_internal_t* m) {
+ cute_tiled_chunk_t* chunk = (cute_tiled_chunk_t*)cute_tiled_alloc(m, sizeof(cute_tiled_chunk_t));
+
+ CUTE_TILED_MEMSET(chunk, 0, sizeof(cute_tiled_layer_t));
+
+ cute_tiled_expect(m, '{');
+
+ while (cute_tiled_peak(m) != '}')
+ {
+ CUTE_TILED_U64 h;
+ cute_tiled_read_string(m);
+ cute_tiled_expect(m, ':');
+ h = cute_tiled_FNV1a(m->scratch, m->scratch_len + 1);
+
+ switch (h)
+ {
+ case 4430454992770877055U: // data
+ CUTE_TILED_CHECK(cute_tiled_peak(m) == '[', "The expected tile format is CSV (uncompressed). It looks like Base64 (uncompressed) was selected. Please see the docs if you are interested in compression.");
+ cute_tiled_expect(m, '[');
+ cute_tiled_read_csv_integers(m, &chunk->data_count, &chunk->data);
+ break;
+
+ case 809651598226485190U: // height
+ cute_tiled_read_int(m, &chunk->height);
+ break;
+
+ case 7400839267610537869U: // width
+ cute_tiled_read_int(m, &chunk->width);
+ break;
+
+ case 644252274336276709U: // x
+ cute_tiled_read_int(m, &chunk->x);
+ break;
+
+ case 643295699219922364U: // y
+ cute_tiled_read_int(m, &chunk->y);
+ break;
+ }
+
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, '}');
+ return chunk;
+
+cute_tiled_err:
+ return 0;
+}
+
+cute_tiled_layer_t* cute_tiled_layers(cute_tiled_map_internal_t* m)
+{
+ cute_tiled_layer_t* layer = (cute_tiled_layer_t*)cute_tiled_alloc(m, sizeof(cute_tiled_layer_t));
+ CUTE_TILED_MEMSET(layer, 0, sizeof(cute_tiled_layer_t));
+ layer->parallaxx = 1.0f;
+ layer->parallaxy = 1.0f;
+ layer->repeatx = 0;
+ layer->repeaty = 0;
+
+ cute_tiled_expect(m, '{');
+
+
+ while (cute_tiled_peak(m) != '}')
+ {
+ CUTE_TILED_U64 h;
+ cute_tiled_read_string(m);
+ cute_tiled_expect(m, ':');
+ h = cute_tiled_FNV1a(m->scratch, m->scratch_len + 1);
+
+ switch (h)
+ {
+ case 16604818415630589433U: // chunks
+ cute_tiled_expect(m, '[');
+
+ while (cute_tiled_peak(m) != ']')
+ {
+ cute_tiled_chunk_t* chunk = cute_tiled_chunks(m);
+ CUTE_TILED_FAIL_IF(!chunk);
+ chunk->next = layer->chunks;
+ layer->chunks = chunk;
+ // layer->next = m->map.layers;
+ // m->map.layers = layer;
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, ']');
+ break;
+ case 1485919047363370797U: // class
+ cute_tiled_intern_string(m, &layer->class_);
+ break;
+
+ case 14868627273436340303U: // compression
+ CUTE_TILED_CHECK(0, "Compression is not yet supported. The expected tile format is CSV (uncompressed). Please see the docs if you are interested in compression.");
+ break;
+
+ case 4430454992770877055U: // data
+ CUTE_TILED_CHECK(cute_tiled_peak(m) == '[', "The expected tile format is CSV (uncompressed). It looks like Base64 (uncompressed) was selected. Please see the docs if you are interested in compression.");
+ cute_tiled_expect(m, '[');
+ cute_tiled_read_csv_integers(m, &layer->data_count, &layer->data);
+ break;
+
+ case 1888774307506158416U: // encoding
+ CUTE_TILED_CHECK(0, "Encoding is not yet supported. The expected tile format is CSV (uncompressed). Please see the docs if you are interested in compression.");
+ break;
+
+ case 2841939415665718447U: // draworder
+ cute_tiled_intern_string(m, &layer->draworder);
+ break;
+
+ case 809651598226485190U: // height
+ cute_tiled_read_int(m, &layer->height);
+ break;
+
+ case 13522647194774232494U: // image
+ cute_tiled_intern_string(m, &layer->image);
+ break;
+
+ case 4566956252693479661U: // layers
+ cute_tiled_expect(m, '[');
+
+ while (cute_tiled_peak(m) != ']')
+ {
+ cute_tiled_layer_t* child_layer = cute_tiled_layers(m);
+ CUTE_TILED_FAIL_IF(!child_layer);
+ child_layer->next = layer->layers;
+ layer->layers = child_layer;
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, ']');
+ break;
+
+ case 12661511911333414066U: // name
+ cute_tiled_intern_string(m, &layer->name);
+ break;
+
+ case 107323337999513585U: // objects
+ cute_tiled_expect(m, '[');
+
+ while (cute_tiled_peak(m) != ']')
+ {
+ cute_tiled_object_t* object = cute_tiled_read_object(m);
+ CUTE_TILED_FAIL_IF(!object);
+ object->next = layer->objects;
+ layer->objects = object;
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, ']');
+ break;
+
+ case 5195853646368960386U: // offsetx
+ cute_tiled_read_float(m, &layer->offsetx);
+ break;
+
+ case 5196810221485314731U: // offsety
+ cute_tiled_read_float(m, &layer->offsety);
+ break;
+
+ case 11746902372727406098U: // opacity
+ cute_tiled_read_float(m, &layer->opacity);
+ break;
+
+ case 14335666674294018687U: // startX
+ cute_tiled_read_int(m, &layer->startx);
+ break;
+
+ case 14334710099177664342U: // startY
+ cute_tiled_read_int(m, &layer->starty);
+ break;
+
+ case 8368542207491637236U: // properties
+ cute_tiled_read_properties(m, &layer->properties, &layer->property_count);
+ break;
+
+ case 8489814081865549564U: // transparentcolor
+ cute_tiled_expect(m, '"');
+ cute_tiled_read_hex_int(m, &layer->transparentcolor);
+ cute_tiled_expect(m, '"');
+ break;
+
+ case 1211175872446544425U: // tintcolor
+ cute_tiled_expect(m, '"');
+ cute_tiled_read_hex_int(m, &layer->tintcolor);
+ cute_tiled_expect(m, '"');
+ break;
+
+ case 13509284784451838071U: // type
+ cute_tiled_intern_string(m, &layer->type);
+ break;
+
+ case 128234417907068947U: // visible
+ cute_tiled_read_bool(m, &layer->visible);
+ break;
+
+ case 7400839267610537869U: // width
+ cute_tiled_read_int(m, &layer->width);
+ break;
+
+ case 644252274336276709U: // x
+ cute_tiled_read_int(m, &layer->x);
+ break;
+
+ case 643295699219922364U: // y
+ cute_tiled_read_int(m, &layer->y);
+ break;
+
+ case 18212633776084966362U: // parallaxx
+ cute_tiled_read_float(m, &layer->parallaxx);
+ break;
+
+ case 18213590351201320707U: // parallaxy
+ cute_tiled_read_float(m, &layer->parallaxy);
+ break;
+
+ case 222650047040294978U: // repeatx
+ cute_tiled_read_bool(m, &layer->repeatx);
+ break;
+
+ case 223606622156649323U: // repeaty
+ cute_tiled_read_bool(m, &layer->repeaty);
+ break;
+
+ case 3133932603199444032U: // id
+ cute_tiled_read_int(m, &layer->id);
+ break;
+
+ case 7796197983149768626: // image-layer imagewidth
+ cute_tiled_read_int(m, &layer->imagewidth);
+ break;
+
+ case 2114495263010514843: // image-layer imageheight
+ cute_tiled_read_int(m, &layer->imageheight);
+ break;
+
+ case 4827327220562374952: // object-layer color
+ cute_tiled_expect(m, '"');
+ cute_tiled_read_hex_int(m, &layer->tintcolor);
+ cute_tiled_expect(m, '"');
+ break;
+
+ default:
+ CUTE_TILED_CHECK(0, "Unknown identifier found.");
+ }
+
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, '}');
+ return layer;
+
+cute_tiled_err:
+ return 0;
+}
+
+int cute_tiled_read_animation_frames_internal(cute_tiled_map_internal_t* m, cute_tiled_frame_t** out_frames, int* out_count)
+{
+ int count = 0;
+ int capacity = 32;
+ cute_tiled_frame_t* frames = (cute_tiled_frame_t*)CUTE_TILED_ALLOC(capacity * sizeof(cute_tiled_frame_t), m->mem_ctx);
+
+ cute_tiled_expect(m, '[');
+
+ while (cute_tiled_peak(m) != ']')
+ {
+ cute_tiled_frame_t frame;
+ cute_tiled_expect(m, '{');
+
+ // Read in the duration and tileid.
+ cute_tiled_skip_until_after(m, ':');
+ cute_tiled_read_int(m, &frame.duration);
+ cute_tiled_expect(m, ',');
+ cute_tiled_skip_until_after(m, ':');
+ cute_tiled_read_int(m, &frame.tileid);
+
+ if (count == capacity)
+ {
+ cute_tiled_frame_t* new_frames;
+ capacity *= 2;
+ new_frames = (cute_tiled_frame_t*)CUTE_TILED_ALLOC(capacity * sizeof(cute_tiled_frame_t), m->mem_ctx);
+ CUTE_TILED_MEMCPY(new_frames, frames, sizeof(cute_tiled_frame_t) * count);
+ CUTE_TILED_FREE(frames, m->mem_ctx);
+ frames = new_frames;
+ }
+ frames[count++] = frame;
+
+ cute_tiled_expect(m, '}');
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, ']');
+ cute_tiled_try(m, ',');
+
+ *out_frames = frames;
+ *out_count = count;
+
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_animation_frames(m, out_frames, out_count) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_animation_frames_internal(m, out_frames, out_count)); \
+ } while (0)
+
+cute_tiled_tile_descriptor_t* cute_tiled_read_tile_descriptor(cute_tiled_map_internal_t* m)
+{
+ cute_tiled_tile_descriptor_t* tile_descriptor = (cute_tiled_tile_descriptor_t*)cute_tiled_alloc(m, sizeof(cute_tiled_tile_descriptor_t));
+ CUTE_TILED_MEMSET(tile_descriptor, 0, sizeof(cute_tiled_tile_descriptor_t));
+
+ cute_tiled_expect(m, '{');
+ while (cute_tiled_peak(m) != '}')
+ {
+ CUTE_TILED_U64 h;
+ cute_tiled_read_string(m);
+ cute_tiled_expect(m, ':');
+ h = cute_tiled_FNV1a(m->scratch, m->scratch_len + 1);
+
+ switch (h)
+ {
+ case 3133932603199444032U: // id
+ cute_tiled_read_int(m, &tile_descriptor->tile_index);
+ break;
+
+ case 13509284784451838071U: // type
+ cute_tiled_intern_string(m, &tile_descriptor->type);
+ break;
+
+ case 13522647194774232494U: // image
+ cute_tiled_intern_string(m, &tile_descriptor->image);
+ break;
+
+ case 7796197983149768626U: // imagewidth
+ cute_tiled_read_int(m, &tile_descriptor->imagewidth);
+ break;
+
+ case 2114495263010514843U: // imageheight
+ cute_tiled_read_int(m, &tile_descriptor->imageheight);
+ break;
+
+ case 8368542207491637236U: // properties
+ cute_tiled_read_properties(m, &tile_descriptor->properties, &tile_descriptor->property_count);
+ break;
+
+ case 6659907350341014391U: // objectgroup
+ {
+ cute_tiled_layer_t* layer = cute_tiled_layers(m);
+ CUTE_TILED_FAIL_IF(!layer);
+ layer->next = tile_descriptor->objectgroup;
+ tile_descriptor->objectgroup = layer;
+ } break;
+
+ case 6875414612738028948: // probability
+ cute_tiled_read_float(m, &tile_descriptor->probability);
+ break;
+
+ case 2784044778313316778U: // terrain: used by tiled editor only
+ cute_tiled_skip_array(m);
+ break;
+
+ case 3115399308714904519U: // animation
+ cute_tiled_read_animation_frames(m, &tile_descriptor->animation, &tile_descriptor->frame_count);
+ break;
+
+ default:
+ CUTE_TILED_CHECK(0, "Unknown identifier found.");
+ }
+
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, '}');
+ return tile_descriptor;
+
+cute_tiled_err:
+ return 0;
+}
+
+int cute_tiled_read_point_internal(cute_tiled_map_internal_t* m, int* point_x, int* point_y)
+{
+ *point_x = 0;
+ *point_y = 0;
+
+ cute_tiled_expect(m, '{');
+ while (cute_tiled_peak(m) != '}')
+ {
+ CUTE_TILED_U64 h;
+ cute_tiled_read_string(m);
+ cute_tiled_expect(m, ':');
+ h = cute_tiled_FNV1a(m->scratch, m->scratch_len + 1);
+
+ switch (h)
+ {
+ case 644252274336276709U: // x
+ cute_tiled_read_int(m, point_x);
+ break;
+
+ case 643295699219922364U: // y
+ cute_tiled_read_int(m, point_y);
+ break;
+
+ default:
+ CUTE_TILED_CHECK(0, "Unknown identifier found.");
+ }
+
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, '}');
+
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_read_point(m, x, y) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_read_point_internal(m, x, y)); \
+ } while (0)
+
+static CUTE_TILED_INLINE int cute_tiled_skip_curly_braces_internal(cute_tiled_map_internal_t* m)
+{
+ int count = 1;
+ cute_tiled_expect(m, '{');
+ while (count)
+ {
+ char c = cute_tiled_next(m);
+ if (c == '}') --count;
+ else if (c == '{') ++count;
+ }
+
+ return 0;
+
+cute_tiled_err:
+ return 1;
+}
+
+cute_tiled_tileset_t* cute_tiled_tileset(cute_tiled_map_internal_t* m)
+{
+ cute_tiled_tileset_t* tileset = (cute_tiled_tileset_t*)cute_tiled_alloc(m, sizeof(cute_tiled_tileset_t));
+ CUTE_TILED_MEMSET(tileset, 0, sizeof(cute_tiled_tileset_t));
+ cute_tiled_expect(m, '{');
+
+ while (cute_tiled_peak(m) != '}')
+ {
+ CUTE_TILED_U64 h;
+ cute_tiled_read_string(m);
+ cute_tiled_expect(m, ':');
+ h = cute_tiled_FNV1a(m->scratch, m->scratch_len + 1);
+
+ switch (h)
+ {
+ case 17465100621023921744U: // backgroundcolor
+ cute_tiled_expect(m, '"');
+ cute_tiled_read_hex_int(m, &tileset->backgroundcolor);
+ cute_tiled_expect(m, '"');
+ break;
+
+ case 1485919047363370797U: // class
+ cute_tiled_intern_string(m, &tileset->class_);
+ break;
+
+ case 12570673734542705940U: // columns
+ cute_tiled_read_int(m, &tileset->columns);
+ break;
+
+ case 13648382824248632287U: // editorsettings
+ cute_tiled_skip_object(m);
+ break;
+
+ case 13956389100366699181U: // firstgid
+ cute_tiled_read_int(m, &tileset->firstgid);
+ break;
+
+ case 16920059161811221315U: // grid: unsupported
+ cute_tiled_skip_object(m);
+ break;
+
+ case 13522647194774232494U: // image
+ cute_tiled_intern_string(m, &tileset->image);
+ break;
+
+ case 7796197983149768626U: // imagewidth
+ cute_tiled_read_int(m, &tileset->imagewidth);
+ break;
+
+ case 2114495263010514843U: // imageheight
+ cute_tiled_read_int(m, &tileset->imageheight);
+ break;
+
+ case 4864566659847942049U: // margin
+ cute_tiled_read_int(m, &tileset->margin);
+ break;
+
+ case 12661511911333414066U: // name
+ cute_tiled_intern_string(m, &tileset->name);
+ break;
+
+ case 1007832939408977147U: // tiledversion
+ cute_tiled_intern_string(m, &tileset->tiledversion);
+ break;
+
+ case 8196820454517111669U: // version
+ if (*m->in == '"')
+ m->in++;
+ cute_tiled_read_float(m, &tileset->version);
+ if (*m->in == '"')
+ m->in++;
+ break;
+
+ case 8368542207491637236U: // properties
+ cute_tiled_read_properties(m, &tileset->properties, &tileset->property_count);
+ break;
+
+ case 6491372721122724890U: // spacing
+ cute_tiled_read_int(m, &tileset->spacing);
+ break;
+
+ case 4065097716972592720U: // tilecount
+ cute_tiled_read_int(m, &tileset->tilecount);
+ break;
+
+ case 13337683360624280154U: // tileheight
+ cute_tiled_read_int(m, &tileset->tileheight);
+ break;
+
+ case 2769630600247906626U: // tileoffset
+ cute_tiled_read_point(m, &tileset->tileoffset_x, &tileset->tileoffset_y);
+ break;
+
+ case 7277156227374254384U: // tileproperties
+ CUTE_TILED_WARNING("`tileproperties` is deprecated. Attempting to skip.");
+ CUTE_TILED_FAIL_IF(cute_tiled_skip_curly_braces_internal(m));
+ break;
+
+ case 15569462518706435895U: // tilepropertytypes
+ CUTE_TILED_WARNING("`tilepropertytypes` is deprecated. Attempting to skip.");
+ CUTE_TILED_FAIL_IF(cute_tiled_skip_curly_braces_internal(m));
+ break;
+
+ case 6504415465426505561U: // tilewidth
+ cute_tiled_read_int(m, &tileset->tilewidth);
+ break;
+
+ case 8489814081865549564U: // transparentcolor
+ cute_tiled_expect(m, '"');
+ cute_tiled_read_hex_int(m, &tileset->transparentcolor);
+ cute_tiled_expect(m, '"');
+ break;
+
+ case 13509284784451838071U: // type
+ cute_tiled_intern_string(m, &tileset->type);
+ break;
+
+ case 8053780534892277672U: // source
+ cute_tiled_intern_string(m, &tileset->source);
+#ifndef CUTE_TILED_NO_EXTERNAL_TILESET_WARNING
+ CUTE_TILED_WARNING("You might have forgotten to embed your tileset -- Most fields of `cute_tiled_tileset_t` will be zero'd out (unset).");
+#endif /* CUTE_TILED_NO_EXTERNAL_TILESET_WARNING */
+ break;
+
+ case 1819203229U: // objectalignment
+ cute_tiled_intern_string(m, &tileset->objectalignment);
+ break;
+
+ case 104417158474046698U: // tiles
+ {
+ cute_tiled_expect(m, '[');
+ while (cute_tiled_peak(m) != ']')
+ {
+ cute_tiled_tile_descriptor_t* tile_descriptor = cute_tiled_read_tile_descriptor(m);
+ CUTE_TILED_FAIL_IF(!tile_descriptor);
+ tile_descriptor->next = tileset->tiles;
+ tileset->tiles = tile_descriptor;
+ cute_tiled_try(m, ',');
+ }
+ cute_tiled_expect(m, ']');
+ } break;
+
+ case 14766449174202642533U: // terrains: used by tiled editor only
+ cute_tiled_skip_array(m);
+ break;
+
+ case 6029584663444593209U: // wangsets: used by tiled editor only
+ cute_tiled_skip_array(m);
+ break;
+
+ default:
+ CUTE_TILED_CHECK(0, "Unknown identifier found.");
+ }
+
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, '}');
+ return tileset;
+
+cute_tiled_err:
+ return 0;
+}
+
+static int cute_tiled_dispatch_map_internal(cute_tiled_map_internal_t* m)
+{
+ CUTE_TILED_U64 h;
+ cute_tiled_read_string(m);
+ cute_tiled_expect(m, ':');
+ h = cute_tiled_FNV1a(m->scratch, m->scratch_len + 1);
+
+ switch (h)
+ {
+ case 17465100621023921744U: // backgroundcolor
+ cute_tiled_expect(m, '"');
+ cute_tiled_read_hex_int(m, &m->map.backgroundcolor);
+ cute_tiled_expect(m, '"');
+ break;
+
+ case 1485919047363370797U: // class
+ cute_tiled_intern_string(m, &m->map.class_);
+ break;
+
+ case 5549108793316760247U: // compressionlevel
+ {
+ int compressionlevel;
+ cute_tiled_read_int(m, &compressionlevel);
+ CUTE_TILED_CHECK(compressionlevel == -1 || compressionlevel == 0, "Compression is not yet supported.");
+ } break;
+
+ case 13648382824248632287U: // editorsettings
+ cute_tiled_skip_object(m);
+ break;
+
+ case 809651598226485190U: // height
+ cute_tiled_read_int(m, &m->map.height);
+ break;
+
+ case 16529928297377797591U: // infinite
+ cute_tiled_read_bool(m, &m->map.infinite);
+ break;
+
+ case 4566956252693479661U: // layers
+ cute_tiled_expect(m, '[');
+
+ while (cute_tiled_peak(m) != ']')
+ {
+ cute_tiled_layer_t* layer = cute_tiled_layers(m);
+ CUTE_TILED_FAIL_IF(!layer);
+ layer->next = m->map.layers;
+ m->map.layers = layer;
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, ']');
+ break;
+
+ case 11291153769551921430U: // nextobjectid
+ cute_tiled_read_int(m, &m->map.nextobjectid);
+ break;
+
+ case 563935667693078739U: // orientation
+ cute_tiled_intern_string(m, &m->map.orientation);
+ break;
+
+ case 8368542207491637236U: // properties
+ cute_tiled_read_properties(m, &m->map.properties, &m->map.property_count);
+ break;
+
+ case 16693886730115578029U: // renderorder
+ cute_tiled_intern_string(m, &m->map.renderorder);
+ break;
+
+ case 1007832939408977147U: // tiledversion
+ cute_tiled_intern_string(m, &m->map.tiledversion);
+ break;
+
+ case 13337683360624280154U: // tileheight
+ cute_tiled_read_int(m, &m->map.tileheight);
+ break;
+
+ case 8310322674355535532U: // tilesets
+ {
+ cute_tiled_expect(m, '[');
+
+ while (cute_tiled_peak(m) != ']')
+ {
+ cute_tiled_tileset_t* tileset = cute_tiled_tileset(m);
+ CUTE_TILED_FAIL_IF(!tileset);
+ tileset->next = m->map.tilesets;
+ m->map.tilesets = tileset;
+ cute_tiled_try(m, ',');
+ }
+
+ cute_tiled_expect(m, ']');
+ } break;
+
+ case 6504415465426505561U: // tilewidth
+ cute_tiled_read_int(m, &m->map.tilewidth);
+ break;
+
+ case 13509284784451838071U: // type
+ cute_tiled_intern_string(m, &m->map.type);
+ break;
+
+ case 8196820454517111669U: // version
+ if (*m->in == '"')
+ m->in++;
+ cute_tiled_read_float(m, &m->map.version);
+ if (*m->in == '"')
+ m->in++;
+ break;
+
+ case 7400839267610537869U: // width
+ cute_tiled_read_int(m, &m->map.width);
+ break;
+
+ case 2498445529143042872U: // nextlayerid
+ cute_tiled_read_int(m, &m->map.nextlayerid);
+ break;
+
+ default:
+ CUTE_TILED_CHECK(0, "Unknown identifier found.");
+ }
+
+ return 1;
+
+cute_tiled_err:
+ return 0;
+}
+
+#define cute_tiled_dispatch_map(m) \
+ do { \
+ CUTE_TILED_FAIL_IF(!cute_tiled_dispatch_map_internal(m)); \
+ } while (0)
+
+static CUTE_TILED_INLINE void cute_tiled_deintern_string(cute_tiled_map_internal_t* m, cute_tiled_string_t* s)
+{
+ s->ptr = strpool_embedded_cstr(&m->strpool, s->hash_id);
+}
+
+static void cute_tiled_deintern_properties(cute_tiled_map_internal_t* m, cute_tiled_property_t* properties, int property_count)
+{
+ int i;
+ for (i = 0; i < property_count; ++i)
+ {
+ cute_tiled_property_t* p = properties + i;
+ cute_tiled_deintern_string(m, &p->name);
+ if (p->type == CUTE_TILED_PROPERTY_STRING) cute_tiled_deintern_string(m, &p->data.string);
+ }
+}
+
+static void cute_tiled_deintern_layer(cute_tiled_map_internal_t* m, cute_tiled_layer_t* layer)
+{
+ while (layer)
+ {
+ cute_tiled_object_t* object;
+ cute_tiled_deintern_string(m, &layer->class_);
+ cute_tiled_deintern_string(m, &layer->draworder);
+ cute_tiled_deintern_string(m, &layer->name);
+ cute_tiled_deintern_string(m, &layer->type);
+ cute_tiled_deintern_string(m, &layer->image);
+ cute_tiled_deintern_properties(m, layer->properties, layer->property_count);
+
+ object = layer->objects;
+ while (object)
+ {
+ cute_tiled_deintern_string(m, &object->name);
+ cute_tiled_deintern_string(m, &object->type);
+ cute_tiled_deintern_properties(m, object->properties, object->property_count);
+ object = object->next;
+ }
+
+ cute_tiled_deintern_layer(m, layer->layers);
+
+ layer = layer->next;
+ }
+}
+
+static void cute_tiled_patch_tileset_strings(cute_tiled_map_internal_t* m, cute_tiled_tileset_t* tileset)
+{
+ cute_tiled_tile_descriptor_t* tile_descriptor;
+ cute_tiled_deintern_string(m, &tileset->class_);
+ cute_tiled_deintern_string(m, &tileset->image);
+ cute_tiled_deintern_string(m, &tileset->name);
+ cute_tiled_deintern_string(m, &tileset->type);
+ cute_tiled_deintern_string(m, &tileset->source);
+ cute_tiled_deintern_string(m, &tileset->tiledversion);
+ cute_tiled_deintern_string(m, &tileset->objectalignment);
+ cute_tiled_deintern_properties(m, tileset->properties, tileset->property_count);
+ tile_descriptor = tileset->tiles;
+ while (tile_descriptor)
+ {
+ cute_tiled_deintern_string(m, &tile_descriptor->image);
+ cute_tiled_deintern_string(m, &tile_descriptor->type);
+ cute_tiled_deintern_properties(m, tile_descriptor->properties, tile_descriptor->property_count);
+ tile_descriptor = tile_descriptor->next;
+ }
+}
+
+static void cute_tiled_patch_interned_strings(cute_tiled_map_internal_t* m)
+{
+ cute_tiled_tileset_t* tileset;
+ cute_tiled_layer_t* layer;
+ cute_tiled_deintern_string(m, &m->map.class_);
+ cute_tiled_deintern_string(m, &m->map.orientation);
+ cute_tiled_deintern_string(m, &m->map.renderorder);
+ cute_tiled_deintern_string(m, &m->map.tiledversion);
+ cute_tiled_deintern_string(m, &m->map.type);
+ cute_tiled_deintern_properties(m, m->map.properties, m->map.property_count);
+
+ tileset = m->map.tilesets;
+ while (tileset)
+ {
+ cute_tiled_patch_tileset_strings(m, tileset);
+ tileset = tileset->next;
+ }
+
+ layer = m->map.layers;
+ cute_tiled_deintern_layer(m, layer);
+}
+
+static void cute_tiled_free_objects(cute_tiled_object_t* objects, void* mem_ctx)
+{
+ cute_tiled_object_t* object = objects;
+ CUTE_TILED_UNUSED(mem_ctx);
+ while (object)
+ {
+ if (object->properties) CUTE_TILED_FREE(object->properties, mem_ctx);
+ if (object->vertices) CUTE_TILED_FREE(object->vertices, mem_ctx);
+ object = object->next;
+ }
+}
+
+static void cute_tiled_free_chunks(cute_tiled_chunk_t* chunks, void* mem_ctx)
+{
+ cute_tiled_chunk_t* chunk = chunks;
+ CUTE_TILED_UNUSED(mem_ctx);
+ while (chunk)
+ {
+ if (chunk->data) CUTE_TILED_FREE(chunk->data, mem_ctx);
+ chunk = chunk->next;
+ }
+}
+
+static void cute_tiled_free_layers(cute_tiled_layer_t* layers, void* mem_ctx)
+{
+ cute_tiled_layer_t* layer = layers;
+ CUTE_TILED_UNUSED(mem_ctx);
+ while (layer)
+ {
+ if (layer->data) CUTE_TILED_FREE(layer->data, mem_ctx);
+ if (layer->properties) CUTE_TILED_FREE(layer->properties, mem_ctx);
+ cute_tiled_free_layers(layer->layers, mem_ctx);
+ cute_tiled_free_chunks(layer->chunks, mem_ctx);
+ cute_tiled_free_objects(layer->objects, mem_ctx);
+ layer = layer->next;
+ }
+}
+
+static void cute_tiled_free_map_internal(cute_tiled_map_internal_t* m)
+{
+ cute_tiled_tileset_t* tileset;
+ cute_tiled_page_t* page;
+ strpool_embedded_term(&m->strpool);
+
+ cute_tiled_free_layers(m->map.layers, m->mem_ctx);
+ if (m->map.properties) CUTE_TILED_FREE(m->map.properties, m->mem_ctx);
+
+ tileset = m->map.tilesets;
+ while (tileset)
+ {
+ cute_tiled_tile_descriptor_t* desc;
+ if (tileset->properties) CUTE_TILED_FREE(tileset->properties, m->mem_ctx);
+ desc = tileset->tiles;
+ while (desc)
+ {
+ if (desc->properties) CUTE_TILED_FREE(desc->properties, m->mem_ctx);
+ if (desc->animation) CUTE_TILED_FREE(desc->animation, m->mem_ctx);
+ cute_tiled_free_layers(desc->objectgroup, m->mem_ctx);
+ desc = desc->next;
+ }
+ tileset = tileset->next;
+ }
+
+ // cute_tiled_read_csv_integers
+ // cute_tiled_read_vertex_array
+ // cute_tiled_read_properties
+
+ page = m->pages;
+ while (page)
+ {
+ cute_tiled_page_t* next = page->next;
+ CUTE_TILED_FREE(page, m->mem_ctx);
+ page = next;
+ }
+
+ CUTE_TILED_FREE(m, m->mem_ctx);
+}
+
+#define CUTE_TILED_REVERSE_LIST(T, root) \
+ do { \
+ T* n = 0; \
+ while (root) { \
+ T* next = root->next; \
+ root->next = n; \
+ n = root; \
+ root = next; \
+ } \
+ root = n; \
+ } while (0)
+
+void cute_tiled_reverse_layers(cute_tiled_map_t* map)
+{
+ CUTE_TILED_REVERSE_LIST(cute_tiled_layer_t, map->layers);
+}
+
+static cute_tiled_map_internal_t* cute_tiled_map_internal_alloc_internal(void* memory, int size_in_bytes, void* mem_ctx)
+{
+ strpool_embedded_config_t config;
+ cute_tiled_map_internal_t* m = (cute_tiled_map_internal_t*)CUTE_TILED_ALLOC(sizeof(cute_tiled_map_internal_t), mem_ctx);
+ CUTE_TILED_MEMSET(m, 0, sizeof(cute_tiled_map_internal_t));
+ m->in = (char*)memory;
+ m->end = m->in + size_in_bytes;
+ m->mem_ctx = mem_ctx;
+ m->page_size = 1024 * 10;
+ m->bytes_left_on_page = m->page_size;
+ m->pages = (cute_tiled_page_t*)CUTE_TILED_ALLOC(sizeof(cute_tiled_page_t) + m->page_size, mem_ctx);
+ m->pages->next = 0;
+ m->pages->data = m->pages + 1;
+ config = strpool_embedded_default_config;
+ config.memctx = mem_ctx;
+ strpool_embedded_init(&m->strpool, &config);
+ return m;
+}
+
+cute_tiled_map_t* cute_tiled_load_map_from_memory(const void* memory, int size_in_bytes, void* mem_ctx)
+{
+ cute_tiled_map_internal_t* m;
+ cute_tiled_layer_t* layer;
+ cute_tiled_tileset_t* tileset;
+ cute_tiled_error_line = 1;
+
+ if (!memory) {
+ // Make sure your map file was correctly found and loaded.
+ // If you called `cute_tiled_load_map_from_file` make sure your path was correct, and check
+ // your printf warnings.
+ CUTE_TILED_CRASH();
+ }
+
+ m = cute_tiled_map_internal_alloc_internal((void*)memory, size_in_bytes, mem_ctx);
+ layer = m->map.layers;
+ tileset = m->map.tilesets;
+ cute_tiled_expect(m, '{');
+ while (cute_tiled_peak(m) != '}')
+ {
+ cute_tiled_dispatch_map(m);
+ cute_tiled_try(m, ',');
+ }
+ cute_tiled_expect(m, '}');
+
+ // finalize output by patching strings and reversing singly linked lists
+ cute_tiled_patch_interned_strings(m);
+ CUTE_TILED_REVERSE_LIST(cute_tiled_layer_t, m->map.layers);
+ CUTE_TILED_REVERSE_LIST(cute_tiled_tileset_t, m->map.tilesets);
+ while (layer)
+ {
+ CUTE_TILED_REVERSE_LIST(cute_tiled_object_t, layer->objects);
+ CUTE_TILED_REVERSE_LIST(cute_tiled_chunk_t, layer->chunks);
+ layer = layer->next;
+ }
+ while (tileset)
+ {
+ CUTE_TILED_REVERSE_LIST(cute_tiled_tile_descriptor_t, tileset->tiles);
+ tileset = tileset->next;
+ }
+
+ return &m->map;
+
+cute_tiled_err:
+ cute_tiled_free_map_internal(m);
+ CUTE_TILED_WARNING(cute_tiled_error_reason);
+ return 0;
+}
+
+void cute_tiled_free_map(cute_tiled_map_t* map)
+{
+ cute_tiled_map_internal_t* m = (cute_tiled_map_internal_t*)(((char*)map) - (size_t)(&((cute_tiled_map_internal_t*)0)->map));
+ cute_tiled_free_map_internal(m);
+}
+
+cute_tiled_tileset_t* cute_tiled_load_external_tileset(const char* path, void* mem_ctx)
+{
+ int size;
+ void* file;
+ cute_tiled_tileset_t* tileset;
+ cute_tiled_error_file = path;
+
+ file = cute_tiled_read_file_to_memory_and_null_terminate(path, &size, mem_ctx);
+ if (!file) CUTE_TILED_WARNING("Unable to find external tileset file.");
+ tileset = cute_tiled_load_external_tileset_from_memory(file, size, mem_ctx);
+ CUTE_TILED_FREE(file, mem_ctx);
+
+ cute_tiled_error_file = NULL;
+
+ return tileset;
+}
+
+cute_tiled_tileset_t* cute_tiled_load_external_tileset_from_memory(const void* memory, int size_in_bytes, void* mem_ctx)
+{
+ cute_tiled_map_internal_t* m = cute_tiled_map_internal_alloc_internal((void*)memory, size_in_bytes, mem_ctx);
+ cute_tiled_tileset_t* tileset = cute_tiled_tileset(m);
+ cute_tiled_patch_tileset_strings(m, tileset);
+ CUTE_TILED_REVERSE_LIST(cute_tiled_tile_descriptor_t, tileset->tiles);
+ tileset->_internal = m;
+ return tileset;
+}
+
+void cute_tiled_free_external_tileset(cute_tiled_tileset_t* tileset)
+{
+ cute_tiled_map_internal_t* m = (cute_tiled_map_internal_t*)tileset->_internal;
+ cute_tiled_free_map_internal(m);
+}
+
+#endif // CUTE_TILED_IMPLEMENTATION_ONCE
+#endif // CUTE_TILED_IMPLEMENTATION
+
+/*
+ ------------------------------------------------------------------------------
+ This software is available under 2 licenses - you may choose the one you like.
+ ------------------------------------------------------------------------------
+ ALTERNATIVE A - zlib license
+ Copyright (c) 2026 Randy Gaul https://randygaul.github.io
+ This software is provided 'as-is', without any express or implied warranty.
+ In no event will the authors be held liable for any damages arising from
+ the use of this software.
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not
+ be misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+ ------------------------------------------------------------------------------
+ ALTERNATIVE B - Public Domain (www.unlicense.org)
+ This is free and unencumbered software released into the public domain.
+ Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+ software, either in source code form or as a compiled binary, for any purpose,
+ commercial or non-commercial, and by any means.
+ In jurisdictions that recognize copyright laws, the author or authors of this
+ software dedicate any and all copyright interest in the software to the public
+ domain. We make this dedication for the benefit of the public at large and to
+ the detriment of our heirs and successors. We intend this dedication to be an
+ overt act of relinquishment in perpetuity of all present and future rights to
+ this software under copyright law.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ ------------------------------------------------------------------------------
+*/