A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(tilemap): share exact staggered and hex grid geometry
yhh0065d44f85b9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 14c2b3782..6612e5803 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Staggered and hexagonal picking follows cell polygons.** Core queries identify the containing diamond or hexagon instead of its rectangular partition, including negative coordinates and either stagger axis/index. Drawing and coordinate queries share native grid geometry, while editor outlines use the same effective hex side limit along the stagger axis. Shared edges resolve to a touching cell; rotation and translation preserve cell ownership. Picking examines at most three neighboring stagger lines without reading tile contents.+- **Rotated tile layers share one frame for drawing, picking and collision previews.** World Z rotation, including parent rotation, applies to tile vertices, visible chunk selection, editor grids, brush ghosts and world-to-tile queries. Collision previews rotate cached local geometry and keep large shapes visible when their bounds overlap the viewport. Generated tile one-way platforms rotate their solid side with the physics body; ordinary one-way platforms retain world-space normals unless `localSpace` is enabled. Static-parent rotation needs no repeated normal submissions, and rebuilt shapes restore their pre-solve behavior.## [0.88.0] - 2026-10-15diff --git a/desktop b/desktopindex 2c07cd24c..e1cf1beff 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 2c07cd24c902af19463a3fdf283508a16b95bcb9+Subproject commit e1cf1beffd1084f38307a7ed923e278a2bed91c8diff --git a/sdk/src/tilemap/tileGeometry.ts b/sdk/src/tilemap/tileGeometry.tsindex 92cbc2476..cea448a1e 100644--- a/sdk/src/tilemap/tileGeometry.ts+++ b/sdk/src/tilemap/tileGeometry.ts@@ -2,8 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file tileGeometry.ts- * @brief Orientation-aware tile-cell geometry — the single TS mirror of the C++- * placement math in TilemapRenderPlugin / TilemapSystem.+ * @brief Orientation-aware tile-cell geometry mirroring the native TileGrid.** The renderer draws each tile as a layer-local axis-aligned tileWidth×tileHeight quad;* only its CENTER moves per orientation (orthogonal / isometric / staggered /@@ -28,7 +27,7 @@ export interface TileGridParams {orientation: number;tileWidth: number;tileHeight: number;- /** Hex edge length in px along the stagger axis (0 → tileHeight/2). Hex only. */+ /** Hex edge along the stagger axis, bounded by that tile dimension (0 → tileHeight/2). */hexSideLength?: number;/** staggerAxis === X: columns stagger (else rows). Staggered + hex. */staggerAxisX?: boolean;@@ -43,14 +42,13 @@ export interface Vec2Like {/** The effective hex side length: the authored value, or the regular-hex fallback (th/2). */function hexSide(p: TileGridParams): number {- return p.hexSideLength && p.hexSideLength > 0 ? p.hexSideLength : p.tileHeight * 0.5;+ const side = p.hexSideLength && p.hexSideLength > 0 ? p.hexSideLength : p.tileHeight * 0.5;+ return Math.min(side, p.staggerAxisX ? p.tileWidth : p.tileHeight);}/**- * The center of cell (tx, ty) in the layer's local space (y-up, layer origin at 0,0).- * Add the layer entity's world position to get world coords. Mirrors the C++ renderer's- * `(worldX, worldY)` per-tile center exactly, so a painted map and an imported one place- * a given cell at the same point.+ * Cell center in layer-local pixels (y-up, origin at 0,0), matching native TileGrid.+ * Apply the layer's world rotation and position to obtain world coordinates.*/export function tileCellCenter(p: TileGridParams, tx: number, ty: number): Vec2Like {const hw = p.tileWidth * 0.5;@@ -90,7 +88,7 @@ export function tileCellOutline(p: TileGridParams): Vec2Like[] {// Diamond: top, right, bottom, left.return [{ x: 0, y: hh }, { x: hw, y: 0 }, { x: 0, y: -hh }, { x: -hw, y: 0 }];case TilemapOrientation.Hexagonal: {- const s = Math.min(hexSide(p), p.tileHeight, p.tileWidth); // clamp so it stays inside the box+ const s = hexSide(p);const hs = s * 0.5;if (p.staggerAxisX) {// Flat-top hex: horizontal flat edges (length s) top and bottom, points left/right.diff --git a/sdk/tests/tilemap-grid-picking-wasm.test.ts b/sdk/tests/tilemap-grid-picking-wasm.test.tsnew file mode 100644index 000000000..77c15ab02--- /dev/null+++ b/sdk/tests/tilemap-grid-picking-wasm.test.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { beforeAll, describe, expect, it } from 'vitest';+import type { ESEngineModule } from '../src/wasm';+import type { EngineApi } from '../src/ecs/bridge/engineApi';+import { createTilemapAPI } from '../src/tilemap/tilemapAPI';+import { tileCellCenter, tileCellOutline, type TileGridParams } from '../src/tilemap/tileGeometry';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++const layouts: TileGridParams[] = [];+for (const orientation of [2, 3]) for (const staggerAxisX of [false, true]) {+ for (const staggerIndexEven of [false, true]) for (const hexSideLength of [0, 6, 999]) {+ for (const [tileWidth, tileHeight] of [[16, 24], [64, 32]]) {+ layouts.push({ orientation, staggerAxisX, staggerIndexEven, hexSideLength, tileWidth, tileHeight });+ }+ }+}++describe.skipIf(!HAS_WASM)('native staggered and hexagonal polygon picking', () => {+ let core: ESEngineModule;+ beforeAll(async () => { core = await loadWasmModule(); });+ it.each(layouts)('picks polygon interiors under translation and rotation: %j', grid => {+ core.setActiveContext(null);+ const tiles = createTilemapAPI(core as EngineApi);+ tiles.initInfiniteLayer(10, grid.tileWidth, grid.tileHeight);+ tiles.setGridType(10, grid.orientation);+ tiles.setHexParams(10, grid.hexSideLength!, grid.staggerAxisX!, grid.staggerIndexEven!);+ const outline = tileCellOutline(grid);+ const probes = [{ x: 0, y: 0 }, ...outline.map(point => ({ x: point.x * .85, y: point.y * .85 })),+ ...outline.map((point, i) => ({ x: (point.x + outline[(i + 1) % outline.length].x) * .425,+ y: (point.y + outline[(i + 1) % outline.length].y) * .425 }))];+ try {+ for (const [x, y] of [[0, 0], [1, 0], [-1, -1], [64, -33], [-65, 17]]) {+ const center = tileCellCenter(grid, x, y);+ const anchor = tiles.tileToWorld(10, x, y, 0, 0);+ expect(anchor.x + grid.tileWidth * .5).toBeCloseTo(center.x, 4);+ expect(anchor.y - grid.tileHeight * .5).toBeCloseTo(center.y, 4);+ for (const rotation of [0, Math.PI / 2, -.37]) for (const probe of probes) {+ const lx = center.x + probe.x, ly = center.y + probe.y;+ const wx = 21 + Math.cos(rotation) * lx - Math.sin(rotation) * ly;+ const wy = -35 + Math.sin(rotation) * lx + Math.cos(rotation) * ly;+ expect(tiles.worldToTile(10, wx, wy, 21, -35, rotation)).toEqual({ x, y });+ }+ for (const boundary of outline) {+ const px = center.x + boundary.x, py = center.y + boundary.y;+ const owner = tiles.worldToTile(10, px, py, 0, 0);+ const picked = tileCellCenter(grid, owner.x, owner.y);+ const cross = outline.map((a, i) => {+ const b = outline[(i + 1) % outline.length];+ return (b.x - a.x) * (py - picked.y - a.y) - (b.y - a.y) * (px - picked.x - a.x);+ });+ const tolerance = .01 * Math.max(grid.tileWidth, grid.tileHeight);+ expect(Math.min(...cross) >= -tolerance || Math.max(...cross) <= tolerance).toBe(true);+ }+ }+ } finally { tiles.destroyLayer(10); }+ });+});diff --git a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp b/src/esengine/renderer/plugins/TilemapRenderPlugin.cppindex 415c5fc6e..c5c41ca49 100644--- a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp+++ b/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp@@ -34,6 +34,7 @@ void TilemapRenderPlugin::rebuildChunk(bool hasAnimations = !layer.tile_animations.empty();f32 hw = layer.tile_width * 0.5f;f32 hh = layer.tile_height * 0.5f;+ const auto grid = layer.grid();for (u32 ly = 0; ly < tilemap::CHUNK_SIZE; ++ly) {i32 ty = baseY + static_cast<i32>(ly);@@ -76,38 +77,8 @@ void TilemapRenderPlugin::rebuildChunk(// where the sampler hands back a tile that does exist.if (tileCol >= rs.atlasCols || tileRow >= rs.atlasRows) continue;- f32 worldX, worldY;- if (layer.grid_type == tilemap::GridType::Isometric) {- worldX = static_cast<f32>(tx - ty) * hw;- worldY = -static_cast<f32>(tx + ty) * hh;- } else if (layer.grid_type == tilemap::GridType::StaggeredIsometric- || layer.grid_type == tilemap::GridType::Hexagonal) {- // Staggered/hex share one layout: the stagger axis advances by- // (tile + side)/2, staggered lines shift half a tile along the- // other axis — matching Tiled's pixel placement so imported maps- // line up 1:1. Staggered iso is exactly hex with side length 0;- // hex with side 0 falls back to a regular pointy hex.- bool isHex = layer.grid_type == tilemap::GridType::Hexagonal;- f32 side = isHex ? (layer.hex_side_length > 0.0f ? layer.hex_side_length- : layer.tile_height * 0.5f)- : 0.0f;- if (layer.hex_stagger_axis_x) {- f32 colW = (layer.tile_width + side) * 0.5f;- bool staggered = ((tx & 1) != 0) != layer.hex_stagger_index_even;- worldX = static_cast<f32>(tx) * colW + hw;- worldY = -static_cast<f32>(ty) * layer.tile_height- - (staggered ? hh : 0.0f) - hh;- } else {- f32 rowH = (layer.tile_height + side) * 0.5f;- bool staggered = ((ty & 1) != 0) != layer.hex_stagger_index_even;- worldX = static_cast<f32>(tx) * layer.tile_width- + (staggered ? hw : 0.0f) + hw;- worldY = -static_cast<f32>(ty) * rowH - hh;- }- } else {- worldX = static_cast<f32>(tx) * layer.tile_width + hw;- worldY = -static_cast<f32>(ty) * layer.tile_height - hh;- }+ const auto center = grid.center(tx, ty);+ const f32 worldX = center.x, worldY = center.y;// Base tile UV rect (GL v increases upward, so vBottom < vTop), with// the atlas margin + spacing folded into offset/step so a Tiled tilesetdiff --git a/src/esengine/tilemap/TileGrid.hpp b/src/esengine/tilemap/TileGrid.hppnew file mode 100644index 000000000..7e315c54b--- /dev/null+++ b/src/esengine/tilemap/TileGrid.hpp@@ -0,0 +1,83 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file TileGrid.hpp+ * @brief Local tile placement and polygon containment shared by rendering and queries.+ */+#pragma once++#include "../core/Types.hpp"+#include <glm/glm.hpp>+#include <algorithm>+#include <cmath>+#include <initializer_list>++namespace esengine::tilemap {++enum class GridType : u8 {+ Orthogonal = 0,+ Isometric = 1,+ StaggeredIsometric = 2,+ Hexagonal = 3,+};++class TileGrid {+public:+ TileGrid(GridType type, f32 width, f32 height, f32 side, bool axisX, bool even)+ : type_(type), width_(width), height_(height), hw_(width * .5f), hh_(height * .5f),+ side_(type == GridType::Hexagonal+ ? std::min(side > 0 ? side : height * .5f, axisX ? width : height) : 0),+ step_(((axisX ? width : height) + side_) * .5f), axis_x_(axisX), even_(even) {}++ // Orthogonal/staggered anchors are top-left; isometric anchors are cell centers.+ glm::vec2 anchor(i32 x, i32 y) const {+ if (type_ == GridType::Isometric) return {(x - y) * hw_, -(x + y) * hh_};+ if (!staggered()) return {x * width_, -y * height_};+ if (axis_x_) return {x * step_, -y * height_ - (shifted(x) ? hh_ : 0)};+ return {x * width_ + (shifted(y) ? hw_ : 0), -y * step_};+ }++ glm::vec2 center(i32 x, i32 y) const {+ const auto a = anchor(x, y);+ return type_ == GridType::Isometric ? a : a + glm::vec2{hw_, -hh_};+ }++ glm::ivec2 cellAt(f32 x, f32 y) const {+ if (type_ == GridType::Isometric) return {floor(x / width_ - y / height_ + .5f),+ floor(-y / height_ - x / width_ + .5f)};+ if (!staggered()) return {floor(x / width_), floor(-y / height_)};+ const f32 down = -y;+ const i32 line = floor(((axis_x_ ? x - hw_ : down - hh_) / step_) + .5f);+ glm::ivec2 fallback{0, 0};+ // At most three stagger lines can overlap a point; tile contents are irrelevant.+ for (const i32 delta : {0, -1, 1}) {+ const i32 candidate = line + delta;+ const f32 shift = shifted(candidate) ? (axis_x_ ? hh_ : hw_) : 0;+ const i32 across = floor(((axis_x_ ? down : x) - shift) / (axis_x_ ? height_ : width_));+ const glm::ivec2 cell = axis_x_ ? glm::ivec2{candidate, across} : glm::ivec2{across, candidate};+ if (delta == 0) fallback = cell;+ const auto c = center(cell.x, cell.y);+ if (contains(x - c.x, y - c.y)) return cell;+ }+ return fallback;+ }++private:+ static i32 floor(f32 value) { return static_cast<i32>(std::floor(value)); }+ bool staggered() const { return type_ == GridType::StaggeredIsometric || type_ == GridType::Hexagonal; }+ bool shifted(i32 line) const { return ((line & 1) != 0) != even_; }+ bool contains(f32 x, f32 y) const {+ x = std::abs(x); y = std::abs(y);+ if (x > hw_ || y > hh_) return false;+ const f32 halfSide = side_ * .5f;+ if (axis_x_) return y * (hw_ - halfSide) + hh_ * std::max(0.0f, x - halfSide)+ <= hh_ * (hw_ - halfSide);+ return x * (hh_ - halfSide) + hw_ * std::max(0.0f, y - halfSide)+ <= hw_ * (hh_ - halfSide);+ }+ GridType type_;+ f32 width_, height_, hw_, hh_, side_, step_;+ bool axis_x_, even_;+};++} // namespace esengine::tilemapdiff --git a/src/esengine/tilemap/TilemapSystem.cpp b/src/esengine/tilemap/TilemapSystem.cppindex b364cfe0f..37418d810 100644--- a/src/esengine/tilemap/TilemapSystem.cpp+++ b/src/esengine/tilemap/TilemapSystem.cpp@@ -389,42 +389,9 @@ void TilemapSystem::tileToWorld(Entity entity, i32 tx, i32 ty,const auto* layer = getLayerData(entity);if (!layer) { outX = 0; outY = 0; return; }- f32 tw = layer->tile_width;- f32 th = layer->tile_height;-- switch (layer->grid_type) {- case GridType::Isometric:- outX = originX + static_cast<f32>(tx - ty) * tw * 0.5f;- outY = originY - static_cast<f32>(tx + ty) * th * 0.5f;- break;- case GridType::StaggeredIsometric:- case GridType::Hexagonal: {- // Staggered/hex share one layout: the stagger axis advances by- // (tile + side)/2 and staggered lines shift half a tile along the- // other axis (staggerindex picks odd or even lines). Staggered iso- // is exactly hex with side length 0; hex with side 0 falls back to a- // regular pointy hex (side = tileHeight/2).- bool isHex = layer->grid_type == GridType::Hexagonal;- f32 side = isHex ? (layer->hex_side_length > 0.0f ? layer->hex_side_length : th * 0.5f)- : 0.0f;- if (layer->hex_stagger_axis_x) {- f32 colW = (tw + side) * 0.5f;- bool staggered = ((tx & 1) != 0) != layer->hex_stagger_index_even;- outX = originX + static_cast<f32>(tx) * colW;- outY = originY - static_cast<f32>(ty) * th - (staggered ? th * 0.5f : 0.0f);- } else {- f32 rowH = (th + side) * 0.5f;- bool staggered = ((ty & 1) != 0) != layer->hex_stagger_index_even;- outX = originX + static_cast<f32>(tx) * tw + (staggered ? tw * 0.5f : 0.0f);- outY = originY - static_cast<f32>(ty) * rowH;- }- break;- }- default:- outX = originX + static_cast<f32>(tx) * tw;- outY = originY - static_cast<f32>(ty) * th;- break;- }+ const auto anchor = layer->grid().anchor(tx, ty);+ outX = originX + anchor.x;+ outY = originY + anchor.y;}void TilemapSystem::worldToTile(Entity entity, f32 wx, f32 wy,@@ -433,53 +400,9 @@ void TilemapSystem::worldToTile(Entity entity, f32 wx, f32 wy,const auto* layer = getLayerData(entity);if (!layer) { outTx = 0; outTy = 0; return; }- f32 tw = layer->tile_width;- f32 th = layer->tile_height;- f32 lx = wx - originX;- f32 ly = originY - wy;-- switch (layer->grid_type) {- case GridType::Isometric: {- // Isometric tiles are center-anchored (tileToWorld/renderer place the- // center at ((tx-ty)*tw/2, -(tx+ty)*th/2)), so this linear map sends a- // tile's diamond to the unit square centered on (tx,ty). Recovering the- // containing tile is therefore round-to-nearest, not floor — floor- // splits each diamond at its center and mis-attributes the upper half- // to the (tx-1,ty-1) neighbor.- f32 ftx = lx / tw + ly / th;- f32 fty = ly / th - lx / tw;- outTx = static_cast<i32>(std::floor(ftx + 0.5f));- outTy = static_cast<i32>(std::floor(fty + 0.5f));- break;- }- case GridType::StaggeredIsometric:- case GridType::Hexagonal: {- // Box-approximate: resolve the stagger line first, then the cell- // along it (no exact hex hit-test). Staggered iso is hex with side- // length 0; hex with side 0 falls back to a regular pointy hex.- bool isHex = layer->grid_type == GridType::Hexagonal;- f32 side = isHex ? (layer->hex_side_length > 0.0f ? layer->hex_side_length : th * 0.5f)- : 0.0f;- if (layer->hex_stagger_axis_x) {- f32 colW = (tw + side) * 0.5f;- i32 roughX = static_cast<i32>(std::floor(lx / colW));- bool staggered = ((roughX & 1) != 0) != layer->hex_stagger_index_even;- outTx = roughX;- outTy = static_cast<i32>(std::floor((ly - (staggered ? th * 0.5f : 0.0f)) / th));- } else {- f32 rowH = (th + side) * 0.5f;- i32 roughY = static_cast<i32>(std::floor(ly / rowH));- bool staggered = ((roughY & 1) != 0) != layer->hex_stagger_index_even;- outTy = roughY;- outTx = static_cast<i32>(std::floor((lx - (staggered ? tw * 0.5f : 0.0f)) / tw));- }- break;- }- default:- outTx = static_cast<i32>(std::floor(lx / tw));- outTy = static_cast<i32>(std::floor(ly / th));- break;- }+ const auto cell = layer->grid().cellAt(wx - originX, wy - originY);+ outTx = cell.x;+ outTy = cell.y;}} // namespace esengine::tilemapdiff --git a/src/esengine/tilemap/TilemapSystem.hpp b/src/esengine/tilemap/TilemapSystem.hppindex fa445324b..6ad27863d 100644--- a/src/esengine/tilemap/TilemapSystem.hpp+++ b/src/esengine/tilemap/TilemapSystem.hpp@@ -4,6 +4,7 @@#include "../core/Types.hpp"#include "TilesetTable.hpp"+#include "TileGrid.hpp"#include <glm/glm.hpp>#include <string>@@ -27,13 +28,6 @@ static constexpr u16 TILE_FLIP_V = 0x4000;ES_CONST(hex)static constexpr u16 TILE_FLIP_D = 0x8000;-enum class GridType : u8 {- Orthogonal = 0,- Isometric = 1,- StaggeredIsometric = 2,- Hexagonal = 3,-};-struct AnimFrame {u16 tile_id;u16 duration_ms;@@ -145,6 +139,11 @@ public:bool hex_stagger_axis_x = false; ///< true: columns stagger (staggeraxis=x)bool hex_stagger_index_even = false; ///< true: even rows/cols carry the shift+ TileGrid grid() const {+ return {grid_type, tile_width, tile_height, hex_side_length,+ hex_stagger_axis_x, hex_stagger_index_even};+ }+std::unordered_map<ChunkCoord, ChunkData, ChunkCoordHash> chunks;bool infinite = false;diff --git a/tests/tilemap/test_tilemap.cpp b/tests/tilemap/test_tilemap.cppindex 3273fb8be..b9b9646a9 100644--- a/tests/tilemap/test_tilemap.cpp+++ b/tests/tilemap/test_tilemap.cpp@@ -406,6 +406,27 @@ TEST_CASE("tilemap_iso_world_to_tile") {}}+TEST_CASE("staggered polygon interiors retain their owning cell") {+ for (const auto type : {GridType::StaggeredIsometric, GridType::Hexagonal}) {+ for (const bool axisX : {false, true}) for (const bool even : {false, true}) {+ for (const f32 side : {0.0f, 6.0f, 999.0f}) {+ TilemapSystem sys;+ sys.initInfiniteLayer(E(0), 16, 24);+ sys.setGridType(E(0), type); sys.setHexParams(E(0), side, axisX, even);+ for (i32 y = -3; y <= 3; ++y) for (i32 x = -3; x <= 3; ++x) {+ f32 ax, ay; sys.tileToWorld(E(0), x, y, 21, -35, ax, ay);+ for (const glm::vec2 offset : {glm::vec2{0, 0}, {6.8f, 0}, {-6.8f, 0}, {0, 10.2f}, {0, -10.2f}}) {+ i32 tx, ty;+ sys.worldToTile(E(0), ax + 8 + offset.x, ay - 12 + offset.y, 21, -35, tx, ty);+ CAPTURE(x); CAPTURE(y); CAPTURE(axisX); CAPTURE(even); CAPTURE(side);+ CHECK(tx == x); CHECK(ty == y);+ }+ }+ }+ }+ }+}+TEST_CASE("tilemap_animation_revision_separation") {// The render cache must distinguish a TABLE change (a tile GAINS an animation// → every chunk re-evaluates once, so an all-static chunk can become animated)diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex d8334a733..8716e6df3 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,10 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(tilemap): share exact staggered and hex grid geometry':+ { note: 'Staggered and hexagonal picking follows cell polygons.' },+ 'test(editor): cover staggered polygon picking through transforms':+ { internal: 'Exercises the real editor cursor-to-cell path over native diamond and hexagonal picking, including parent rotation, negative cells and both stagger axes and indices.' },'test(physics): keep lifecycle fixtures on the current module contract':{ internal: 'Updates lifecycle and shutdown module doubles to provide the new body-local one-way normal entry point while preserving native contract rejection tests.' },'test(editor): verify rotated tile layers through play':