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 "../graphics/BlockLighting.hpp"
12 #include "../graphics/BlockMesh.hpp"
13 #include "../graphics/Viewport.hpp"
14 #include "../io/WorldSave.hpp"
24 constexpr int Chunk::width;
25 constexpr int Chunk::height;
26 constexpr int Chunk::depth;
27 constexpr int Chunk::size;
30 Chunk::Chunk(const BlockTypeRegistry &types) noexcept
44 Chunk::Chunk(Chunk &&other) noexcept
46 , generated(other.generated)
47 , lighted(other.lighted)
48 , position(other.position)
49 , ref_count(other.ref_count)
50 , dirty_mesh(other.dirty_mesh)
51 , dirty_save(other.dirty_save) {
52 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
53 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
54 std::copy(other.light, other.light + sizeof(light), light);
58 Chunk &Chunk::operator =(Chunk &&other) noexcept {
60 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
61 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
62 std::copy(other.light, other.light + sizeof(light), light);
63 generated = other.generated;
64 lighted = other.lighted;
65 position = other.position;
66 std::swap(ref_count, other.ref_count);
67 dirty_mesh = other.dirty_save;
68 dirty_save = other.dirty_save;
80 SetNode(Chunk *chunk, Chunk::Pos pos)
81 : chunk(chunk), pos(pos) { }
83 int Get() const noexcept { return chunk->GetLight(pos); }
84 void Set(int level) noexcept { chunk->SetLight(pos, level); }
86 const BlockType &GetType() const noexcept { return chunk->Type(Chunk::ToIndex(pos)); }
88 bool HasNext(Block::Face face) noexcept {
89 const BlockType &type = GetType();
90 if (type.block_light && !type.luminosity) return false;
91 const BlockLookup next(chunk, pos, face);
94 SetNode GetNext(Block::Face face) noexcept {
95 const BlockLookup next(chunk, pos, face);
96 return SetNode(&next.GetChunk(), next.GetBlockPos());
106 UnsetNode(Chunk *chunk, Chunk::Pos pos)
107 : SetNode(chunk, pos), level(Get()) { }
109 UnsetNode(const SetNode &set)
110 : SetNode(set), level(Get()) { }
113 bool HasNext(Block::Face face) noexcept {
114 const BlockLookup next(chunk, pos, face);
117 UnsetNode GetNext(Block::Face face) noexcept { return UnsetNode(SetNode::GetNext(face)); }
121 std::queue<SetNode> light_queue;
122 std::queue<UnsetNode> dark_queue;
124 void work_light() noexcept {
125 while (!light_queue.empty()) {
126 SetNode node = light_queue.front();
129 int level = node.Get() - 1;
130 for (int face = 0; face < Block::FACE_COUNT; ++face) {
131 if (node.HasNext(Block::Face(face))) {
132 SetNode other = node.GetNext(Block::Face(face));
133 if (other.Get() < level) {
135 light_queue.emplace(other);
142 void work_dark() noexcept {
143 while (!dark_queue.empty()) {
144 UnsetNode node = dark_queue.front();
147 for (int face = 0; face < Block::FACE_COUNT; ++face) {
148 if (node.HasNext(Block::Face(face))) {
149 UnsetNode other = node.GetNext(Block::Face(face));
150 // TODO: if there a light source here with the same level this will err
151 if (other.Get() != 0 && other.Get() < node.level) {
153 dark_queue.emplace(other);
155 light_queue.emplace(other);
164 void Chunk::SetBlock(int index, const Block &block) noexcept {
165 const BlockType &old_type = Type(blocks[index]);
166 const BlockType &new_type = Type(block);
168 blocks[index] = block;
171 if (!lighted || &old_type == &new_type) return;
173 if (new_type.luminosity > old_type.luminosity) {
175 SetLight(index, new_type.luminosity);
176 light_queue.emplace(this, ToPos(index));
178 } else if (new_type.luminosity < old_type.luminosity) {
180 dark_queue.emplace(this, ToPos(index));
183 SetLight(index, new_type.luminosity);
184 light_queue.emplace(this, ToPos(index));
186 } else if (new_type.block_light && !old_type.block_light) {
188 if (GetLight(index) > 0) {
189 dark_queue.emplace(this, ToPos(index));
194 } else if (!new_type.block_light && old_type.block_light) {
197 Pos pos(ToPos(index));
198 for (int face = 0; face < Block::FACE_COUNT; ++face) {
199 BlockLookup next_block(this, pos, Block::Face(face));
201 level = std::max(level, next_block.GetLight());
205 SetLight(index, level - 1);
206 light_queue.emplace(this, pos);
212 void Chunk::ScanLights() {
215 for (; pos.z < depth; ++pos.z) {
216 for (pos.y = 0; pos.y < height; ++pos.y) {
217 for (pos.x = 0; pos.x < width; ++pos.x, ++idx) {
218 const BlockType &type = Type(blocks[idx]);
219 if (type.luminosity) {
220 SetLight(idx, type.luminosity);
221 light_queue.emplace(this, pos);
230 void Chunk::SetNeighbor(Block::Face face, Chunk &other) noexcept {
231 neighbor[face] = &other;
232 other.neighbor[Block::Opposite(face)] = this;
235 void Chunk::Unlink() noexcept {
236 for (int face = 0; face < Block::FACE_COUNT; ++face) {
237 if (neighbor[face]) {
238 neighbor[face]->neighbor[Block::Opposite(Block::Face(face))] = nullptr;
239 neighbor[face] = nullptr;
245 void Chunk::SetLight(int index, int level) noexcept {
246 if (light[index] != level) {
247 light[index] = level;
252 int Chunk::GetLight(int index) const noexcept {
256 float Chunk::GetVertexLight(const Pos &pos, const BlockMesh::Position &vtx, const EntityMesh::Normal &norm) const noexcept {
257 int index = ToIndex(pos);
258 float light = GetLight(index);
260 Block::Face direct_face(Block::NormalFace(norm));
262 BlockLookup direct(const_cast<Chunk *>(this), pos, Block::NormalFace(norm));
264 float direct_light = direct.GetLight();
265 if (direct_light > light) {
266 light = direct_light;
272 if (Type(BlockAt(index)).luminosity > 0 || direct.GetType().block_light) {
277 switch (Block::Axis(direct_face)) {
279 edge[0] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
280 edge[1] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
283 edge[0] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
284 edge[1] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
287 edge[0] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
288 edge[1] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
295 BlockLookup next[2] = {
296 direct.Next(edge[0]),
297 direct.Next(edge[1]),
301 if (next[0].GetType().block_light) {
304 light += next[0].GetLight();
309 if (next[1].GetType().block_light) {
312 light += next[1].GetLight();
318 BlockLookup corner = next[0].Next(edge[1]);
320 if (corner.GetType().block_light) {
323 light += corner.GetLight();
327 } else if (next[1]) {
328 BlockLookup corner = next[1].Next(edge[0]);
330 if (corner.GetType().block_light) {
333 light += corner.GetLight();
342 return (light / num) - (occlusion * 0.8f);
346 bool Chunk::IsSurface(const Pos &pos) const noexcept {
347 const Block &block = BlockAt(pos);
348 if (!Type(block).visible) {
351 for (int face = 0; face < Block::FACE_COUNT; ++face) {
352 BlockLookup next = BlockLookup(const_cast<Chunk *>(this), pos, Block::Face(face));
353 if (!next || !next.GetType().visible) {
361 bool Chunk::Intersection(
369 coll.depth = std::numeric_limits<float>::infinity();
370 for (int z = 0; z < depth; ++z) {
371 for (int y = 0; y < height; ++y) {
372 for (int x = 0; x < width; ++x, ++idx) {
373 const BlockType &type = Type(idx);
379 if (type.shape->Intersects(ray, M * ToTransform(Pos(x, y, z), idx), cur_dist, cur_norm)) {
380 if (cur_dist < coll.depth) {
382 coll.depth = cur_dist;
383 coll.normal = cur_norm;
390 if (coll.block < 0) {
393 coll.normal = glm::vec3(BlockAt(coll.block).Transform() * glm::vec4(coll.normal, 0.0f));
398 bool Chunk::Intersection(
400 const glm::mat4 &Mbox,
401 const glm::mat4 &Mchunk,
402 std::vector<WorldCollision> &col
408 if (!blank::Intersection(box, Mbox, Bounds(), Mchunk, penetration, normal)) {
411 for (int idx = 0, z = 0; z < depth; ++z) {
412 for (int y = 0; y < height; ++y) {
413 for (int x = 0; x < width; ++x, ++idx) {
414 const BlockType &type = Type(idx);
415 if (!type.collision) {
418 if (type.shape->Intersects(Mchunk * ToTransform(Pos(x, y, z), idx), box, Mbox, penetration, normal)) {
419 col.emplace_back(this, idx, penetration, normal);
431 BlockMesh::Buffer buf;
435 void Chunk::Update(BlockMesh &model) noexcept {
436 int vtx_count = 0, idx_count = 0;
437 for (const auto &block : blocks) {
438 const CollisionBounds *shape = Type(block).shape;
439 vtx_count += shape->VertexCount();
440 idx_count += shape->VertexIndexCount();
443 buf.Reserve(vtx_count, idx_count);
446 BlockMesh::Index vtx_counter = 0;
447 for (size_t z = 0; z < depth; ++z) {
448 for (size_t y = 0; y < height; ++y) {
449 for (size_t x = 0; x < width; ++x, ++idx) {
450 const BlockType &type = Type(BlockAt(idx));
451 const Pos pos(x, y, z);
453 if (!type.visible || Obstructed(pos).All()) continue;
455 type.FillBlockMesh(buf, ToTransform(pos, idx), vtx_counter);
456 size_t vtx_begin = vtx_counter;
457 vtx_counter += type.shape->VertexCount();
459 for (size_t vtx = vtx_begin; vtx < vtx_counter; ++vtx) {
460 buf.lights.emplace_back(GetVertexLight(
463 type.shape->VertexNormal(vtx - vtx_begin, BlockAt(idx).Transform())
474 Block::FaceSet Chunk::Obstructed(const Pos &pos) const noexcept {
475 Block::FaceSet result;
477 for (int f = 0; f < Block::FACE_COUNT; ++f) {
478 Block::Face face = Block::Face(f);
479 BlockLookup next(const_cast<Chunk *>(this), pos, face);
480 if (next && next.GetType().FaceFilled(next.GetBlock(), Block::Opposite(face))) {
488 glm::mat4 Chunk::ToTransform(const Pos &pos, int idx) const noexcept {
489 return glm::translate(ToCoords(pos)) * BlockAt(idx).Transform();
493 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p) noexcept
495 while (pos.x >= Chunk::width) {
496 if (chunk->HasNeighbor(Block::FACE_RIGHT)) {
497 chunk = &chunk->GetNeighbor(Block::FACE_RIGHT);
498 pos.x -= Chunk::width;
505 if (chunk->HasNeighbor(Block::FACE_LEFT)) {
506 chunk = &chunk->GetNeighbor(Block::FACE_LEFT);
507 pos.x += Chunk::width;
513 while (pos.y >= Chunk::height) {
514 if (chunk->HasNeighbor(Block::FACE_UP)) {
515 chunk = &chunk->GetNeighbor(Block::FACE_UP);
516 pos.y -= Chunk::height;
523 if (chunk->HasNeighbor(Block::FACE_DOWN)) {
524 chunk = &chunk->GetNeighbor(Block::FACE_DOWN);
525 pos.y += Chunk::height;
531 while (pos.z >= Chunk::depth) {
532 if (chunk->HasNeighbor(Block::FACE_FRONT)) {
533 chunk = &chunk->GetNeighbor(Block::FACE_FRONT);
534 pos.z -= Chunk::depth;
541 if (chunk->HasNeighbor(Block::FACE_BACK)) {
542 chunk = &chunk->GetNeighbor(Block::FACE_BACK);
543 pos.z += Chunk::depth;
551 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p, Block::Face face) noexcept
553 pos += Block::FaceNormal(face);
554 if (!Chunk::InBounds(pos)) {
555 pos -= Block::FaceNormal(face) * Chunk::Extent();
556 chunk = &chunk->GetNeighbor(face);
561 ChunkLoader::ChunkLoader(
563 const Generator &gen,
564 const WorldSave &save
572 void ChunkLoader::Update(int dt) {
573 // check if there's chunks waiting to be loaded
574 // load until one of load or generation limits was hit
575 constexpr int max_load = 10;
576 constexpr int max_gen = 1;
579 while (loaded < max_load && generated < max_gen && store.HasMissing()) {
587 // store a few chunks as well
588 constexpr int max_save = 10;
590 for (Chunk &chunk : store) {
591 if (chunk.ShouldUpdateSave()) {
594 if (saved >= max_save) {
601 int ChunkLoader::ToLoad() const noexcept {
602 return store.EstimateMissing();
605 bool ChunkLoader::LoadOne() {
606 if (!store.HasMissing()) return false;
608 Chunk::Pos pos = store.NextMissing();
609 Chunk *chunk = store.Allocate(pos);
611 // chunk store corrupted?
615 bool generated = false;
616 if (save.Exists(pos)) {
623 ChunkIndex *index = store.ClosestIndex(pos);
628 Chunk::Pos begin(pos - Chunk::Pos(1));
629 Chunk::Pos end(pos + Chunk::Pos(2));
630 for (Chunk::Pos iter(begin); iter.z < end.z; ++iter.z) {
631 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
632 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
633 if (index->IsBorder(iter)) continue;
634 Chunk *light_chunk = index->Get(iter);
635 if (!light_chunk || light_chunk->Lighted()) continue;
636 if (index->HasAllSurrounding(iter)) {
637 light_chunk->ScanLights();
646 void ChunkLoader::LoadN(std::size_t n) {
647 std::size_t end = std::min(n, std::size_t(ToLoad()));
648 for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
654 ChunkRenderer::ChunkRenderer(ChunkIndex &index)
656 , models(index.TotalChunks())
658 , fog_density(0.0f) {
662 ChunkRenderer::~ChunkRenderer() {
666 int ChunkRenderer::MissingChunks() const noexcept {
667 return index.MissingChunks();
670 void ChunkRenderer::LoadTextures(const AssetLoader &loader, const TextureIndex &tex_index) {
672 loader.LoadTextures(tex_index, block_tex);
673 block_tex.FilterNearest();
676 void ChunkRenderer::Update(int dt) {
677 for (int i = 0, updates = 0; updates < dt && i < index.TotalChunks(); ++i) {
678 if (!index[i]) continue;
679 if (!index[i]->Lighted() && index.HasAllSurrounding(index[i]->Position())) {
680 index[i]->ScanLights();
682 if (index[i]->ShouldUpdateMesh()) {
683 index[i]->Update(models[i]);
689 void ChunkRenderer::Render(Viewport &viewport) {
690 BlockLighting &chunk_prog = viewport.ChunkProgram();
691 chunk_prog.SetTexture(block_tex);
692 chunk_prog.SetFogDensity(fog_density);
694 for (int i = 0; i < index.TotalChunks(); ++i) {
695 if (!index[i]) continue;
696 glm::mat4 m(index[i]->Transform(index.Base()));
697 glm::mat4 mvp(chunk_prog.GetVP() * m);
698 if (!CullTest(Chunk::Bounds(), mvp)) {
699 if (index[i]->ShouldUpdateMesh()) {
700 index[i]->Update(models[i]);
709 ChunkIndex::ChunkIndex(ChunkStore &store, const Chunk::Pos &base, int extent)
713 , side_length(2 * extent + 1)
714 , total_length(side_length * side_length * side_length)
717 , stride(1, side_length, side_length * side_length)
718 , chunks(total_length, nullptr) {
722 ChunkIndex::~ChunkIndex() {
726 bool ChunkIndex::InRange(const Chunk::Pos &pos) const noexcept {
727 return Distance(pos) <= extent;
730 bool ChunkIndex::IsBorder(const Chunk::Pos &pos) const noexcept {
731 return Distance(pos) == extent;
734 int ChunkIndex::Distance(const Chunk::Pos &pos) const noexcept {
735 return manhattan_radius(pos - base);
738 bool ChunkIndex::HasAllSurrounding(const Chunk::Pos &pos) const noexcept {
739 Chunk::Pos begin(pos - Chunk::Pos(1));
740 Chunk::Pos end(pos + Chunk::Pos(2));
741 for (Chunk::Pos iter(begin); iter.z < end.z; ++iter.z) {
742 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
743 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
744 if (!Get(iter)) return false;
751 int ChunkIndex::IndexOf(const Chunk::Pos &pos) const noexcept {
757 return mod_pos.x * stride.x
758 + mod_pos.y * stride.y
759 + mod_pos.z * stride.z;
762 Chunk::Pos ChunkIndex::PositionOf(int i) const noexcept {
764 (i / stride.x) % side_length,
765 (i / stride.y) % side_length,
766 (i / stride.z) % side_length
768 Chunk::Pos zero_base(
773 Chunk::Pos base_relative(zero_pos - zero_base);
774 if (base_relative.x > extent) base_relative.x -= side_length;
775 else if (base_relative.x < -extent) base_relative.x += side_length;
776 if (base_relative.y > extent) base_relative.y -= side_length;
777 else if (base_relative.y < -extent) base_relative.y += side_length;
778 if (base_relative.z > extent) base_relative.z -= side_length;
779 else if (base_relative.z < -extent) base_relative.z += side_length;
780 return base + base_relative;
783 Chunk *ChunkIndex::Get(const Chunk::Pos &pos) noexcept {
785 return chunks[IndexOf(pos)];
791 const Chunk *ChunkIndex::Get(const Chunk::Pos &pos) const noexcept {
793 return chunks[IndexOf(pos)];
799 void ChunkIndex::Rebase(const Chunk::Pos &new_base) {
800 if (new_base == base) return;
802 Chunk::Pos diff(new_base - base);
804 if (manhattan_radius(diff) > extent) {
805 // that's more than half, so probably not worth shifting
814 Shift(Block::FACE_RIGHT);
818 Shift(Block::FACE_LEFT);
822 Shift(Block::FACE_UP);
826 Shift(Block::FACE_DOWN);
830 Shift(Block::FACE_FRONT);
834 Shift(Block::FACE_BACK);
840 int ChunkIndex::GetCol(int c) const noexcept {
842 if (c < 0) c += side_length;
846 void ChunkIndex::Shift(Block::Face f) {
847 int a_axis = Block::Axis(f);
848 int b_axis = (a_axis + 1) % 3;
849 int c_axis = (a_axis + 2) % 3;
850 int dir = Block::Direction(f);
852 int a = GetCol(base[a_axis] + (extent * dir));
853 int a_stride = a * stride[a_axis];
854 for (int b = 0; b < side_length; ++b) {
855 int b_stride = b * stride[b_axis];
856 for (int c = 0; c < side_length; ++c) {
857 int bc_stride = b_stride + c * stride[c_axis];
858 int index = a_stride + bc_stride;
860 int neighbor = ((a - dir + side_length) % side_length) * stride[a_axis] + bc_stride;
861 if (chunks[neighbor] && chunks[neighbor]->HasNeighbor(f)) {
862 Set(index, chunks[neighbor]->GetNeighbor(f));
868 void ChunkIndex::Clear() noexcept {
869 for (int i = 0; i < total_length && total_indexed > 0; ++i) {
874 void ChunkIndex::Scan() noexcept {
875 for (Chunk &chunk : store) {
880 void ChunkIndex::Register(Chunk &chunk) noexcept {
881 if (InRange(chunk.Position())) {
882 Set(IndexOf(chunk.Position()), chunk);
886 void ChunkIndex::Set(int index, Chunk &chunk) noexcept {
888 chunks[index] = &chunk;
893 void ChunkIndex::Unset(int index) noexcept {
895 chunks[index]->UnRef();
896 chunks[index] = nullptr;
901 Chunk::Pos ChunkIndex::NextMissing() noexcept {
902 if (MissingChunks() > 0) {
903 int roundtrip = last_missing;
904 last_missing = (last_missing + 1) % total_length;
905 while (chunks[last_missing]) {
906 last_missing = (last_missing + 1) % total_length;
907 if (last_missing == roundtrip) {
912 return PositionOf(last_missing);
916 ChunkStore::ChunkStore(const BlockTypeRegistry &types)
924 ChunkStore::~ChunkStore() {
928 ChunkIndex &ChunkStore::MakeIndex(const Chunk::Pos &pos, int extent) {
929 indices.emplace_back(*this, pos, extent);
930 return indices.back();
933 void ChunkStore::UnregisterIndex(ChunkIndex &index) {
934 for (auto i = indices.begin(), end = indices.end(); i != end; ++i) {
944 ChunkIndex *ChunkStore::ClosestIndex(const Chunk::Pos &pos) {
945 ChunkIndex *closest_index = nullptr;
946 int closest_distance = std::numeric_limits<int>::max();
948 for (ChunkIndex &index : indices) {
949 int distance = index.Distance(pos);
950 if (distance < closest_distance) {
951 closest_index = &index;
952 closest_distance = distance;
956 return closest_index;
959 Chunk *ChunkStore::Get(const Chunk::Pos &pos) {
960 for (ChunkIndex &index : indices) {
961 Chunk *chunk = index.Get(pos);
969 Chunk *ChunkStore::Allocate(const Chunk::Pos &pos) {
970 Chunk *chunk = Get(pos);
975 loaded.emplace(loaded.begin(), types);
977 loaded.splice(loaded.begin(), free, free.begin());
978 loaded.front().Unlink();
980 chunk = &loaded.front();
981 chunk->Position(pos);
982 for (ChunkIndex &index : indices) {
983 if (index.InRange(pos)) {
984 index.Register(*chunk);
987 for (int i = 0; i < Block::FACE_COUNT; ++i) {
988 Block::Face face = Block::Face(i);
989 Chunk::Pos neighbor_pos(pos + Block::FaceNormal(face));
990 Chunk *neighbor = Get(neighbor_pos);
992 chunk->SetNeighbor(face, *neighbor);
998 bool ChunkStore::HasMissing() const noexcept {
999 for (const ChunkIndex &index : indices) {
1000 if (index.MissingChunks() > 0) {
1007 int ChunkStore::EstimateMissing() const noexcept {
1009 for (const ChunkIndex &index : indices) {
1010 missing += index.MissingChunks();
1015 Chunk::Pos ChunkStore::NextMissing() noexcept {
1016 for (ChunkIndex &index : indices) {
1017 if (index.MissingChunks()) {
1018 return index.NextMissing();
1021 return Chunk::Pos(0, 0, 0);
1024 void ChunkStore::Clean() {
1025 for (auto i = loaded.begin(), end = loaded.end(); i != end;) {
1026 if (i->Referenced() || i->ShouldUpdateSave()) {
1031 free.splice(free.end(), loaded, chunk);
1033 chunk->InvalidateMesh();