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.

7.9 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
#pragma once

#include "../core/Types.hpp"
#include "TilesetTable.hpp"
#include "TileGrid.hpp"

#include <glm/glm.hpp>
#include <string>
#include <unordered_map>
#include <vector>
#include "../core/Reflection.hpp"

namespace esengine {
namespace tilemap {

static constexpr u16 EMPTY_TILE = 0;
ES_CONST()
static constexpr u32 CHUNK_SIZE = 16;

ES_CONST(hex)
static constexpr u16 TILE_ID_MASK = 0x1FFF;
ES_CONST(hex)
static constexpr u16 TILE_FLIP_H  = 0x2000;
ES_CONST(hex)
static constexpr u16 TILE_FLIP_V  = 0x4000;
ES_CONST(hex)
static constexpr u16 TILE_FLIP_D  = 0x8000;

struct AnimFrame {
    u16 tile_id;
    u16 duration_ms;
};

struct TileAnimation {
    std::vector<AnimFrame> frames;
    u32 total_duration_ms = 0;
};

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);

struct ChunkCoord {
    i32 x, y;
    bool operator==(const ChunkCoord& o) const { return x == o.x && y == o.y; }
};

struct ChunkCoordHash {
    size_t operator()(const ChunkCoord& c) const {
        return std::hash<u64>()(static_cast<u64>(static_cast<u32>(c.x))
             | (static_cast<u64>(static_cast<u32>(c.y)) << 32));
    }
};

struct ChunkData {
    u16 tiles[CHUNK_SIZE * CHUNK_SIZE]{};
    // Edit stamp copied from the owning LayerData::edit_revision on each change.
    // The renderer compares this against the revision it last built per chunk and
    // NEVER writes it back — rendering reads a read-only snapshot instead of
    // flipping a content-side `dirty` flag (RC5: abstractions are one-way).
    u32 revision = 0;
};

class TilemapSystem {
public:
    void initLayer(Entity entity, u32 width, u32 height,
                   f32 tileWidth, f32 tileHeight);
    void initInfiniteLayer(Entity entity, f32 tileWidth, f32 tileHeight);
    void setChunkTiles(Entity entity, i32 chunkX, i32 chunkY,
                       const u16* tiles, u32 width, u32 height);
    /// Takes one chunk out of the layer: its tiles are gone and the renderer lets go of what it built for them. A layer that streams a world
    /// in as it is walked needs this, or every chunk it has ever held stays.
    void removeChunk(Entity entity, i32 chunkX, i32 chunkY);
    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);

    void setTileAnimation(Entity entity, u16 tileId,
                          const AnimFrame* frames, u32 frameCount);
    void clearTileAnimations(Entity entity);
    void advanceAnimations(Entity entity, f32 dtMs);
    u16 resolveAnimatedTile(Entity entity, u16 tileId) const;

    void setTileProperty(Entity entity, u16 tileId,
                         const std::string& key, const std::string& value);
    std::string getTileProperty(Entity entity, u16 tileId,
                                const std::string& key) const;

    void flipTile(Entity entity, i32 x, i32 y, bool flipH, bool flipV, bool flipD);
    void rotateTile(Entity entity, i32 x, i32 y, i32 degrees);

    void setGridType(Entity entity, GridType type);

    /// Hexagonal-grid parameters (Tiled's hexsidelength / staggeraxis /
    /// staggerindex); only read when the layer's grid type is Hexagonal.
    void setHexParams(Entity entity, f32 sideLength, bool staggerAxisX, bool staggerIndexEven);

    struct LayerData {
        u32 generation = 0;
        u32 width = 0;   // finite-layer bounds (0 = infinite); tiles live in `chunks`.
        u32 height = 0;
        f32 tile_width = 0;
        f32 tile_height = 0;

        // Single-tileset fields (kept for painted layers / the single-tileset
        // fallback). Multi-tileset layers (e.g. Tiled imports) instead populate
        // `tilesets` below; when it is non-empty the renderer uses it and these
        // are ignored.
        u32 texture_handle = 0;
        u32 tileset_columns = 1;
        f32 uv_tile_width = 0;
        f32 uv_tile_height = 0;

        // Multi-tileset table (sorted by first_id). Empty = single-tileset layer.
        std::vector<TilesetSlot> tilesets;
        i32 sort_layer = 0;
        f32 depth = 0;
        glm::vec4 tint{1.0f, 1.0f, 1.0f, 1.0f};
        f32 opacity = 1.0f;
        glm::vec2 parallax_factor{1.0f, 1.0f};
        bool visible = true;
        Entity origin_entity = INVALID_ENTITY;
        GridType grid_type = GridType::Orthogonal;
        /// Hexagonal layout inputs (see setHexParams). A zero side length falls
        /// back to tile_height/2 (a regular pointy-top hex).
        f32 hex_side_length = 0.0f;
        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;

        // Monotonic counter bumped on every chunk edit; stamped into
        // ChunkData::revision so the renderer detects changes without the content
        // system exposing a mutable dirty flag.
        u32 edit_revision = 0;
        // Bumped when a chunk is taken out, so the renderer knows to drop what it cached for chunks that are gone.
        u32 chunks_erased = 0;

        std::unordered_map<u16, TileAnimation> tile_animations;
        f64 elapsed_ms = 0;  // f64: an f32 accumulator stalls (dt < ULP) after ~day-scale uptime
        // Bumped only when some animation's CURRENT frame flips — ANIMATED chunk
        // meshes rebuild on this, not every frame.
        u32 anim_revision = 0;
        // Bumped when the animation TABLE changes (a tile gains/loses an
        // animation). This forces EVERY chunk to re-evaluate once, so a chunk that
        // was all-static picks up a tile that just became animated — the
        // anim_revision check above is gated on has_animated_tiles and would miss
        // that false→true transition.
        u32 anim_table_revision = 0;

        std::unordered_map<u16, std::unordered_map<std::string, std::string>> tile_properties;
    };

    const LayerData* getLayerData(Entity entity) const;
    LayerData* getLayerDataMut(Entity entity);

    void setRenderProps(Entity entity, u32 textureHandle, u32 tilesetColumns,
                        f32 uvTileW, f32 uvTileH,
                        i32 sortLayer, f32 depth,
                        f32 parallaxX, f32 parallaxY);

    // Replace the layer's multi-tileset table (sorted ascending by first_id).
    // Passing an empty table reverts the layer to the single-tileset fields.
    void setTilesets(Entity entity, std::vector<TilesetSlot> slots);
    void setTint(Entity entity, f32 r, f32 g, f32 b, f32 a, f32 opacity);
    void setVisible(Entity entity, bool visible);
    void setOriginEntity(Entity layerKey, Entity originEntity);

    void tileToWorld(Entity entity, i32 tx, i32 ty,
                     f32 originX, f32 originY, f32& outX, f32& outY) const;
    void worldToTile(Entity entity, f32 wx, f32 wy,
                     f32 originX, f32 originY, i32& outTx, i32& outTy) const;

    using LayerMap = std::unordered_map<Entity, LayerData>;
    const LayerMap& allLayers() const { return layers_; }

private:
    u32 next_generation_ = 0;
    LayerMap layers_;
};

}  // namespace tilemap
}  // namespace esengine