-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmanifest_loader.cpp
More file actions
72 lines (63 loc) · 2.13 KB
/
manifest_loader.cpp
File metadata and controls
72 lines (63 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "chomper/manifest/manifest_loader.hpp"
#include <klib/assert.hpp>
#include <le2d/resource/audio_buffer.hpp>
#include <le2d/resource/font.hpp>
#include <le2d/resource/texture.hpp>
namespace chomper {
ManifestLoader::ManifestLoader(le::AssetLoader asset_loader) : m_asset_loader(std::move(asset_loader)) {}
void ManifestLoader::startLoad(AssetManifest const& assetManifest) {
// call startLoads<AssetType>() for each field in the manifest.
startLoads<le::ITexture>(assetManifest.textures);
startLoads<le::IAudioBuffer>(assetManifest.audio);
startLoads<le::IFont>(assetManifest.fonts);
}
auto ManifestLoader::getProgress() const -> Progress {
return Progress{
.remaining = std::int64_t(m_loading.size()),
.loaded = std::int64_t(m_loaded.size()),
};
}
auto ManifestLoader::update() -> Progress {
auto const isReady = [this](std::future<Asset>& future) {
// should only have futures from std::async().
KLIB_ASSERT(future.valid());
if (future.wait_for(0s) == std::future_status::ready) { // if future is ready,
m_loaded.push_back(future.get()); // store loaded asset, and
return true; // erase corresponding future.
}
return false; // else do nothing.
};
std::erase_if(m_loading, isReady);
return getProgress();
}
void ManifestLoader::transferTo(Resources& out) {
// block until all pending loads have been completed.
for (auto& future : m_loading) {
m_loaded.push_back(future.get());
}
m_loading.clear();
// transfer valid loaded assets to out.
auto count = std::int64_t{};
for (auto& asset : m_loaded) {
if (!asset.asset) {
continue;
}
out.store(std::move(asset.uri), std::move(asset.asset));
++count;
}
m_loaded.clear();
m_log.info("{} asset(s) transferred to {}", count, klib::demangled_name(out));
}
template <std::derived_from<le::IAsset> AssetTypeT>
void ManifestLoader::startLoads(std::span<std::string const> uris) {
for (auto const& uri : uris) {
if (uri.empty()) {
continue;
}
auto const loadAsset = [this, uri] {
return Asset{.uri = std::move(uri), .asset = m_asset_loader.load<AssetTypeT>(uri)};
};
m_loading.push_back(std::async(loadAsset));
}
}
} // namespace chomper