+ChunkRequester::ChunkRequester(
+ ChunkStore &store,
+ const WorldSave &save
+) noexcept
+: store(store)
+, save(save) {
+
+}
+
+void ChunkRequester::Update(int dt) {
+ // check if there's chunks waiting to be loaded
+ LoadN(10);
+
+ // store a few chunks as well
+ constexpr int max_save = 10;
+ int saved = 0;
+ for (Chunk &chunk : store) {
+ if (chunk.ShouldUpdateSave()) {
+ save.Write(chunk);
+ ++saved;
+ if (saved >= max_save) {
+ break;
+ }
+ }
+ }
+}
+
+int ChunkRequester::ToLoad() const noexcept {
+ return store.EstimateMissing();
+}
+
+void ChunkRequester::LoadOne() {
+ if (!store.HasMissing()) return;
+
+ Chunk::Pos pos = store.NextMissing();
+ Chunk *chunk = store.Allocate(pos);
+ if (!chunk) {
+ // chunk store corrupted?
+ return;
+ }
+
+ if (save.Exists(pos)) {
+ save.Read(*chunk);
+ // TODO: request chunk from server with cache tag
+ } else {
+ // TODO: request chunk from server
+ }
+}
+
+void ChunkRequester::LoadN(std::size_t n) {
+ std::size_t end = std::min(n, std::size_t(ToLoad()));
+ for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
+ LoadOne();
+ }
+}
+
+