Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
TilemapSystem.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#include "TilemapSystem.hpp"
4
5#include <algorithm>
6#include <cmath>
7#include <cstring>
8#include <limits>
9
10namespace esengine::tilemap {
11
12TileRange computeVisibleRange(f32 camLeft, f32 camBottom, f32 camRight, f32 camTop,
13 f32 originX, f32 originY,
14 f32 tileWidth, f32 tileHeight,
15 u32 mapWidth, u32 mapHeight) {
16 f32 localLeft = camLeft - originX;
17 f32 localBottom = camBottom - originY;
18 f32 localRight = camRight - originX;
19 f32 localTop = camTop - originY;
20
21 i32 minX = static_cast<i32>(std::floor(localLeft / tileWidth));
22 i32 minY = static_cast<i32>(std::floor(localBottom / tileHeight));
23 i32 maxX = static_cast<i32>(std::ceil(localRight / tileWidth));
24 i32 maxY = static_cast<i32>(std::ceil(localTop / tileHeight));
25
26 minX = std::max(minX, 0);
27 minY = std::max(minY, 0);
28 maxX = std::min(maxX, static_cast<i32>(mapWidth));
29 maxY = std::min(maxY, static_cast<i32>(mapHeight));
30
31 return {minX, minY, maxX, maxY};
32}
33
34// Tiles live in a sparse chunk map (the single store), addressed by floor-division so any
35// coordinate works — negative included (infinite painting).
36namespace {
37
38inline i32 chunkOf(i32 a) { // floor(a / CHUNK_SIZE), negative-safe
39 const i32 n = static_cast<i32>(CHUNK_SIZE);
40 return a / n - static_cast<i32>(a % n < 0);
41}
42
43// Finite layers (width>0) bound writes; infinite layers (width==0) take any coord.
44inline bool inBounds(const TilemapSystem::LayerData& layer, i32 x, i32 y) {
45 if (layer.width == 0 && layer.height == 0) return true;
46 return x >= 0 && y >= 0
47 && static_cast<u32>(x) < layer.width && static_cast<u32>(y) < layer.height;
48}
49
50inline u16 readTile(const TilemapSystem::LayerData& layer, i32 x, i32 y) {
51 const i32 cx = chunkOf(x), cy = chunkOf(y);
52 auto it = layer.chunks.find({cx, cy});
53 if (it == layer.chunks.end()) return EMPTY_TILE;
54 const i32 lx = x - cx * static_cast<i32>(CHUNK_SIZE);
55 const i32 ly = y - cy * static_cast<i32>(CHUNK_SIZE);
56 return it->second.tiles[static_cast<usize>(ly) * CHUNK_SIZE + static_cast<usize>(lx)];
57}
58
59inline void writeTile(TilemapSystem::LayerData& layer, i32 x, i32 y, u16 value) {
60 const i32 cx = chunkOf(x), cy = chunkOf(y);
61 const i32 lx = x - cx * static_cast<i32>(CHUNK_SIZE);
62 const i32 ly = y - cy * static_cast<i32>(CHUNK_SIZE);
63 const usize index = static_cast<usize>(ly) * CHUNK_SIZE + static_cast<usize>(lx);
64 auto it = layer.chunks.find({cx, cy});
65 if (it == layer.chunks.end()) {
66 if (value == EMPTY_TILE) return;
67 it = layer.chunks.try_emplace(ChunkCoord{cx, cy}).first;
68 }
69 ChunkData& chunk = it->second;
70 if (chunk.tiles[index] == value) return;
71 chunk.tiles[index] = value;
72 chunk.revision = ++layer.edit_revision;
73}
74
75// Tiled finite-layer load: chunk a flat row-major array, storing only non-empty chunks.
76void buildChunksFromFlat(TilemapSystem::LayerData& layer,
77 const u16* tiles, u32 width, u32 height, u32 count) {
78 if (!layer.chunks.empty()) ++layer.edit_revision;
79 layer.chunks.clear();
80 const u32 chunksX = (width + CHUNK_SIZE - 1) / CHUNK_SIZE;
81 const u32 chunksY = (height + CHUNK_SIZE - 1) / CHUNK_SIZE;
82 for (u32 cy = 0; cy < chunksY; ++cy) {
83 for (u32 cx = 0; cx < chunksX; ++cx) {
84 ChunkData chunk;
85 bool any = false;
86 for (u32 ly = 0; ly < CHUNK_SIZE; ++ly) {
87 const u32 ty = cy * CHUNK_SIZE + ly;
88 if (ty >= height) break;
89 for (u32 lx = 0; lx < CHUNK_SIZE; ++lx) {
90 const u32 tx = cx * CHUNK_SIZE + lx;
91 if (tx >= width) break;
92 const usize i = static_cast<usize>(ty) * width + tx;
93 const u16 v = (i < count) ? tiles[i] : EMPTY_TILE;
94 chunk.tiles[ly * CHUNK_SIZE + lx] = v;
95 if (v != EMPTY_TILE) any = true;
96 }
97 }
98 if (any) {
99 chunk.revision = ++layer.edit_revision;
100 layer.chunks[{static_cast<i32>(cx), static_cast<i32>(cy)}] = chunk;
101 }
102 }
103 }
104}
105
106} // namespace
107
108void TilemapSystem::initLayer(Entity entity, u32 width, u32 height,
109 f32 tileWidth, f32 tileHeight) {
110 LayerData layer;
111 layer.generation = ++next_generation_;
112 layer.width = width;
113 layer.height = height;
114 layer.tile_width = tileWidth;
115 layer.tile_height = tileHeight;
116 layers_[entity] = std::move(layer);
117}
118
119void TilemapSystem::initInfiniteLayer(Entity entity, f32 tileWidth, f32 tileHeight) {
120 LayerData layer;
121 layer.generation = ++next_generation_;
122 layer.width = 0;
123 layer.height = 0;
124 layer.tile_width = tileWidth;
125 layer.tile_height = tileHeight;
126 layer.infinite = true;
127 layers_[entity] = std::move(layer);
128}
129
130void TilemapSystem::setChunkTiles(Entity entity, i32 chunkX, i32 chunkY,
131 const u16* tiles, u32 width, u32 height) {
132 auto* layer = getLayerDataMut(entity);
133 if (!layer) return;
134
135 ChunkCoord coord{chunkX, chunkY};
136 auto& chunk = layer->chunks[coord];
137 chunk.revision = ++layer->edit_revision;
138 std::memset(chunk.tiles, 0, sizeof(chunk.tiles));
139
140 for (u32 ly = 0; ly < height && ly < CHUNK_SIZE; ++ly) {
141 for (u32 lx = 0; lx < width && lx < CHUNK_SIZE; ++lx) {
142 chunk.tiles[ly * CHUNK_SIZE + lx] = tiles[ly * width + lx];
143 }
144 }
145}
146
147void TilemapSystem::removeChunk(Entity entity, i32 chunkX, i32 chunkY) {
148 auto* layer = getLayerDataMut(entity);
149 if (!layer) return;
150 if (layer->chunks.erase(ChunkCoord{chunkX, chunkY}) == 0) return;
151 ++layer->edit_revision;
152 ++layer->chunks_erased;
153}
154
156 layers_.erase(entity);
157}
158
159bool TilemapSystem::hasLayer(Entity entity) const {
160 return layers_.count(entity) > 0;
161}
162
164 auto it = layers_.find(entity);
165 if (it == layers_.end()) return nullptr;
166 return &it->second;
167}
168
169void TilemapSystem::setTile(Entity entity, i32 x, i32 y, u16 tileId) {
170 auto it = layers_.find(entity);
171 if (it == layers_.end()) return;
172 auto& layer = it->second;
173 if (!inBounds(layer, x, y)) return;
174 writeTile(layer, x, y, tileId);
175}
176
178 auto it = layers_.find(entity);
179 if (it == layers_.end()) return EMPTY_TILE;
180 const auto& layer = it->second;
181 if (!inBounds(layer, x, y)) return EMPTY_TILE;
182 return readTile(layer, x, y);
183}
184
186 u32 w, u32 h, u16 tileId) {
187 auto it = layers_.find(entity);
188 if (it == layers_.end()) return;
189 auto& layer = it->second;
190 const i64 coordinateEnd = static_cast<i64>(std::numeric_limits<i32>::max()) + 1;
191 i64 startX = x, startY = y;
192 i64 endX = std::min(static_cast<i64>(x) + w, coordinateEnd);
193 i64 endY = std::min(static_cast<i64>(y) + h, coordinateEnd);
194 if (layer.width != 0 || layer.height != 0) {
195 startX = std::max(startX, i64{0});
196 startY = std::max(startY, i64{0});
197 endX = std::min(endX, static_cast<i64>(layer.width));
198 endY = std::min(endY, static_cast<i64>(layer.height));
199 }
200 if (startX >= endX || startY >= endY) return;
201 for (i64 ty = startY; ty < endY; ++ty) {
202 for (i64 tx = startX; tx < endX; ++tx) {
203 writeTile(layer, static_cast<i32>(tx), static_cast<i32>(ty), tileId);
204 }
205 }
206}
207
208void TilemapSystem::setTiles(Entity entity, const u16* tiles, u32 count) {
209 auto it = layers_.find(entity);
210 if (it == layers_.end()) return;
211 auto& layer = it->second;
212 buildChunksFromFlat(layer, tiles, layer.width, layer.height, count);
213}
214
216 auto it = layers_.find(entity);
217 if (it == layers_.end()) return nullptr;
218 return &it->second;
219}
220
221void TilemapSystem::setRenderProps(Entity entity, u32 textureHandle, u32 tilesetColumns,
222 f32 uvTileW, f32 uvTileH,
223 i32 sortLayer, f32 depth,
224 f32 parallaxX, f32 parallaxY) {
225 auto* layer = getLayerDataMut(entity);
226 if (!layer) return;
227 layer->texture_handle = textureHandle;
228 layer->tileset_columns = tilesetColumns;
229 layer->uv_tile_width = uvTileW;
230 layer->uv_tile_height = uvTileH;
231 layer->sort_layer = sortLayer;
232 layer->depth = depth;
233 layer->parallax_factor = {parallaxX, parallaxY};
234}
235
236void TilemapSystem::setTilesets(Entity entity, std::vector<TilesetSlot> slots) {
237 auto* layer = getLayerDataMut(entity);
238 if (!layer) return;
239 std::sort(slots.begin(), slots.end(),
240 [](const TilesetSlot& a, const TilesetSlot& b) { return a.first_id < b.first_id; });
241 layer->tilesets = std::move(slots);
242}
243
244void TilemapSystem::setTint(Entity entity, f32 r, f32 g, f32 b, f32 a, f32 opacity) {
245 auto* layer = getLayerDataMut(entity);
246 if (!layer) return;
247 layer->tint = {r, g, b, a};
248 layer->opacity = opacity;
249}
250
251void TilemapSystem::setVisible(Entity entity, bool visible) {
252 auto* layer = getLayerDataMut(entity);
253 if (!layer) return;
254 layer->visible = visible;
255}
256
257void TilemapSystem::setOriginEntity(Entity layerKey, Entity originEntity) {
258 auto* layer = getLayerDataMut(layerKey);
259 if (!layer) return;
260 layer->origin_entity = originEntity;
261}
262
264 const AnimFrame* frames, u32 frameCount) {
265 auto* layer = getLayerDataMut(entity);
266 if (!layer || frameCount == 0) return;
267
268 TileAnimation anim;
269 anim.frames.assign(frames, frames + frameCount);
270 anim.total_duration_ms = 0;
271 for (u32 i = 0; i < frameCount; i++) {
272 anim.total_duration_ms += frames[i].duration_ms;
273 }
274 if (anim.total_duration_ms == 0) return;
275 layer->tile_animations[tileId] = std::move(anim);
276 layer->anim_table_revision++; // the table changed — every chunk re-evaluates once
277}
278
280 auto* layer = getLayerDataMut(entity);
281 if (!layer || layer->tile_animations.empty()) return;
282 // A tileset swap re-adds only the new set's animations; without this, stale
283 // ids from the old tileset keep animating (setTileAnimation only inserts).
284 layer->tile_animations.clear();
285 layer->anim_table_revision++;
286}
287
288namespace {
290u32 frameIndexAt(const TileAnimation& anim, f64 elapsedMs) {
291 u32 t = static_cast<u32>(std::fmod(elapsedMs, static_cast<f64>(anim.total_duration_ms)));
292 u32 acc = 0;
293 for (u32 i = 0; i < anim.frames.size(); ++i) {
294 acc += anim.frames[i].duration_ms;
295 if (t < acc) return i;
296 }
297 return static_cast<u32>(anim.frames.size()) - 1;
298}
299} // namespace
300
302 auto* layer = getLayerDataMut(entity);
303 if (!layer || layer->tile_animations.empty()) return;
304 const f64 prev = layer->elapsed_ms;
305 layer->elapsed_ms += static_cast<f64>(dtMs);
306 // Bump the revision only when some animation's visible frame actually
307 // flipped — the renderer rebuilds animated chunks on this stamp instead of
308 // every frame, so slow animations cost re-meshing only at their frame rate.
309 for (const auto& [id, anim] : layer->tile_animations) {
310 if (frameIndexAt(anim, prev) != frameIndexAt(anim, layer->elapsed_ms)) {
311 layer->anim_revision++;
312 return;
313 }
314 }
315}
316
318 const auto* layer = getLayerData(entity);
319 if (!layer) return tileId;
320
321 auto it = layer->tile_animations.find(tileId);
322 if (it == layer->tile_animations.end()) return tileId;
323
324 const auto& anim = it->second;
325 return anim.frames[frameIndexAt(anim, layer->elapsed_ms)].tile_id;
326}
327
329 const std::string& key, const std::string& value) {
330 auto* layer = getLayerDataMut(entity);
331 if (!layer) return;
332 layer->tile_properties[tileId][key] = value;
333}
334
335std::string TilemapSystem::getTileProperty(Entity entity, u16 tileId,
336 const std::string& key) const {
337 const auto* layer = getLayerData(entity);
338 if (!layer) return {};
339
340 auto tileIt = layer->tile_properties.find(tileId);
341 if (tileIt == layer->tile_properties.end()) return {};
342
343 auto propIt = tileIt->second.find(key);
344 if (propIt == tileIt->second.end()) return {};
345
346 return propIt->second;
347}
348
350 bool flipH, bool flipV, bool flipD) {
351 auto* layer = getLayerDataMut(entity);
352 if (!layer || !inBounds(*layer, x, y)) return;
353 u16 id = readTile(*layer, x, y) & TILE_ID_MASK;
354 if (id == EMPTY_TILE) return;
355
356 u16 flags = 0;
357 if (flipH) flags |= TILE_FLIP_H;
358 if (flipV) flags |= TILE_FLIP_V;
359 if (flipD) flags |= TILE_FLIP_D;
360 writeTile(*layer, x, y, id | flags);
361}
362
363void TilemapSystem::rotateTile(Entity entity, i32 x, i32 y, i32 degrees) {
364 auto* layer = getLayerDataMut(entity);
365 if (!layer || !inBounds(*layer, x, y)) return;
366 u16 id = readTile(*layer, x, y) & TILE_ID_MASK;
367 if (id == EMPTY_TILE) return;
368
369 i32 rot = ((degrees % 360) + 360) % 360;
370 u16 flags = 0;
371 switch (rot) {
372 case 90: flags = TILE_FLIP_H | TILE_FLIP_D; break;
373 case 180: flags = TILE_FLIP_H | TILE_FLIP_V; break;
374 case 270: flags = TILE_FLIP_V | TILE_FLIP_D; break;
375 default: break;
376 }
377 writeTile(*layer, x, y, id | flags);
378}
379
381 auto* layer = getLayerDataMut(entity);
382 if (!layer) return;
383 layer->grid_type = type;
384}
385
386void TilemapSystem::setHexParams(Entity entity, f32 sideLength, bool staggerAxisX, bool staggerIndexEven) {
387 auto* layer = getLayerDataMut(entity);
388 if (!layer) return;
389 layer->hex_side_length = sideLength;
390 layer->hex_stagger_axis_x = staggerAxisX;
391 layer->hex_stagger_index_even = staggerIndexEven;
392}
393
395 f32 originX, f32 originY,
396 f32& outX, f32& outY) const {
397 const auto* layer = getLayerData(entity);
398 if (!layer) { outX = 0; outY = 0; return; }
399
400 const auto anchor = layer->grid().anchor(tx, ty);
401 outX = originX + anchor.x;
402 outY = originY + anchor.y;
403}
404
406 f32 originX, f32 originY,
407 i32& outTx, i32& outTy) const {
408 const auto* layer = getLayerData(entity);
409 if (!layer) { outTx = 0; outTy = 0; return; }
410
411 const auto cell = layer->grid().cellAt(wx - originX, wy - originY);
412 outTx = cell.x;
413 outTy = cell.y;
414}
415
416} // namespace esengine::tilemap
void setOriginEntity(Entity layerKey, Entity originEntity)
void rotateTile(Entity entity, i32 x, i32 y, i32 degrees)
void setChunkTiles(Entity entity, i32 chunkX, i32 chunkY, const u16 *tiles, u32 width, u32 height)
void setTiles(Entity entity, const u16 *tiles, u32 count)
void setVisible(Entity entity, bool visible)
void setHexParams(Entity entity, f32 sideLength, bool staggerAxisX, bool staggerIndexEven)
void setTileProperty(Entity entity, u16 tileId, const std::string &key, const std::string &value)
void removeChunk(Entity entity, i32 chunkX, i32 chunkY)
void setTileAnimation(Entity entity, u16 tileId, const AnimFrame *frames, u32 frameCount)
bool hasLayer(Entity entity) const
void setTile(Entity entity, i32 x, i32 y, u16 tileId)
void setTilesets(Entity entity, std::vector< TilesetSlot > slots)
void worldToTile(Entity entity, f32 wx, f32 wy, f32 originX, f32 originY, i32 &outTx, i32 &outTy) const
void clearTileAnimations(Entity entity)
void initLayer(Entity entity, u32 width, u32 height, f32 tileWidth, f32 tileHeight)
u16 getTile(Entity entity, i32 x, i32 y) const
void advanceAnimations(Entity entity, f32 dtMs)
void fillRect(Entity entity, i32 x, i32 y, u32 w, u32 h, u16 tileId)
void flipTile(Entity entity, i32 x, i32 y, bool flipH, bool flipV, bool flipD)
void setRenderProps(Entity entity, u32 textureHandle, u32 tilesetColumns, f32 uvTileW, f32 uvTileH, i32 sortLayer, f32 depth, f32 parallaxX, f32 parallaxY)
const LayerData * getLayerData(Entity entity) const
void tileToWorld(Entity entity, i32 tx, i32 ty, f32 originX, f32 originY, f32 &outX, f32 &outY) const
u16 resolveAnimatedTile(Entity entity, u16 tileId) const
std::string getTileProperty(Entity entity, u16 tileId, const std::string &key) const
void setGridType(Entity entity, GridType type)
void setTint(Entity entity, f32 r, f32 g, f32 b, f32 a, f32 opacity)
LayerData * getLayerDataMut(Entity entity)
void initInfiniteLayer(Entity entity, f32 tileWidth, f32 tileHeight)
static constexpr u32 CHUNK_SIZE
TileRange computeVisibleRange(f32 camLeft, f32 camBottom, f32 camRight, f32 camTop, f32 originX, f32 originY, f32 tileWidth, f32 tileHeight, u32 mapWidth, u32 mapHeight)
static constexpr u16 TILE_FLIP_D
static constexpr u16 TILE_FLIP_H
static constexpr u16 EMPTY_TILE
static constexpr u16 TILE_FLIP_V
static constexpr u16 TILE_ID_MASK
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::int64_t i64
Signed 64-bit integer.
Definition Types.hpp:56
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
double f64
64-bit floating point
Definition Types.hpp:61
float f32
32-bit floating point
Definition Types.hpp:59
Entity identifier with packed index + generation.
Definition Types.hpp:135
u16 tiles[CHUNK_SIZE *CHUNK_SIZE]
std::vector< AnimFrame > frames