1 #include "BlockLookup.hpp"
3 #include "ChunkIndex.hpp"
4 #include "ChunkLoader.hpp"
5 #include "ChunkRenderer.hpp"
6 #include "ChunkStore.hpp"
8 #include "Generator.hpp"
9 #include "WorldCollision.hpp"
10 #include "../app/Assets.hpp"
11 #include "../geometry/distance.hpp"
12 #include "../graphics/BlockLighting.hpp"
13 #include "../graphics/BlockMesh.hpp"
14 #include "../graphics/Viewport.hpp"
15 #include "../io/WorldSave.hpp"
23 #include <glm/gtx/io.hpp>
28 constexpr int Chunk::side;
29 constexpr int Chunk::size;
32 Chunk::Chunk(const BlockTypeRegistry &types) noexcept
47 Chunk::Chunk(Chunk &&other) noexcept
49 , gravity(std::move(other.gravity))
50 , generated(other.generated)
51 , lighted(other.lighted)
52 , position(other.position)
53 , ref_count(other.ref_count)
54 , dirty_mesh(other.dirty_mesh)
55 , dirty_save(other.dirty_save) {
56 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
57 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
58 std::copy(other.light, other.light + sizeof(light), light);
62 Chunk &Chunk::operator =(Chunk &&other) noexcept {
64 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
65 gravity = std::move(other.gravity);
66 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
67 std::copy(other.light, other.light + sizeof(light), light);
68 generated = other.generated;
69 lighted = other.lighted;
70 position = other.position;
71 std::swap(ref_count, other.ref_count);
72 dirty_mesh = other.dirty_save;
73 dirty_save = other.dirty_save;
83 RoughLocation::Fine pos;
85 SetNode(Chunk *chunk, RoughLocation::Fine pos)
86 : chunk(chunk), pos(pos) { }
88 int Get() const noexcept { return chunk->GetLight(pos); }
89 void Set(int level) noexcept { chunk->SetLight(pos, level); }
91 const BlockType &GetType() const noexcept { return chunk->Type(Chunk::ToIndex(pos)); }
93 int EmitLevel() const noexcept { return GetType().luminosity; }
94 bool EmitsLight() const noexcept { return EmitLevel() > 0; }
96 bool HasNext(Block::Face face) noexcept {
97 const BlockType &type = GetType();
98 if (type.block_light && !type.luminosity) return false;
99 const BlockLookup next(chunk, pos, face);
102 SetNode GetNext(Block::Face face) noexcept {
103 const BlockLookup next(chunk, pos, face);
104 return SetNode(&next.GetChunk(), next.GetBlockPos());
114 UnsetNode(Chunk *chunk, RoughLocation::Fine pos)
115 : SetNode(chunk, pos), level(Get()) { }
117 UnsetNode(const SetNode &set)
118 : SetNode(set), level(Get()) { }
121 bool HasNext(Block::Face face) noexcept {
122 const BlockLookup next(chunk, pos, face);
125 UnsetNode GetNext(Block::Face face) noexcept { return UnsetNode(SetNode::GetNext(face)); }
129 std::queue<SetNode> light_queue;
130 std::queue<UnsetNode> dark_queue;
132 void work_light() noexcept {
133 while (!light_queue.empty()) {
134 SetNode node = light_queue.front();
137 int level = node.Get() - 1;
138 for (int face = 0; face < Block::FACE_COUNT; ++face) {
139 if (node.HasNext(Block::Face(face))) {
140 SetNode other = node.GetNext(Block::Face(face));
141 if (other.Get() < level) {
143 light_queue.emplace(other);
150 void work_dark() noexcept {
151 while (!dark_queue.empty()) {
152 UnsetNode node = dark_queue.front();
155 for (int face = 0; face < Block::FACE_COUNT; ++face) {
156 if (node.HasNext(Block::Face(face))) {
157 UnsetNode other = node.GetNext(Block::Face(face));
158 if (other.Get() != 0 && other.Get() < node.level) {
159 if (other.EmitsLight()) {
160 other.Set(other.EmitLevel());
161 light_queue.emplace(other);
165 dark_queue.emplace(other);
167 light_queue.emplace(other);
176 void Chunk::SetBlock(int index, const Block &block) noexcept {
177 const BlockType &old_type = Type(blocks[index]);
178 const BlockType &new_type = Type(block);
180 blocks[index] = block;
183 if (old_type.gravity && !new_type.gravity) {
184 gravity.erase(index);
185 } else if (new_type.gravity && !old_type.gravity) {
186 gravity.insert(index);
189 if (!lighted || &old_type == &new_type) return;
191 if (new_type.luminosity > old_type.luminosity) {
193 SetLight(index, new_type.luminosity);
194 light_queue.emplace(this, ToPos(index));
196 } else if (new_type.luminosity < old_type.luminosity) {
198 dark_queue.emplace(this, ToPos(index));
201 SetLight(index, new_type.luminosity);
202 light_queue.emplace(this, ToPos(index));
204 } else if (new_type.block_light && !old_type.block_light) {
206 if (GetLight(index) > 0) {
207 dark_queue.emplace(this, ToPos(index));
212 } else if (!new_type.block_light && old_type.block_light) {
215 RoughLocation::Fine pos(ToPos(index));
216 for (int face = 0; face < Block::FACE_COUNT; ++face) {
217 BlockLookup next_block(this, pos, Block::Face(face));
219 level = std::max(level, next_block.GetLight());
223 SetLight(index, level - 1);
224 light_queue.emplace(this, pos);
230 void Chunk::ScanLights() {
232 RoughLocation::Fine pos(0, 0, 0);
233 for (; pos.z < side; ++pos.z) {
234 for (pos.y = 0; pos.y < side; ++pos.y) {
235 for (pos.x = 0; pos.x < side; ++pos.x, ++idx) {
236 const BlockType &type = Type(blocks[idx]);
237 if (type.luminosity) {
238 SetLight(idx, type.luminosity);
239 light_queue.emplace(this, pos);
248 void Chunk::ScanActive() {
250 for (int index = 0; index < size; ++index) {
251 if (Type(index).gravity) {
252 gravity.insert(gravity.end(), index);
257 void Chunk::SetNeighbor(Block::Face face, Chunk &other) noexcept {
258 neighbor[face] = &other;
259 other.neighbor[Block::Opposite(face)] = this;
262 void Chunk::Unlink() noexcept {
263 for (int face = 0; face < Block::FACE_COUNT; ++face) {
264 if (neighbor[face]) {
265 neighbor[face]->neighbor[Block::Opposite(Block::Face(face))] = nullptr;
266 neighbor[face] = nullptr;
272 void Chunk::SetLight(int index, int level) noexcept {
273 if (light[index] != level) {
274 light[index] = level;
279 int Chunk::GetLight(int index) const noexcept {
283 float Chunk::GetVertexLight(const RoughLocation::Fine &pos, const BlockMesh::Position &vtx, const EntityMesh::Normal &norm) const noexcept {
284 int index = ToIndex(pos);
285 float light = GetLight(index);
287 Block::Face direct_face(Block::NormalFace(norm));
289 BlockLookup direct(const_cast<Chunk *>(this), pos, Block::NormalFace(norm));
291 float direct_light = direct.GetLight();
292 if (direct_light > light) {
293 light = direct_light;
299 if (Type(BlockAt(index)).luminosity > 0 || direct.GetType().block_light) {
304 switch (Block::Axis(direct_face)) {
306 edge[0] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
307 edge[1] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
310 edge[0] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
311 edge[1] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
314 edge[0] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
315 edge[1] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
322 BlockLookup next[2] = {
323 direct.Next(edge[0]),
324 direct.Next(edge[1]),
328 if (next[0].GetType().block_light) {
331 light += next[0].GetLight();
336 if (next[1].GetType().block_light) {
339 light += next[1].GetLight();
345 BlockLookup corner = next[0].Next(edge[1]);
347 if (corner.GetType().block_light) {
350 light += corner.GetLight();
354 } else if (next[1]) {
355 BlockLookup corner = next[1].Next(edge[0]);
357 if (corner.GetType().block_light) {
360 light += corner.GetLight();
369 return (light / num) - (occlusion * 0.8f);
373 glm::vec3 Chunk::GravityAt(const ExactLocation &coords) const noexcept {
374 glm::vec3 grav(0.0f);
375 for (int index : gravity) {
376 RoughLocation::Fine block_pos(ToPos(index));
377 ExactLocation block_coords(position, ToCoords(block_pos));
378 // trust that block type hasn't changed
379 grav += Type(index).gravity->GetGravity(
380 coords.Difference(block_coords).Absolute(),
381 ToTransform(block_pos, index));
387 bool Chunk::IsSurface(const RoughLocation::Fine &pos) const noexcept {
388 const Block &block = BlockAt(pos);
389 if (!Type(block).visible) {
392 for (int face = 0; face < Block::FACE_COUNT; ++face) {
393 BlockLookup next = BlockLookup(const_cast<Chunk *>(this), pos, Block::Face(face));
394 if (!next || !next.GetType().visible) {
402 bool Chunk::Intersection(
404 const ExactLocation::Coarse &reference,
410 coll.depth = std::numeric_limits<float>::infinity();
411 for (int z = 0; z < side; ++z) {
412 for (int y = 0; y < side; ++y) {
413 for (int x = 0; x < side; ++x, ++idx) {
414 const BlockType &type = Type(idx);
415 if (!type.collision || !type.shape) {
420 if (type.shape->Intersects(ray, ToTransform(reference, RoughLocation::Fine(x, y, z), idx), cur_dist, cur_norm)) {
421 if (cur_dist < coll.depth) {
423 coll.depth = cur_dist;
424 coll.normal = cur_norm;
431 if (coll.block < 0) {
434 coll.normal = glm::vec3(BlockAt(coll.block).Transform() * glm::vec4(coll.normal, 0.0f));
439 bool Chunk::Intersection(
441 const glm::mat4 &Mbox,
442 const glm::mat4 &Mchunk,
443 std::vector<WorldCollision> &col
449 if (!blank::Intersection(box, Mbox, Bounds(), Mchunk, penetration, normal)) {
453 // box's origin relative to the chunk
454 const glm::vec3 box_coords(Mbox[3] - Mchunk[3]);
455 const float box_rad = box.OriginRadius();
457 // assume a bounding radius of 2 for blocks
458 constexpr float block_rad = 2.0f;
459 const float bb_radius = box_rad + block_rad;
461 const RoughLocation::Fine begin(max(
462 RoughLocation::Fine(0),
463 RoughLocation::Fine(floor(box_coords - bb_radius))
465 const RoughLocation::Fine end(min(
466 RoughLocation::Fine(side - 1),
467 RoughLocation::Fine(ceil(box_coords + bb_radius))
470 for (RoughLocation::Fine pos(begin); pos.z < end.y; ++pos.z) {
471 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
472 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
473 int idx = ToIndex(pos);
474 const BlockType &type = Type(idx);
475 if (!type.collision || !type.shape) {
478 if (type.shape->Intersects(Mchunk * ToTransform(pos, idx), box, Mbox, penetration, normal)) {
479 col.emplace_back(this, idx, penetration, normal);
488 bool Chunk::Intersection(
489 const Entity &entity,
490 const glm::mat4 &Mentity,
491 const glm::mat4 &Mchunk,
492 std::vector<WorldCollision> &col
494 // entity's origin relative to the chunk
495 const glm::vec3 entity_coords(Mentity[3] - Mchunk[3]);
496 const float ec_radius = entity.Radius() + Radius();
498 if (distance2(entity_coords, Center()) > ec_radius * ec_radius) {
506 // assume a bounding radius of 2 for blocks
507 constexpr float block_rad = 2.0f;
508 const float eb_radius = entity.Radius() + block_rad;
510 const RoughLocation::Fine begin(max(
511 RoughLocation::Fine(0),
512 RoughLocation::Fine(floor(entity_coords - eb_radius))
514 const RoughLocation::Fine end(min(
515 RoughLocation::Fine(side),
516 RoughLocation::Fine(ceil(entity_coords + eb_radius))
519 for (RoughLocation::Fine pos(begin); pos.z < end.z; ++pos.z) {
520 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
521 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
522 int idx = ToIndex(pos);
523 const BlockType &type = Type(idx);
524 if (!type.collision || !type.shape) {
527 if (type.shape->Intersects(Mchunk * ToTransform(pos, idx), entity.Bounds(), Mentity, penetration, normal)) {
528 col.emplace_back(this, idx, penetration, normal);
540 BlockMesh::Buffer buf;
544 void Chunk::Update(BlockMesh &model) noexcept {
545 int vtx_count = 0, idx_count = 0;
546 for (const auto &block : blocks) {
547 const BlockType &type = Type(block);
548 if (type.visible && type.shape) {
549 vtx_count += type.shape->VertexCount();
550 idx_count += type.shape->IndexCount();
554 buf.Reserve(vtx_count, idx_count);
558 BlockMesh::Index vtx_counter = 0;
559 for (size_t z = 0; z < side; ++z) {
560 for (size_t y = 0; y < side; ++y) {
561 for (size_t x = 0; x < side; ++x, ++idx) {
562 const BlockType &type = Type(BlockAt(idx));
563 const RoughLocation::Fine pos(x, y, z);
565 if (!type.visible || !type.shape || Obstructed(pos).All()) continue;
567 type.FillBlockMesh(buf, ToTransform(pos, idx), vtx_counter);
568 size_t vtx_begin = vtx_counter;
569 vtx_counter += type.shape->VertexCount();
571 for (size_t vtx = vtx_begin; vtx < vtx_counter; ++vtx) {
572 buf.lights.emplace_back(GetVertexLight(
575 type.shape->VertexNormal(vtx - vtx_begin, BlockAt(idx).Transform())
587 Block::FaceSet Chunk::Obstructed(const RoughLocation::Fine &pos) const noexcept {
588 Block::FaceSet result;
590 for (int f = 0; f < Block::FACE_COUNT; ++f) {
591 Block::Face face = Block::Face(f);
592 BlockLookup next(const_cast<Chunk *>(this), pos, face);
593 if (next && next.GetType().FaceFilled(next.GetBlock(), Block::Opposite(face))) {
601 glm::mat4 Chunk::ToTransform(const RoughLocation::Fine &pos, int idx) const noexcept {
602 return glm::translate(ToCoords(pos)) * BlockAt(idx).Transform();
605 glm::mat4 Chunk::ToTransform(const ExactLocation::Coarse &ref, const RoughLocation::Fine &pos, int idx) const noexcept {
606 return glm::translate(ExactLocation::Fine((position - ref) * ExactLocation::Extent()) + ToCoords(pos)) * BlockAt(idx).Transform();
610 BlockLookup::BlockLookup(Chunk *c, const RoughLocation::Fine &p) noexcept
612 while (pos.x >= Chunk::side) {
613 if (chunk->HasNeighbor(Block::FACE_RIGHT)) {
614 chunk = &chunk->GetNeighbor(Block::FACE_RIGHT);
615 pos.x -= Chunk::side;
622 if (chunk->HasNeighbor(Block::FACE_LEFT)) {
623 chunk = &chunk->GetNeighbor(Block::FACE_LEFT);
624 pos.x += Chunk::side;
630 while (pos.y >= Chunk::side) {
631 if (chunk->HasNeighbor(Block::FACE_UP)) {
632 chunk = &chunk->GetNeighbor(Block::FACE_UP);
633 pos.y -= Chunk::side;
640 if (chunk->HasNeighbor(Block::FACE_DOWN)) {
641 chunk = &chunk->GetNeighbor(Block::FACE_DOWN);
642 pos.y += Chunk::side;
648 while (pos.z >= Chunk::side) {
649 if (chunk->HasNeighbor(Block::FACE_FRONT)) {
650 chunk = &chunk->GetNeighbor(Block::FACE_FRONT);
651 pos.z -= Chunk::side;
658 if (chunk->HasNeighbor(Block::FACE_BACK)) {
659 chunk = &chunk->GetNeighbor(Block::FACE_BACK);
660 pos.z += Chunk::side;
668 BlockLookup::BlockLookup(Chunk *c, const RoughLocation::Fine &p, Block::Face face) noexcept
670 pos += Block::FaceNormal(face);
671 if (!Chunk::InBounds(pos)) {
672 pos -= Block::FaceNormal(face) * ExactLocation::Extent();
673 chunk = &chunk->GetNeighbor(face);
678 ChunkLoader::ChunkLoader(
680 const Generator &gen,
681 const WorldSave &save
689 void ChunkLoader::Update(int dt) {
690 // check if there's chunks waiting to be loaded
691 // load until one of load or generation limits was hit
692 constexpr int max_load = 10;
693 constexpr int max_gen = 1;
696 while (loaded < max_load && generated < max_gen && store.HasMissing()) {
704 // store a few chunks as well
705 constexpr int max_save = 10;
707 for (Chunk &chunk : store) {
708 if (chunk.ShouldUpdateSave()) {
711 if (saved >= max_save) {
718 int ChunkLoader::ToLoad() const noexcept {
719 return store.EstimateMissing();
722 bool ChunkLoader::LoadOne() {
723 if (!store.HasMissing()) return false;
725 ExactLocation::Coarse pos = store.NextMissing();
726 Chunk *chunk = store.Allocate(pos);
728 // chunk store corrupted?
732 bool generated = false;
733 if (save.Exists(pos)) {
740 ChunkIndex *index = store.ClosestIndex(pos);
745 ExactLocation::Coarse begin(pos - ExactLocation::Coarse(1));
746 ExactLocation::Coarse end(pos + ExactLocation::Coarse(2));
747 for (ExactLocation::Coarse iter(begin); iter.z < end.z; ++iter.z) {
748 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
749 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
750 if (index->IsBorder(iter)) continue;
751 Chunk *light_chunk = index->Get(iter);
752 if (!light_chunk) continue;
753 if (index->HasAllSurrounding(iter)) {
754 if (!light_chunk->Lighted()) {
755 light_chunk->ScanLights();
757 light_chunk->InvalidateMesh();
767 void ChunkLoader::LoadN(std::size_t n) {
768 std::size_t end = std::min(n, std::size_t(ToLoad()));
769 for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
775 ChunkRenderer::ChunkRenderer(ChunkIndex &index)
777 , models(index.TotalChunks())
779 , fog_density(0.0f) {
783 ChunkRenderer::~ChunkRenderer() {
787 int ChunkRenderer::MissingChunks() const noexcept {
788 return index.MissingChunks();
791 void ChunkRenderer::LoadTextures(const AssetLoader &loader, const ResourceIndex &tex_index) {
793 loader.LoadTextures(tex_index, block_tex);
794 block_tex.FilterNearest();
797 void ChunkRenderer::Update(int dt) {
798 for (int i = 0, updates = 0; updates < dt && i < index.TotalChunks(); ++i) {
799 if (!index[i]) continue;
800 if (!index[i]->Lighted() && index.HasAllSurrounding(index[i]->Position())) {
801 index[i]->ScanLights();
803 if (index[i]->ShouldUpdateMesh()) {
804 index[i]->Update(models[i]);
810 void ChunkRenderer::Render(Viewport &viewport) {
811 BlockLighting &chunk_prog = viewport.ChunkProgram();
812 chunk_prog.SetTexture(block_tex);
813 chunk_prog.SetFogDensity(fog_density);
815 Frustum frustum(transpose(chunk_prog.GetVP()));
818 for (int i = 0; i < index.TotalChunks(); ++i) {
819 if (!index[i]) continue;
820 box.min = (index[i]->Position() - index.Base()) * ExactLocation::Extent();
821 box.max = box.min + ExactLocation::FExtent();
823 if (!CullTest(box, frustum)) {
824 if (index[i]->ShouldUpdateMesh()) {
825 index[i]->Update(models[i]);
827 if (!models[i].Empty()) {
828 chunk_prog.SetM(index[i]->Transform(index.Base()));
836 ChunkIndex::ChunkIndex(ChunkStore &store, const ExactLocation::Coarse &base, int extent)
840 , side_length(2 * extent + 1)
841 , total_length(side_length * side_length * side_length)
844 , stride(1, side_length, side_length * side_length)
845 , chunks(total_length, nullptr) {
849 ChunkIndex::~ChunkIndex() {
853 bool ChunkIndex::InRange(const ExactLocation::Coarse &pos) const noexcept {
854 return Distance(pos) <= extent;
857 bool ChunkIndex::IsBorder(const ExactLocation::Coarse &pos) const noexcept {
858 return Distance(pos) == extent;
861 int ChunkIndex::Distance(const ExactLocation::Coarse &pos) const noexcept {
862 return manhattan_radius(pos - base);
865 bool ChunkIndex::HasAllSurrounding(const ExactLocation::Coarse &pos) const noexcept {
866 ExactLocation::Coarse begin(pos - ExactLocation::Coarse(1));
867 ExactLocation::Coarse end(pos + ExactLocation::Coarse(2));
868 for (ExactLocation::Coarse iter(begin); iter.z < end.z; ++iter.z) {
869 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
870 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
871 if (!Get(iter)) return false;
878 int ChunkIndex::IndexOf(const ExactLocation::Coarse &pos) const noexcept {
879 ExactLocation::Coarse mod_pos(
884 return mod_pos.x * stride.x
885 + mod_pos.y * stride.y
886 + mod_pos.z * stride.z;
889 ExactLocation::Coarse ChunkIndex::PositionOf(int i) const noexcept {
890 ExactLocation::Coarse zero_pos(
891 (i / stride.x) % side_length,
892 (i / stride.y) % side_length,
893 (i / stride.z) % side_length
895 ExactLocation::Coarse zero_base(
900 ExactLocation::Coarse base_relative(zero_pos - zero_base);
901 if (base_relative.x > extent) base_relative.x -= side_length;
902 else if (base_relative.x < -extent) base_relative.x += side_length;
903 if (base_relative.y > extent) base_relative.y -= side_length;
904 else if (base_relative.y < -extent) base_relative.y += side_length;
905 if (base_relative.z > extent) base_relative.z -= side_length;
906 else if (base_relative.z < -extent) base_relative.z += side_length;
907 return base + base_relative;
910 Chunk *ChunkIndex::Get(const ExactLocation::Coarse &pos) noexcept {
912 return chunks[IndexOf(pos)];
918 const Chunk *ChunkIndex::Get(const ExactLocation::Coarse &pos) const noexcept {
920 return chunks[IndexOf(pos)];
926 void ChunkIndex::Rebase(const ExactLocation::Coarse &new_base) {
927 if (new_base == base) return;
929 ExactLocation::Coarse diff(new_base - base);
931 if (manhattan_radius(diff) > extent) {
932 // that's more than half, so probably not worth shifting
941 Shift(Block::FACE_RIGHT);
945 Shift(Block::FACE_LEFT);
949 Shift(Block::FACE_UP);
953 Shift(Block::FACE_DOWN);
957 Shift(Block::FACE_FRONT);
961 Shift(Block::FACE_BACK);
967 int ChunkIndex::GetCol(int c) const noexcept {
969 if (c < 0) c += side_length;
973 void ChunkIndex::Shift(Block::Face f) {
974 int a_axis = Block::Axis(f);
975 int b_axis = (a_axis + 1) % 3;
976 int c_axis = (a_axis + 2) % 3;
977 int dir = Block::Direction(f);
979 int a = GetCol(base[a_axis] + (extent * dir));
980 int a_stride = a * stride[a_axis];
981 for (int b = 0; b < side_length; ++b) {
982 int b_stride = b * stride[b_axis];
983 for (int c = 0; c < side_length; ++c) {
984 int bc_stride = b_stride + c * stride[c_axis];
985 int index = a_stride + bc_stride;
987 int neighbor = ((a - dir + side_length) % side_length) * stride[a_axis] + bc_stride;
988 if (chunks[neighbor] && chunks[neighbor]->HasNeighbor(f)) {
989 Set(index, chunks[neighbor]->GetNeighbor(f));
995 void ChunkIndex::Clear() noexcept {
996 for (int i = 0; i < total_length && total_indexed > 0; ++i) {
1001 void ChunkIndex::Scan() noexcept {
1002 for (Chunk &chunk : store) {
1007 void ChunkIndex::Register(Chunk &chunk) noexcept {
1008 if (InRange(chunk.Position())) {
1009 Set(IndexOf(chunk.Position()), chunk);
1013 void ChunkIndex::Set(int index, Chunk &chunk) noexcept {
1015 chunks[index] = &chunk;
1020 void ChunkIndex::Unset(int index) noexcept {
1021 if (chunks[index]) {
1022 chunks[index]->UnRef();
1023 chunks[index] = nullptr;
1028 ExactLocation::Coarse ChunkIndex::NextMissing() noexcept {
1029 if (MissingChunks() > 0) {
1030 int roundtrip = last_missing;
1031 last_missing = (last_missing + 1) % total_length;
1032 while (chunks[last_missing]) {
1033 last_missing = (last_missing + 1) % total_length;
1034 if (last_missing == roundtrip) {
1039 return PositionOf(last_missing);
1043 ChunkStore::ChunkStore(const BlockTypeRegistry &types)
1051 ChunkStore::~ChunkStore() {
1055 ChunkIndex &ChunkStore::MakeIndex(const ExactLocation::Coarse &pos, int extent) {
1056 indices.emplace_back(*this, pos, extent);
1057 return indices.back();
1060 void ChunkStore::UnregisterIndex(ChunkIndex &index) {
1061 for (auto i = indices.begin(), end = indices.end(); i != end; ++i) {
1062 if (&*i == &index) {
1071 ChunkIndex *ChunkStore::ClosestIndex(const ExactLocation::Coarse &pos) {
1072 ChunkIndex *closest_index = nullptr;
1073 int closest_distance = std::numeric_limits<int>::max();
1075 for (ChunkIndex &index : indices) {
1076 int distance = index.Distance(pos);
1077 if (distance < closest_distance) {
1078 closest_index = &index;
1079 closest_distance = distance;
1083 return closest_index;
1086 Chunk *ChunkStore::Get(const ExactLocation::Coarse &pos) noexcept {
1087 for (ChunkIndex &index : indices) {
1088 Chunk *chunk = index.Get(pos);
1096 const Chunk *ChunkStore::Get(const ExactLocation::Coarse &pos) const noexcept {
1097 for (const ChunkIndex &index : indices) {
1098 const Chunk *chunk = index.Get(pos);
1106 Chunk *ChunkStore::Allocate(const ExactLocation::Coarse &pos) {
1107 Chunk *chunk = Get(pos);
1112 loaded.emplace(loaded.begin(), types);
1114 loaded.splice(loaded.begin(), free, free.begin());
1115 loaded.front().Unlink();
1117 chunk = &loaded.front();
1118 chunk->Position(pos);
1119 for (ChunkIndex &index : indices) {
1120 if (index.InRange(pos)) {
1121 index.Register(*chunk);
1124 for (int i = 0; i < Block::FACE_COUNT; ++i) {
1125 Block::Face face = Block::Face(i);
1126 ExactLocation::Coarse neighbor_pos(pos + Block::FaceNormal(face));
1127 Chunk *neighbor = Get(neighbor_pos);
1129 chunk->SetNeighbor(face, *neighbor);
1135 bool ChunkStore::HasMissing() const noexcept {
1136 for (const ChunkIndex &index : indices) {
1137 if (index.MissingChunks() > 0) {
1144 int ChunkStore::EstimateMissing() const noexcept {
1146 for (const ChunkIndex &index : indices) {
1147 missing += index.MissingChunks();
1152 ExactLocation::Coarse ChunkStore::NextMissing() noexcept {
1153 for (ChunkIndex &index : indices) {
1154 if (index.MissingChunks()) {
1155 return index.NextMissing();
1158 return ExactLocation::Coarse(0, 0, 0);
1161 void ChunkStore::Clean() {
1162 for (auto i = loaded.begin(), end = loaded.end(); i != end;) {
1163 if (i->Referenced() || i->ShouldUpdateSave()) {
1168 free.splice(free.end(), loaded, chunk);
1170 chunk->InvalidateMesh();