Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
TilemapRenderPlugin.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
5
12
13#include <cmath>
14
15namespace esengine {
16
18 batch_shader_id_ = ctx.batch_shader_id;
19}
20
21void TilemapRenderPlugin::rebuildChunk(
23 const tilemap::ChunkData& chunk, tilemap::ChunkCoord coord,
24 const std::vector<tilemap::TilesetSlot>& slots,
25 const std::vector<ResolvedSlot>& resolved,
26 Entity entity, ChunkCache& cache
27) {
28 cache.slots.resize(slots.size());
29 for (auto& mesh : cache.slots) { mesh.vertices.clear(); mesh.indices.clear(); }
30 cache.has_animated_tiles = false;
31
32 i32 baseX = coord.x * static_cast<i32>(tilemap::CHUNK_SIZE);
33 i32 baseY = coord.y * static_cast<i32>(tilemap::CHUNK_SIZE);
34
35 bool hasAnimations = !layer.tile_animations.empty();
36 f32 hw = layer.tile_width * 0.5f;
37 f32 hh = layer.tile_height * 0.5f;
38 const auto grid = layer.grid();
39
40 for (u32 ly = 0; ly < tilemap::CHUNK_SIZE; ++ly) {
41 i32 ty = baseY + static_cast<i32>(ly);
42 if (!layer.infinite && static_cast<u32>(ty) >= layer.height) break;
43
44 for (u32 lx = 0; lx < tilemap::CHUNK_SIZE; ++lx) {
45 i32 tx = baseX + static_cast<i32>(lx);
46 if (!layer.infinite && static_cast<u32>(tx) >= layer.width) break;
47
48 u16 rawTile = chunk.tiles[ly * tilemap::CHUNK_SIZE + lx];
49 u16 tileId = rawTile & tilemap::TILE_ID_MASK;
50 if (tileId == tilemap::EMPTY_TILE) continue;
51
52 if (hasAnimations &&
53 layer.tile_animations.find(tileId) != layer.tile_animations.end()) {
54 cache.has_animated_tiles = true;
55 tileId = tilemap_system_->resolveAnimatedTile(entity, tileId);
56 }
57
58 // Resolve which tileset (slot) this tile belongs to, then its local
59 // index within that tileset. A tile whose tileset texture is missing
60 // is skipped.
61 int slotIndex = tilemap::resolveTilesetSlot(slots, tileId);
62 if (slotIndex < 0 || !resolved[slotIndex].valid) continue;
63 const ResolvedSlot& rs = resolved[slotIndex];
64 u32 tilesetColumns = slots[slotIndex].columns;
65 if (tilesetColumns == 0) continue;
66 f32 uvTileW = rs.uvW;
67 f32 uvTileH = rs.uvH;
68
69 bool flipH = (rawTile & tilemap::TILE_FLIP_H) != 0;
70 bool flipV = (rawTile & tilemap::TILE_FLIP_V) != 0;
71 bool flipD = (rawTile & tilemap::TILE_FLIP_D) != 0;
72
73 u32 tileIndex = tileId - slots[slotIndex].first_id;
74 u32 tileCol = tileIndex % tilesetColumns;
75 u32 tileRow = tileIndex / tilesetColumns;
76 // A cell the atlas does not hold — an id past the tileset, or a
77 // column count wider than the texture. Its UV rect falls outside,
78 // where the sampler hands back a tile that does exist.
79 if (tileCol >= rs.atlasCols || tileRow >= rs.atlasRows) continue;
80
81 const auto center = grid.center(tx, ty);
82 const f32 worldX = center.x, worldY = center.y;
83
84 // Base tile UV rect (GL v increases upward, so vBottom < vTop), with
85 // the atlas margin + spacing folded into offset/step so a Tiled tileset
86 // with gaps samples the right cell. `inset` is zero on an extruded
87 // atlas and half a texel on a packed one — see where it is resolved.
88 f32 uMin = rs.uvOffsetX + static_cast<f32>(tileCol) * rs.uvStepX + rs.insetU;
89 f32 uMax = uMin + uvTileW - 2.0f * rs.insetU;
90 f32 vBottom = 1.0f - rs.uvOffsetY - static_cast<f32>(tileRow) * rs.uvStepY - uvTileH + rs.insetV;
91 f32 vTop = vBottom + uvTileH - 2.0f * rs.insetV;
92
93 // Map a corner's normalized (s,t) in {0,1}^2 to its texture UV, applying
94 // the tile flip flags. Tiled order — diagonal (transpose) first, then H,
95 // then V — so the standard 90°/270° combos (H|D, V|D) come out as true
96 // rotations. H/V-only reduce to the previous behavior exactly.
97 auto cornerUV = [&](f32 s, f32 t) -> glm::vec2 {
98 tilemap::applyTileFlip(s, t, flipH, flipV, flipD);
99 return glm::vec2{ uMin + s * (uMax - uMin), vBottom + t * (vTop - vBottom) };
100 };
101
102 glm::vec2 bl = cornerUV(0.0f, 0.0f);
103 glm::vec2 br = cornerUV(1.0f, 0.0f);
104 glm::vec2 tr = cornerUV(1.0f, 1.0f);
105 glm::vec2 tl = cornerUV(0.0f, 1.0f);
106
107 SlotMesh& mesh = cache.slots[slotIndex];
108 u32 baseVertex = static_cast<u32>(mesh.vertices.size());
109 mesh.vertices.push_back({ {worldX - hw, worldY - hh, 0.0f}, 0, {bl.x, bl.y} });
110 mesh.vertices.push_back({ {worldX + hw, worldY - hh, 0.0f}, 0, {br.x, br.y} });
111 mesh.vertices.push_back({ {worldX + hw, worldY + hh, 0.0f}, 0, {tr.x, tr.y} });
112 mesh.vertices.push_back({ {worldX - hw, worldY + hh, 0.0f}, 0, {tl.x, tl.y} });
113
114 for (u32 i = 0; i < 6; ++i) {
115 mesh.indices.push_back(baseVertex + BATCH_QUAD_INDICES[i]);
116 }
117 }
118 }
119}
120
121TilemapRenderPlugin::ChunkCache& TilemapRenderPlugin::ensureChunk(
123 const std::vector<tilemap::TilesetSlot>& slots, const std::vector<ResolvedSlot>& resolved, Entity entity, ChunkMap& chunkCaches
124) {
125 auto& cache = chunkCaches[coord];
126 if (chunkData.revision != cache.built_revision
127 || layer.anim_table_revision != cache.built_anim_table_revision
128 || (cache.has_animated_tiles && layer.anim_revision != cache.built_anim_revision)
129 || cache.slots.size() != slots.size()) {
130 rebuildChunk(layer, chunkData, coord, slots, resolved, entity, cache);
131 cache.built_revision = chunkData.revision;
132 cache.built_anim_revision = layer.anim_revision;
133 cache.built_anim_table_revision = layer.anim_table_revision;
134 cache.mesh_serial = ++mesh_serial_;
135 }
136 return cache;
137}
138
139void TilemapRenderPlugin::releaseStrip(GfxDevice& device, Strip& strip) {
140 // Deleted whatever device generation they were made on: a device that was lost keeps its buffers' records (it rebuilds them with their
141 // contents gone), so the handles still name them, and leaving them would grow the device's table by a strip's buffers every recovery.
142 for (StripSlot& slot : strip.slots) {
143 const u64 bytes = static_cast<u64>(slot.vboBytes) + slot.iboBytes;
144 strip_bytes_ = strip_bytes_ >= bytes ? strip_bytes_ - bytes : 0;
145 if (slot.vbo != BufferHandle::Invalid) device.deleteBuffer(slot.vbo);
146 if (slot.ibo != BufferHandle::Invalid) device.deleteBuffer(slot.ibo);
147 slot = StripSlot{};
148 }
149 for (Strip& piece : strip.pieces) releaseStrip(device, piece);
150 strip.pieces.clear();
151 strip.built = false;
152}
153
154void TilemapRenderPlugin::releaseLayer(LayerCache& layer) {
155 if (device_) {
156 for (auto& [key, strip] : layer.strips) releaseStrip(*device_, strip);
157 }
158 layer.strips.clear();
159}
160
161void TilemapRenderPlugin::evictStrips(GfxDevice& device) {
162 if (strip_bytes_ <= STRIP_BYTES_BUDGET) return;
163 // Not drawn by the last two collects: a frame with several cameras collects once for each, and what an earlier one queued has not drawn yet.
164 for (auto& [entity, layer] : layer_caches_) {
165 for (auto it = layer.strips.begin(); it != layer.strips.end() && strip_bytes_ > STRIP_BYTES_BUDGET;) {
166 if (it->second.lastUsed + 2 <= collect_serial_) {
167 releaseStrip(device, it->second);
168 it = layer.strips.erase(it);
169 } else {
170 ++it;
171 }
172 }
173 }
174}
175
177 for (auto& [entity, layer] : layer_caches_) releaseLayer(layer);
178 layer_caches_.clear();
179}
180
182 auto& registry = collect_ctx.registry;
183 auto& clips = collect_ctx.clip_state;
184 auto& buffers = collect_ctx.buffer_pool;
185 auto& draw_list = collect_ctx.draw_list;
186 auto& ctx = collect_ctx.frame_context;
187 if (!tilemap_system_) return;
188 const ecs::GroupOpacityLookup groupOpacity(registry);
189
190 const auto& layers = tilemap_system_->allLayers();
191 if (layers.empty()) return;
192
193 const CameraView& cam = collect_ctx.camera;
194 ++collect_serial_;
195
196 for (const auto& [entity, layer] : layers) {
197 auto cachedLayer = layer_caches_.find(entity);
198 if (cachedLayer != layer_caches_.end() && cachedLayer->second.generation != layer.generation) {
199 releaseLayer(cachedLayer->second);
200 layer_caches_.erase(cachedLayer);
201 cachedLayer = layer_caches_.end();
202 }
203 if (registry.valid(entity) && !registry.isEntityActive(entity)) continue;
204 // The TilemapLayer component is the single source of a layer's visual
205 // metadata — the renderer reads it live each frame (so animated
206 // tint/opacity need no sync). Every scene-driven layer has one (Tiled
207 // imports project REAL child entities); only a code-driven TilemapAPI
208 // layer without a component entity still reads LayerData metadata.
209 const ecs::TilemapLayer* comp = registry.tryGet<ecs::TilemapLayer>(entity);
210
211 bool visible;
212 i32 sortLayer;
213 f32 depth;
214 glm::vec4 tint;
215 f32 opacity;
216 glm::vec2 parallax;
217 resource::TextureHandle singleTileset; // single-tileset fallback source
218 u32 singleColumns;
219 // Lit by the scene's 2D lights. A layer drawn from a LayerData alone has no component to say so, and is not.
220 bool lit = false;
221 // Where this layer's grid starts. A layer whose tiles are drawn from a
222 // LayerData has no component to author it on, so it starts at the origin.
223 glm::vec2 originOffset{0.0f, 0.0f};
224 if (comp) {
225 visible = comp->visible;
226 sortLayer = comp->renderLayer;
227 depth = 0.0f;
228 tint = comp->tintColor;
229 opacity = comp->opacity;
230 parallax = comp->parallaxFactor;
231 singleTileset = comp->tileset;
232 singleColumns = static_cast<u32>(comp->tilesetColumns);
233 originOffset = comp->originOffset;
234 lit = comp->lit;
235 } else {
236 visible = layer.visible;
237 sortLayer = layer.sort_layer;
238 depth = layer.depth;
239 tint = layer.tint;
240 opacity = layer.opacity;
241 parallax = layer.parallax_factor;
242 singleTileset = resource::TextureHandle(layer.texture_handle);
243 singleColumns = layer.tileset_columns;
244 }
245
246 if (registry.valid(entity)) opacity *= groupOpacity.of(entity);
247 if (!visible) continue;
248
249 // The layer's tileset slot list: the multi-tileset table when present
250 // (Tiled imports), else a single slot from the painted/synthetic tileset.
251 const std::vector<tilemap::TilesetSlot>* slotsPtr;
252 if (!layer.tilesets.empty()) {
253 slotsPtr = &layer.tilesets;
254 } else {
255 if (!singleTileset.isValid() || singleColumns == 0) continue;
256 single_slot_scratch_.clear();
257 single_slot_scratch_.push_back(tilemap::TilesetSlot{ 1, singleTileset.id(), singleColumns });
258 slotsPtr = &single_slot_scratch_;
259 }
260 const std::vector<tilemap::TilesetSlot>& slots = *slotsPtr;
261
262 // Resolve each slot's texture + UV scale (tile size / texture size). Kept
263 // parallel to `slots`; a slot whose texture is missing renders nothing.
264 resolved_scratch_.assign(slots.size(), ResolvedSlot{});
265 std::vector<ResolvedSlot>& resolved = resolved_scratch_;
266 bool anySlotValid = false;
267 for (usize i = 0; i < slots.size(); ++i) {
268 auto* tex = ctx.resources.getTexture(resource::TextureHandle(slots[i].texture_handle));
269 if (!tex) continue;
270 f32 tw = static_cast<f32>(tex->getWidth());
271 f32 th = static_cast<f32>(tex->getHeight());
272 if (tw <= 0.0f || th <= 0.0f) continue;
273 resolved[i].valid = true;
274 resolved[i].glTexId = tex->getId();
275 resolved[i].uvW = layer.tile_width / tw;
276 resolved[i].uvH = layer.tile_height / th;
277 f32 margin = static_cast<f32>(slots[i].margin);
278 f32 spacing = static_cast<f32>(slots[i].spacing);
279 resolved[i].uvOffsetX = margin / tw;
280 resolved[i].uvOffsetY = margin / th;
281 resolved[i].uvStepX = (layer.tile_width + spacing) / tw;
282 resolved[i].uvStepY = (layer.tile_height + spacing) / th;
283 // An extruded atlas guarantees a stray sample reads the cell's own
284 // edge, so the exact rect is safe — and it is the only rect that does
285 // not stretch the tile. A packed atlas must still inset.
286 const bool extruded = slots[i].extrude > 0;
287 resolved[i].insetU = extruded ? 0.0f : 0.5f / tw;
288 resolved[i].insetV = extruded ? 0.0f : 0.5f / th;
289 resolved[i].atlasCols = tilemap::atlasCells(tw, margin, layer.tile_width, spacing);
290 resolved[i].atlasRows = tilemap::atlasCells(th, margin, layer.tile_height, spacing);
291 anySlotValid = true;
292 }
293 if (!anySlotValid) continue;
294
295 // The same program a lit sprite draws with. Its vertices carry no layer and no reach of their own (the lane is zero), so
296 // every light's layer range takes the tiles in and which lights are worked out is the screen tile's say (LightStore::markLoopLights):
297 // a strip stays on the GPU as it is while the lights move over it.
298 u32 layerShader = batch_shader_id_;
299 if (lit && ctx.frame) {
300 if (const u32 litProgram = ctx.frame->batchProgram(BatchVariant::Lit)) layerShader = litProgram;
301 }
302
303 f32 originX = 0, originY = 0, angle = 0;
304 Entity transformEntity = (layer.origin_entity != INVALID_ENTITY)
305 ? layer.origin_entity : entity;
306 if (auto* transform = registry.tryGet<ecs::Transform>(transformEntity)) {
307 transform->ensureDecomposed(); // lazily derived; see Transform.hpp
308 originX = rebased(transform->worldPosition).x;
309 originY = rebased(transform->worldPosition).y;
310 const auto& q = transform->worldRotation;
311 angle = std::atan2(2.0f * (q.w * q.z + q.x * q.y),
312 1.0f - 2.0f * (q.y * q.y + q.z * q.z));
313 }
314 const f32 cosAngle = std::cos(angle), sinAngle = std::sin(angle);
315
316 glm::vec4 finalColor(tint.r, tint.g, tint.b, tint.a * opacity);
317 u32 packedColor = packColor(finalColor);
318
319 f32 parallaxOffsetX = cam.parallaxCenter.x * (1.0f - parallax.x);
320 f32 parallaxOffsetY = cam.parallaxCenter.y * (1.0f - parallax.y);
321 // The layer's own offset rides here rather than in the chunk vertices:
322 // those are cached, and this is read every frame, so moving the grid is
323 // live in the editor and costs no rebuild.
324 f32 adjOriginX = originX + parallaxOffsetX + originOffset.x;
325 f32 adjOriginY = originY + parallaxOffsetY + originOffset.y;
326
327 // Visible chunk window. A chunk's screen position is only cx*CHUNK*tw /
328 // cy*CHUNK*th for an orthogonal grid; iso couples cx and cy, and
329 // staggered/hex advance by half a tile — so the orthogonal linear formula
330 // dropped on-screen chunks when an iso/hex map was scrolled. Invert the
331 // real tile placement instead: map the camera rect's four corners to tile
332 // coords with the orientation-aware worldToTile, take their bounding box,
333 // and grow it to whole chunks. worldToTile is affine for iso (a rect maps
334 // to a parallelogram, whose corner bbox contains it) and box-approximate
335 // for stagger/hex — a one-tile margin absorbs the half-tile shift and any
336 // tile whose center is off-screen while its body still overlaps.
337 i32 chunkSize = static_cast<i32>(tilemap::CHUNK_SIZE);
338 i32 cornerTx[4], cornerTy[4];
339 const auto cornerToTile = [&](f32 x, f32 y, i32& tx, i32& ty) {
340 if (angle == 0) {
341 tilemap_system_->worldToTile(entity, x, y, adjOriginX, adjOriginY, tx, ty);
342 } else {
343 const f32 dx = x - originX - parallaxOffsetX, dy = y - originY - parallaxOffsetY;
344 tilemap_system_->worldToTile(entity, dx * cosAngle + dy * sinAngle,
345 -dx * sinAngle + dy * cosAngle, originOffset.x, originOffset.y, tx, ty);
346 }
347 };
348 cornerToTile(cam.left, cam.top, cornerTx[0], cornerTy[0]);
349 cornerToTile(cam.right, cam.top, cornerTx[1], cornerTy[1]);
350 cornerToTile(cam.left, cam.bottom, cornerTx[2], cornerTy[2]);
351 cornerToTile(cam.right, cam.bottom, cornerTx[3], cornerTy[3]);
352 i32 minTx = cornerTx[0], maxTx = cornerTx[0];
353 i32 minTy = cornerTy[0], maxTy = cornerTy[0];
354 for (int i = 1; i < 4; ++i) {
355 minTx = std::min(minTx, cornerTx[i]); maxTx = std::max(maxTx, cornerTx[i]);
356 minTy = std::min(minTy, cornerTy[i]); maxTy = std::max(maxTy, cornerTy[i]);
357 }
358 minTx -= 1; minTy -= 1; maxTx += 1; maxTy += 1;
359
360 i32 minCX = static_cast<i32>(std::floor(static_cast<f32>(minTx) / static_cast<f32>(chunkSize)));
361 i32 minCY = static_cast<i32>(std::floor(static_cast<f32>(minTy) / static_cast<f32>(chunkSize)));
362 i32 maxCX = static_cast<i32>(std::floor(static_cast<f32>(maxTx) / static_cast<f32>(chunkSize))) + 1;
363 i32 maxCY = static_cast<i32>(std::floor(static_cast<f32>(maxTy) / static_cast<f32>(chunkSize))) + 1;
364
365 if (!layer.infinite) {
366 i32 chunksX = static_cast<i32>((layer.width + tilemap::CHUNK_SIZE - 1) / tilemap::CHUNK_SIZE);
367 i32 chunksY = static_cast<i32>((layer.height + tilemap::CHUNK_SIZE - 1) / tilemap::CHUNK_SIZE);
368 minCX = std::max(minCX, 0);
369 minCY = std::max(minCY, 0);
370 maxCX = std::min(maxCX, chunksX);
371 maxCY = std::min(maxCY, chunksY);
372 }
373
374 if (minCX >= maxCX || minCY >= maxCY) continue;
375
376 auto& layerCache = cachedLayer != layer_caches_.end() ? cachedLayer->second : layer_caches_[entity];
377 layerCache.generation = layer.generation;
378 const LayoutInputs layout{layer.tile_width, layer.tile_height, layer.grid_type,
379 layer.hex_side_length, layer.hex_stagger_axis_x, layer.hex_stagger_index_even};
380 if (layerCache.layout != layout || layerCache.tilesets != slots || layerCache.resolved != resolved) {
381 releaseLayer(layerCache);
382 layerCache.chunks.clear();
383 layerCache.layout = layout;
384 layerCache.tilesets = slots;
385 layerCache.resolved = resolved;
386 }
387 auto& chunkCaches = layerCache.chunks;
388 // A chunk taken out of the layer leaves its mesh here; let those go, or a layer walked over for ever grows by every chunk it held.
389 if (layerCache.chunksErasedSeen != layer.chunks_erased) {
390 for (auto it = chunkCaches.begin(); it != chunkCaches.end();) {
391 it = layer.chunks.find(it->first) == layer.chunks.end() ? chunkCaches.erase(it) : std::next(it);
392 }
393 layerCache.chunksErasedSeen = layer.chunks_erased;
394 }
395
396 // A layer that has not moved draws from strips the GPU holds. A parallax layer places its tiles by where the camera is, which changes
397 // every frame it moves, so it keeps the path that builds the vertices each frame; so does a layer being faded, tinted or carried, until
398 // it has stood still for a while.
399 const Placement place{adjOriginX, adjOriginY, originX, originY, originOffset.x, originOffset.y, angle, depth, packedColor};
400 constexpr u64 SETTLE_COLLECTS = 30;
401 if (layerCache.lastPlacementKnown && !(layerCache.lastPlacement == place)) {
402 if (layerCache.movingUntil <= collect_serial_) releaseLayer(layerCache);
403 layerCache.movingUntil = collect_serial_ + SETTLE_COLLECTS;
404 }
405 layerCache.lastPlacement = place;
406 layerCache.lastPlacementKnown = true;
407 if (parallax.x == 1.0f && parallax.y == 1.0f && layerCache.movingUntil <= collect_serial_ && buffers.device().isDeviceUsable()) {
408 GfxDevice& device = buffers.device();
409 device_ = &device;
410 const u64 generation = device.deviceGeneration();
411 const i32 firstStrip = static_cast<i32>(std::floor(static_cast<f32>(minCX) / static_cast<f32>(STRIP_CHUNKS)));
412 const i32 lastStrip = static_cast<i32>(std::floor(static_cast<f32>(maxCX - 1) / static_cast<f32>(STRIP_CHUNKS)));
413 const VertexLayoutHandle batchLayout = buffers.layoutHandle(LayoutId::Batch);
414
415 visible_strips_scratch_.clear();
416 for (i32 cy = minCY; cy < maxCY; ++cy) {
417 // The chunks a strip is made of, brought up to date: the newest build among them and how many there are say whether the
418 // strip still describes them.
419 const auto measure = [&](i32 cxBegin, i32 width, u64& stamp, u32& chunkCount) {
420 stamp = 0;
421 chunkCount = 0;
422 for (i32 cx = cxBegin; cx < cxBegin + width; ++cx) {
423 const tilemap::ChunkCoord coord{cx, cy};
424 const auto chunkIt = layer.chunks.find(coord);
425 if (chunkIt == layer.chunks.end()) continue;
426 stamp = std::max(stamp, ensureChunk(layer, chunkIt->second, coord, slots, resolved, entity, chunkCaches).mesh_serial);
427 ++chunkCount;
428 }
429 };
430 const auto refresh = [&](Strip& strip, i32 cxBegin, i32 width, u64 stamp, u32 chunkCount) {
431 const bool current = strip.built && strip.stamp == stamp && strip.chunkCount == chunkCount
432 && strip.placement == place && strip.deviceGeneration == generation && strip.slots.size() == slots.size();
433 if (!current) {
434 releaseStrip(device, strip);
435 strip.slots.assign(slots.size(), StripSlot{});
436 for (usize si = 0; si < slots.size(); ++si) {
437 if (!resolved[si].valid) continue;
438 strip_vertices_scratch_.clear();
439 strip_indices_scratch_.clear();
440 // Chunks in ascending x: the order the merged draw laid a row of them out in.
441 for (i32 cx = cxBegin; cx < cxBegin + width; ++cx) {
442 const auto chunkIt = chunkCaches.find(tilemap::ChunkCoord{cx, cy});
443 if (chunkIt == chunkCaches.end() || si >= chunkIt->second.slots.size()) continue;
444 if (layer.chunks.find(tilemap::ChunkCoord{cx, cy}) == layer.chunks.end()) continue;
445 const SlotMesh& mesh = chunkIt->second.slots[si];
446 if (mesh.indices.empty()) continue;
447 const u32 baseVertex = static_cast<u32>(strip_vertices_scratch_.size());
448 for (const BatchVertex& v : mesh.vertices) {
449 const f32 lx = v.position.x + originOffset.x, ly = v.position.y + originOffset.y;
450 strip_vertices_scratch_.push_back({
451 angle == 0
452 ? glm::vec3{v.position.x + adjOriginX, v.position.y + adjOriginY, depth}
453 : glm::vec3{originX + parallaxOffsetX + lx * cosAngle - ly * sinAngle,
454 originY + parallaxOffsetY + lx * sinAngle + ly * cosAngle, depth},
455 packedColor, v.texCoord });
456 }
457 for (u32 idx : mesh.indices) strip_indices_scratch_.push_back(baseVertex + idx);
458 }
459 if (strip_indices_scratch_.empty()) continue;
460 StripSlot& out = strip.slots[si];
461 out.vertexCount = static_cast<u32>(strip_vertices_scratch_.size());
462 out.indexCount = static_cast<u32>(strip_indices_scratch_.size());
463 out.vboBytes = out.vertexCount * static_cast<u32>(sizeof(BatchVertex));
464 out.iboBytes = out.indexCount * static_cast<u32>(sizeof(u32));
465 out.vbo = device.createBuffer({GfxBufferUsage::Vertex, out.vboBytes, /*dynamic=*/false}, GfxContent::transient(),
466 strip_vertices_scratch_.data());
467 out.ibo = device.createBuffer({GfxBufferUsage::Index, out.iboBytes, /*dynamic=*/false}, GfxContent::transient(),
468 strip_indices_scratch_.data());
469 if (out.vbo == BufferHandle::Invalid || out.ibo == BufferHandle::Invalid) {
470 if (out.vbo != BufferHandle::Invalid) device.deleteBuffer(out.vbo);
471 if (out.ibo != BufferHandle::Invalid) device.deleteBuffer(out.ibo);
472 out = StripSlot{};
473 continue;
474 }
475 strip_bytes_ += out.vboBytes + out.iboBytes;
476 }
477 strip.placement = place;
478 strip.stamp = stamp;
479 strip.chunkCount = chunkCount;
480 strip.deviceGeneration = generation;
481 strip.built = true;
482 }
483 visible_strips_scratch_.push_back(&strip);
484 };
485 for (i32 sx = firstStrip; sx <= lastStrip; ++sx) {
486 Strip& strip = layerCache.strips[StripKey{sx, cy}];
487 strip.lastUsed = collect_serial_;
488 const i32 cxBegin = sx * STRIP_CHUNKS;
489 u64 stamp = 0;
490 u32 chunkCount = 0;
491 measure(cxBegin, STRIP_CHUNKS, stamp, chunkCount);
492 const bool held = strip.built || !strip.pieces.empty();
493 if (chunkCount == 0 && !held) continue;
494 if (held && (strip.stamp != stamp || strip.chunkCount != chunkCount)) strip.piecesUntil = collect_serial_ + STRIP_PIECES_COLLECTS;
495 if (strip.piecesUntil > collect_serial_) {
496 if (strip.built) releaseStrip(device, strip);
497 if (strip.pieces.empty()) strip.pieces.resize(STRIP_CHUNKS / STRIP_PIECE_CHUNKS);
498 strip.stamp = stamp;
499 strip.chunkCount = chunkCount;
500 for (usize i = 0; i < strip.pieces.size(); ++i) {
501 Strip& piece = strip.pieces[i];
502 const i32 pieceBegin = cxBegin + static_cast<i32>(i) * STRIP_PIECE_CHUNKS;
503 u64 pieceStamp = 0;
504 u32 pieceChunks = 0;
505 measure(pieceBegin, STRIP_PIECE_CHUNKS, pieceStamp, pieceChunks);
506 if (pieceChunks == 0 && !piece.built) continue;
507 refresh(piece, pieceBegin, STRIP_PIECE_CHUNKS, pieceStamp, pieceChunks);
508 }
509 continue;
510 }
511 if (!strip.pieces.empty()) releaseStrip(device, strip);
512 refresh(strip, cxBegin, STRIP_CHUNKS, stamp, chunkCount);
513 }
514 }
515
516 // Slot by slot, then row by row: the order the merged draws were emitted in, so tiles that overlap overlap the same way.
517 for (usize si = 0; si < slots.size(); ++si) {
518 if (!resolved[si].valid) continue;
519 for (const Strip* strip : visible_strips_scratch_) {
520 if (si >= strip->slots.size() || strip->slots[si].indexCount == 0) continue;
521 const StripSlot& slot = strip->slots[si];
522 BatchDrawKey key{
523 .stage = ctx.current_stage,
524 .layer = sortLayer,
525 .shaderId = layerShader,
526 .blend = BlendMode::Normal,
527 .textureId = resolved[si].glTexId,
528 .depth = depth,
529 .entity = entity,
530 .type = RenderType::Sprite,
531 };
532 key.vertexBuffer = slot.vbo;
533 key.indexBuffer = slot.ibo;
534 key.vertexLayout = batchLayout;
535 if (!batchEntityVisible(draw_list, clips, key.entity, key.layer, key.cullBit)) continue;
536 pushBatchDraw(draw_list, clips, 0, slot.vertexCount, 0, slot.indexCount, key);
537 }
538 }
539 continue;
540 }
541
542 // Per-slot merged geometry for this layer (one draw call per slot/texture).
543 if (slot_vertices_scratch_.size() < slots.size()) {
544 slot_vertices_scratch_.resize(slots.size());
545 slot_indices_scratch_.resize(slots.size());
546 }
547 for (usize si = 0; si < slots.size(); ++si) {
548 slot_vertices_scratch_[si].clear();
549 slot_indices_scratch_[si].clear();
550 }
551 std::vector<std::vector<BatchVertex>>& slotVertices = slot_vertices_scratch_;
552 std::vector<std::vector<u32>>& slotIndices = slot_indices_scratch_;
553
554 for (i32 cy = minCY; cy < maxCY; ++cy) {
555 for (i32 cx = minCX; cx < maxCX; ++cx) {
556 tilemap::ChunkCoord coord{cx, cy};
557 auto chunkIt = layer.chunks.find(coord);
558 if (chunkIt == layer.chunks.end()) continue;
559
560 const auto& chunkData = chunkIt->second;
561 auto& cache = ensureChunk(layer, chunkData, coord, slots, resolved, entity, chunkCaches);
562
563 for (usize si = 0; si < slots.size() && si < cache.slots.size(); ++si) {
564 const SlotMesh& mesh = cache.slots[si];
565 if (mesh.indices.empty()) continue;
566 u32 baseVertex = static_cast<u32>(slotVertices[si].size());
567 for (const BatchVertex& v : mesh.vertices) {
568 const f32 lx = v.position.x + originOffset.x, ly = v.position.y + originOffset.y;
569 slotVertices[si].push_back({
570 angle == 0
571 ? glm::vec3{v.position.x + adjOriginX, v.position.y + adjOriginY, depth}
572 : glm::vec3{originX + parallaxOffsetX + lx * cosAngle - ly * sinAngle,
573 originY + parallaxOffsetY + lx * sinAngle + ly * cosAngle, depth},
574 packedColor, v.texCoord });
575 }
576 for (u32 idx : mesh.indices) {
577 slotIndices[si].push_back(baseVertex + idx);
578 }
579 }
580 }
581 }
582
583 // Emit one batch per tileset slot that produced geometry. Indices are
584 // 0-based within each slot's merged vertices; appendIndexedBatch rebases them.
585 for (usize si = 0; si < slots.size(); ++si) {
586 if (!resolved[si].valid || slotIndices[si].empty()) continue;
587 appendIndexedBatch(buffers, draw_list, clips,
588 slotVertices[si].data(), static_cast<u32>(slotVertices[si].size()),
589 slotIndices[si].data(), static_cast<u32>(slotIndices[si].size()),
591 .stage = ctx.current_stage,
592 .layer = sortLayer,
593 .shaderId = layerShader,
594 .blend = BlendMode::Normal,
595 .textureId = resolved[si].glTexId,
596 // Authored, not measured: a tilemap layer is flat content stacked
597 // by a number the layer carries, so there is no world point to ask
598 // the camera how near it is. It stays a plain sort value.
599 .depth = depth,
600 .entity = entity,
601 .type = RenderType::Sprite,
602 });
603 }
604 }
605
606 for (auto it = layer_caches_.begin(); it != layer_caches_.end(); ) {
607 if (layers.find(it->first) == layers.end()) {
608 releaseLayer(it->second);
609 it = layer_caches_.erase(it);
610 } else {
611 ++it;
612 }
613 }
614 if (device_) evictStrips(*device_);
615}
616
617} // namespace esengine
The single submission face: the ONLY place a DrawCommand is assembled.
Frame resources and the shared scene rendering contract.
Tiled tile-flip → UV transform (single source, dependency-free).
Tilemap layer ECS component (editor-facing metadata).
Unified Transform component with local and world-space data.
static constexpr GfxContent transient()
Abstract graphics device interface.
Definition GfxDevice.hpp:75
BufferHandle createBuffer(const BufferDesc &desc, GfxContent content, const void *initialData)
Creates a buffer with fixed capacity and optional initial contents.
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
u64 deviceGeneration() const
Which generation of the device the live GPU objects belong to.
void collect(RenderCollectContext &ctx) override
void init(RenderFrameContext &ctx) override
The opacity a draw inherits from the GroupOpacity above it.
f32 of(Entity entity) const
1 when no enabled group encloses entity (itself included).
bool isValid() const
Checks if the handle references a valid resource.
Definition Handle.hpp:82
IdType id() const
Gets the packed identifier (index + generation).
Definition Handle.hpp:85
u16 resolveAnimatedTile(Entity entity, u16 tileId) const
Handle< esengine::Texture > TextureHandle
Handle to a texture resource.
Definition Handle.hpp:217
void applyTileFlip(float &s, float &t, bool flipH, bool flipV, bool flipD)
Definition TileFlip.hpp:24
static constexpr u32 CHUNK_SIZE
uint32_t atlasCells(float size, float margin, float tileSize, float spacing)
static constexpr u16 TILE_FLIP_D
static constexpr u16 TILE_FLIP_H
int resolveTilesetSlot(const std::vector< TilesetSlot > &slots, uint16_t id)
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::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
void pushBatchDraw(DrawList &drawList, const ClipState &clips, u32 vertexByteOffset, u32 vertexCount, u32 indexOffset, u32 indexCount, const BatchDrawKey &key)
Atomic primitive: assemble + clip + push one DrawCommand for an index range ALREADY written into (or,...
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
u32 packColor(f32 r, f32 g, f32 b, f32 a)
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
void appendIndexedBatch(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex *verts, u32 vertexCount, const u32 *localIndices, u32 indexCount, const BatchDrawKey &key)
Copies verts into the Batch stream, then pushes one DrawCommand spanning them.
bool batchEntityVisible(const DrawList &drawList, const ClipState &clips, Entity entity, i32 layer, u32 cullBit)
static EstellaContext & ctx()
constexpr u32 BATCH_QUAD_INDICES[6]
Canonical two-triangle quad winding shared by every batch path.
float f32
32-bit floating point
Definition Types.hpp:59
Non-geometry attributes of a batch draw — everything needed to build the sort key + DrawCommand.
VertexLayoutHandle vertexLayout
One vertex of the shared batch stream.
What every plugin needs to know about the camera, derived once per collect from the inverse view-proj...
Entity identifier with packed index + generation.
Definition Types.hpp:135
resource::TextureHandle tileset
bool lit
Lit by the scene's 2D lights (Light), as a Sprite's lit is: flat normal, the layer's tint as the albe...
Unified transform component.
Definition Transform.hpp:45
u16 tiles[CHUNK_SIZE *CHUNK_SIZE]
std::unordered_map< u16, TileAnimation > tile_animations