Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
TilemapRenderPlugin.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#pragma once
4
7
9
10#include <unordered_map>
11#include <vector>
12
13namespace esengine {
14
15namespace tilemap { class TilemapSystem; }
16
18public:
19 void init(RenderFrameContext& ctx) override;
20 void shutdown() override;
21
22 void setTilemapSystem(tilemap::TilemapSystem* system) { tilemap_system_ = system; }
23
24 void collect(RenderCollectContext& ctx) override;
25 const char* collectScope() const override { return "render.collect.tilemap"; }
26
27private:
28 // One batch per tileset slot. Vertices stay layer-local and untinted;
29 // rotation, origin, parallax and tint apply at frame merge without cache rebuilds.
30 struct SlotMesh {
31 std::vector<BatchVertex> vertices;
32 std::vector<u32> indices;
33 };
34 struct ChunkCache {
35 std::vector<SlotMesh> slots; // indexed by the layer's render-slot order
36 bool has_animated_tiles = false;
37 // Revision of the content chunk this cache was last built from. Compared
38 // against ChunkData::revision so we rebuild only on real edits — the
39 // renderer reads this snapshot stamp and never writes to content.
40 u32 built_revision = 0;
41 // Animation-frame revision this cache was built at; an animated chunk
42 // rebuilds when a visible frame flips, not every frame.
43 u32 built_anim_revision = 0;
44 // Animation-TABLE revision this cache was built at; every chunk rebuilds
45 // once when the table changes so a static chunk can become animated.
46 u32 built_anim_table_revision = 0;
47 // Which build of this chunk's mesh a strip was made from: a counter the plugin hands out, so a strip is stale exactly when a chunk in it
48 // was rebuilt after it (the newest serial among its chunks is not the one it recorded).
49 u64 mesh_serial = 0;
50 };
51
52 // A layer slot with its texture resolved for the current frame.
53 struct ResolvedSlot {
54 u32 glTexId = 0;
55 f32 uvW = 0.0f;
56 f32 uvH = 0.0f;
57 // Atlas margin (border before the first tile) and per-tile step
58 // (tileSize + spacing), in UV units. For a gapless atlas offset=0 and
59 // step==uvW/uvH; a Tiled tileset with margin/spacing shifts each cell so
60 // it samples its own texels instead of the adjacent tile's.
61 f32 uvOffsetX = 0.0f;
62 f32 uvStepX = 0.0f;
63 f32 uvOffsetY = 0.0f;
64 f32 uvStepY = 0.0f;
65 // How far a tile-corner UV is pulled in from the cell rect. Zero when the
66 // tileset is extruded (the atlas guarantees no crossing, so UV rect ==
67 // geometry rect); half a texel on a packed atlas, which stretches the tile.
68 f32 insetU = 0.0f;
69 f32 insetV = 0.0f;
70 // How many tiles the texture actually holds, at this layer's cell size.
71 // A tile id past them has no texels of its own, and sampling outside the
72 // atlas returns some other tile — so it is skipped instead.
73 u32 atlasCols = 0;
74 u32 atlasRows = 0;
75 bool valid = false;
76 bool operator==(const ResolvedSlot&) const = default;
77 };
78
79 struct LayoutInputs {
80 f32 tileWidth = 0;
81 f32 tileHeight = 0;
83 f32 hexSideLength = 0;
84 bool staggerAxisX = false;
85 bool staggerIndexEven = false;
86 bool operator==(const LayoutInputs&) const = default;
87 };
88
89 using ChunkMap = std::unordered_map<tilemap::ChunkCoord, ChunkCache, tilemap::ChunkCoordHash>;
90
91 // Geometry the GPU keeps between frames. A layer whose grid sits where it did (no parallax, same tint, same place) draws from here, so a frame
92 // in which no chunk changed uploads nothing and copies no vertex. The unit is a STRIP: one row of chunks, thirty-two of them wide, in
93 // world space. A strip rather than a block of chunks because the merged draw this replaces laid tiles out chunk row by chunk row, and
94 // tiles that overlap (a tall tile over its neighbour, an isometric map) are drawn in that order: strips drawn row by row, slot by slot,
95 // reproduce it, and a square block of chunks would not.
96 static constexpr i32 STRIP_CHUNKS = 32;
97 // A strip makes a frame with no change free and a frame with one dear: one tile dug is the whole row uploaded again, over a megabyte
98 // when the row is full. So a strip whose chunks change is cut into pieces this many chunks wide, of which a change uploads one, until
99 // no change has reached it for this many collects. The pieces cost a few more draws, and are drawn in the order the strip's tiles were.
100 static constexpr i32 STRIP_PIECE_CHUNKS = 4;
101 static constexpr u64 STRIP_PIECES_COLLECTS = 1800;
103 static constexpr u64 STRIP_BYTES_BUDGET = 96ull * 1024 * 1024;
104 struct StripKey {
105 i32 sx = 0;
106 i32 cy = 0;
107 bool operator==(const StripKey&) const = default;
108 };
109 struct StripKeyHash {
110 usize operator()(const StripKey& key) const {
111 return std::hash<i64>{}((static_cast<i64>(key.sx) << 32) ^ static_cast<i64>(static_cast<u32>(key.cy)));
112 }
113 };
115 struct Placement {
116 f32 adjX = 0, adjY = 0, originX = 0, originY = 0, offsetX = 0, offsetY = 0, angle = 0, depth = 0;
117 u32 color = 0;
118 bool operator==(const Placement&) const = default;
119 };
120 struct StripSlot {
123 u32 vertexCount = 0;
124 u32 indexCount = 0;
125 u32 vboBytes = 0;
126 u32 iboBytes = 0;
127 };
128 struct Strip {
129 std::vector<StripSlot> slots; // by the layer's render-slot order
130 Placement placement;
131 u64 stamp = 0; // newest mesh serial among the chunks it was built from
132 u32 chunkCount = 0; // how many chunks that was
133 u64 deviceGeneration = 0; // the device its buffers belong to
134 u64 lastUsed = 0; // the collect that last drew it
135 bool built = false;
136 std::vector<Strip> pieces; // while its chunks keep changing: these are drawn, left to right, and it holds no buffers of its own
137 u64 piecesUntil = 0; // the collect it goes back to being one strip
138 };
139
140 struct LayerCache {
141 u32 generation = 0;
142 LayoutInputs layout;
143 std::vector<tilemap::TilesetSlot> tilesets;
144 std::vector<ResolvedSlot> resolved;
145 ChunkMap chunks;
146 std::unordered_map<StripKey, Strip, StripKeyHash> strips;
147 // Where the layer was placed the last time it was collected, and until which collect it counts as MOVING. A layer faded, tinted or carried
148 // along is placed anew every frame, and a strip is made of every chunk in a row of them, many times what is on screen: for such a layer
149 // the vertices are built per frame for the visible chunks, as before, until it has stood still for a while.
150 Placement lastPlacement;
151 bool lastPlacementKnown = false;
152 u64 movingUntil = 0;
154 u32 chunksErasedSeen = 0;
155 };
156 using LayerChunkMap = std::unordered_map<Entity, LayerCache>;
157
158 void rebuildChunk(const tilemap::TilemapSystem::LayerData& layer,
159 const tilemap::ChunkData& chunk, tilemap::ChunkCoord coord,
160 const std::vector<tilemap::TilesetSlot>& slots,
161 const std::vector<ResolvedSlot>& resolved,
162 Entity entity, ChunkCache& cache);
163
165 ChunkCache& ensureChunk(const tilemap::TilemapSystem::LayerData& layer, const tilemap::ChunkData& chunkData,
166 tilemap::ChunkCoord coord, const std::vector<tilemap::TilesetSlot>& slots,
167 const std::vector<ResolvedSlot>& resolved, Entity entity, ChunkMap& chunkCaches);
169 void releaseStrip(GfxDevice& device, Strip& strip);
170 void releaseLayer(LayerCache& layer);
172 void evictStrips(GfxDevice& device);
173
174 tilemap::TilemapSystem* tilemap_system_ = nullptr;
175 u32 batch_shader_id_ = 0;
176 LayerChunkMap layer_caches_;
177 GfxDevice* device_ = nullptr;
178 u64 mesh_serial_ = 0;
179 u64 collect_serial_ = 0;
180 u64 strip_bytes_ = 0;
181 std::vector<BatchVertex> strip_vertices_scratch_;
182 std::vector<u32> strip_indices_scratch_;
183 std::vector<Strip*> visible_strips_scratch_;
184
185 // Per-frame scratch reused across layers/frames so collect allocates nothing
186 // in the steady state.
187 std::vector<tilemap::TilesetSlot> single_slot_scratch_;
188 std::vector<ResolvedSlot> resolved_scratch_;
189 std::vector<std::vector<BatchVertex>> slot_vertices_scratch_;
190 std::vector<std::vector<u32>> slot_indices_scratch_;
191};
192
193} // namespace esengine
void setTilemapSystem(tilemap::TilemapSystem *system)
const char * collectScope() const override
What this plugin's collect is called in a frame profile.
void collect(RenderCollectContext &ctx) override
void init(RenderFrameContext &ctx) override
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
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
static EstellaContext & ctx()
float f32
32-bit floating point
Definition Types.hpp:59