|
| 1 | +#pragma once |
| 2 | +#include <djson/string_table.hpp> |
| 3 | +#include <klib/assert.hpp> |
| 4 | +#include <le2d/asset/asset_loader.hpp> |
| 5 | +#include <concepts> |
| 6 | + |
| 7 | +namespace miracle { |
| 8 | +class Resources { |
| 9 | + public: |
| 10 | + explicit Resources(le::AssetLoader asset_loader); |
| 11 | + |
| 12 | + template <std::derived_from<le::IAsset> AssetTypeT> |
| 13 | + [[nodiscard]] auto insert(std::string uri, std::unique_ptr<AssetTypeT> asset) -> AssetTypeT& { |
| 14 | + KLIB_ASSERT(asset); |
| 15 | + auto& ret = *asset; |
| 16 | + m_map.insert_or_assign(std::move(uri), Entry::create(std::move(asset))); |
| 17 | + return ret; |
| 18 | + } |
| 19 | + |
| 20 | + void erase(std::string_view uri); |
| 21 | + |
| 22 | + [[nodiscard]] auto contains(std::string_view const uri) const -> bool { return m_map.contains(uri); } |
| 23 | + |
| 24 | + template <std::derived_from<le::IAsset> AssetTypeT> |
| 25 | + [[nodiscard]] auto peek(std::string_view const uri) const -> AssetTypeT* { |
| 26 | + auto const it = m_map.find(uri); |
| 27 | + if (it == m_map.end() || it->second.type != typeid(AssetTypeT)) { return nullptr; } |
| 28 | + return static_cast<AssetTypeT*>(it->second.asset.get()); |
| 29 | + } |
| 30 | + |
| 31 | + template <std::derived_from<le::IAsset> AssetTypeT> |
| 32 | + [[nodiscard]] auto at(std::string_view const uri) const -> AssetTypeT& { |
| 33 | + auto* ret = peek<AssetTypeT>(uri); |
| 34 | + KLIB_ASSERT(ret); |
| 35 | + return *ret; |
| 36 | + } |
| 37 | + |
| 38 | + template <std::derived_from<le::IAsset> AssetTypeT> |
| 39 | + [[nodiscard]] auto load(std::string_view const uri) -> AssetTypeT* { |
| 40 | + if (auto* ret = peek<AssetTypeT>(uri); ret) { return ret; } |
| 41 | + std::unique_ptr<AssetTypeT> asset = m_asset_loader.load<AssetTypeT>(uri); |
| 42 | + if (!asset) { return nullptr; } |
| 43 | + return &insert(std::string{uri}, std::move(asset)); |
| 44 | + } |
| 45 | + |
| 46 | + void clear() { m_map.clear(); } |
| 47 | + |
| 48 | + [[nodiscard]] auto size() const -> std::size_t { return m_map.size(); } |
| 49 | + [[nodiscard]] auto is_empty() const -> bool { return m_map.empty(); } |
| 50 | + |
| 51 | + private: |
| 52 | + struct Entry { |
| 53 | + template <typename T> |
| 54 | + [[nodiscard]] static auto create(std::unique_ptr<T> asset) -> Entry { |
| 55 | + return Entry{.type = typeid(T), .asset = std::move(asset)}; |
| 56 | + } |
| 57 | + |
| 58 | + std::type_index type; |
| 59 | + std::unique_ptr<le::IAsset> asset{}; |
| 60 | + }; |
| 61 | + |
| 62 | + [[nodiscard]] auto find(std::string_view uri, std::type_index type) const -> le::IAsset*; |
| 63 | + |
| 64 | + le::AssetLoader m_asset_loader; |
| 65 | + dj::StringTable<Entry> m_map{}; |
| 66 | +}; |
| 67 | +} // namespace miracle |
0 commit comments