]> git.localhorst.tv Git - blank.git/blob - src/world/chunk.cpp
model -> mesh
[blank.git] / src / world / chunk.cpp
1 #include "BlockLookup.hpp"
2 #include "Chunk.hpp"
3 #include "ChunkIndex.hpp"
4 #include "ChunkLoader.hpp"
5 #include "ChunkRenderer.hpp"
6 #include "ChunkStore.hpp"
7
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"
15
16 #include <algorithm>
17 #include <limits>
18 #include <ostream>
19 #include <queue>
20
21
22 namespace blank {
23
24 constexpr int Chunk::width;
25 constexpr int Chunk::height;
26 constexpr int Chunk::depth;
27 constexpr int Chunk::size;
28
29
30 Chunk::Chunk(const BlockTypeRegistry &types) noexcept
31 : types(&types)
32 , neighbor{0}
33 , blocks{}
34 , light{0}
35 , generated(false)
36 , lighted(false)
37 , position(0, 0, 0)
38 , ref_count(0)
39 , dirty_mesh(false)
40 , dirty_save(false) {
41
42 }
43
44 Chunk::Chunk(Chunk &&other) noexcept
45 : types(other.types)
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);
55         other.ref_count = 0;
56 }
57
58 Chunk &Chunk::operator =(Chunk &&other) noexcept {
59         types = other.types;
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;
69         return *this;
70 }
71
72
73 namespace {
74
75 struct SetNode {
76
77         Chunk *chunk;
78         Chunk::Pos pos;
79
80         SetNode(Chunk *chunk, Chunk::Pos pos)
81         : chunk(chunk), pos(pos) { }
82
83         int Get() const noexcept { return chunk->GetLight(pos); }
84         void Set(int level) noexcept { chunk->SetLight(pos, level); }
85
86         const BlockType &GetType() const noexcept { return chunk->Type(Chunk::ToIndex(pos)); }
87
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);
92                 return next;
93         }
94         SetNode GetNext(Block::Face face) noexcept {
95                 const BlockLookup next(chunk, pos, face);
96                 return SetNode(&next.GetChunk(), next.GetBlockPos());
97         }
98
99 };
100
101 struct UnsetNode
102 : public SetNode {
103
104         int level;
105
106         UnsetNode(Chunk *chunk, Chunk::Pos pos)
107         : SetNode(chunk, pos), level(Get()) { }
108
109         UnsetNode(const SetNode &set)
110         : SetNode(set), level(Get()) { }
111
112
113         bool HasNext(Block::Face face) noexcept {
114                 const BlockLookup next(chunk, pos, face);
115                 return next;
116         }
117         UnsetNode GetNext(Block::Face face) noexcept { return UnsetNode(SetNode::GetNext(face)); }
118
119 };
120
121 std::queue<SetNode> light_queue;
122 std::queue<UnsetNode> dark_queue;
123
124 void work_light() noexcept {
125         while (!light_queue.empty()) {
126                 SetNode node = light_queue.front();
127                 light_queue.pop();
128
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) {
134                                         other.Set(level);
135                                         light_queue.emplace(other);
136                                 }
137                         }
138                 }
139         }
140 }
141
142 void work_dark() noexcept {
143         while (!dark_queue.empty()) {
144                 UnsetNode node = dark_queue.front();
145                 dark_queue.pop();
146
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) {
152                                         other.Set(0);
153                                         dark_queue.emplace(other);
154                                 } else {
155                                         light_queue.emplace(other);
156                                 }
157                         }
158                 }
159         }
160 }
161
162 }
163
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);
167
168         blocks[index] = block;
169         Invalidate();
170
171         if (!lighted || &old_type == &new_type) return;
172
173         if (new_type.luminosity > old_type.luminosity) {
174                 // light added
175                 SetLight(index, new_type.luminosity);
176                 light_queue.emplace(this, ToPos(index));
177                 work_light();
178         } else if (new_type.luminosity < old_type.luminosity) {
179                 // light removed
180                 dark_queue.emplace(this, ToPos(index));
181                 SetLight(index, 0);
182                 work_dark();
183                 SetLight(index, new_type.luminosity);
184                 light_queue.emplace(this, ToPos(index));
185                 work_light();
186         } else if (new_type.block_light && !old_type.block_light) {
187                 // obstacle added
188                 if (GetLight(index) > 0) {
189                         dark_queue.emplace(this, ToPos(index));
190                         SetLight(index, 0);
191                         work_dark();
192                         work_light();
193                 }
194         } else if (!new_type.block_light && old_type.block_light) {
195                 // obstacle removed
196                 int level = 0;
197                 Pos pos(ToPos(index));
198                 for (int face = 0; face < Block::FACE_COUNT; ++face) {
199                         BlockLookup next_block(this, pos, Block::Face(face));
200                         if (next_block) {
201                                 level = std::max(level, next_block.GetLight());
202                         }
203                 }
204                 if (level > 1) {
205                         SetLight(index, level - 1);
206                         light_queue.emplace(this, pos);
207                         work_light();
208                 }
209         }
210 }
211
212 void Chunk::ScanLights() {
213         int idx = 0;
214         Pos pos(0, 0, 0);
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);
222                                 }
223                         }
224                 }
225         }
226         work_light();
227         lighted = true;
228 }
229
230 void Chunk::SetNeighbor(Block::Face face, Chunk &other) noexcept {
231         neighbor[face] = &other;
232         other.neighbor[Block::Opposite(face)] = this;
233 }
234
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;
240                 }
241         }
242 }
243
244
245 void Chunk::SetLight(int index, int level) noexcept {
246         if (light[index] != level) {
247                 light[index] = level;
248                 Invalidate();
249         }
250 }
251
252 int Chunk::GetLight(int index) const noexcept {
253         return light[index];
254 }
255
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);
259
260         Block::Face direct_face(Block::NormalFace(norm));
261         // tis okay
262         BlockLookup direct(const_cast<Chunk *>(this), pos, Block::NormalFace(norm));
263         if (direct) {
264                 float direct_light = direct.GetLight();
265                 if (direct_light > light) {
266                         light = direct_light;
267                 }
268         } else {
269                 return light;
270         }
271
272         if (Type(BlockAt(index)).luminosity > 0 || direct.GetType().block_light) {
273                 return light;
274         }
275
276         Block::Face edge[2];
277         switch (Block::Axis(direct_face)) {
278                 case 0: // X
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;
281                         break;
282                 case 1: // Y
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;
285                         break;
286                 case 2: // Z
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;
289                         break;
290         }
291
292         int num = 1;
293         int occlusion = 0;
294
295         BlockLookup next[2] = {
296                 direct.Next(edge[0]),
297                 direct.Next(edge[1]),
298         };
299
300         if (next[0]) {
301                 if (next[0].GetType().block_light) {
302                         ++occlusion;
303                 } else {
304                         light += next[0].GetLight();
305                         ++num;
306                 }
307         }
308         if (next[1]) {
309                 if (next[1].GetType().block_light) {
310                         ++occlusion;
311                 } else {
312                         light += next[1].GetLight();
313                         ++num;
314                 }
315         }
316         if (occlusion < 2) {
317                 if (next[0]) {
318                         BlockLookup corner = next[0].Next(edge[1]);
319                         if (corner) {
320                                 if (corner.GetType().block_light) {
321                                         ++occlusion;
322                                 } else {
323                                         light += corner.GetLight();
324                                         ++num;
325                                 }
326                         }
327                 } else if (next[1]) {
328                         BlockLookup corner = next[1].Next(edge[0]);
329                         if (corner) {
330                                 if (corner.GetType().block_light) {
331                                         ++occlusion;
332                                 } else {
333                                         light += corner.GetLight();
334                                         ++num;
335                                 }
336                         }
337                 }
338         } else {
339                 ++occlusion;
340         }
341
342         return (light / num) - (occlusion * 0.8f);
343 }
344
345
346 bool Chunk::IsSurface(const Pos &pos) const noexcept {
347         const Block &block = BlockAt(pos);
348         if (!Type(block).visible) {
349                 return false;
350         }
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) {
354                         return true;
355                 }
356         }
357         return false;
358 }
359
360
361 bool Chunk::Intersection(
362         const Ray &ray,
363         const glm::mat4 &M,
364         WorldCollision &coll
365 ) noexcept {
366         int idx = 0;
367         coll.chunk = this;
368         coll.block = -1;
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);
374                                 if (!type.visible) {
375                                         continue;
376                                 }
377                                 float cur_dist;
378                                 glm::vec3 cur_norm;
379                                 if (type.shape->Intersects(ray, M * ToTransform(Pos(x, y, z), idx), cur_dist, cur_norm)) {
380                                         if (cur_dist < coll.depth) {
381                                                 coll.block = idx;
382                                                 coll.depth = cur_dist;
383                                                 coll.normal = cur_norm;
384                                         }
385                                 }
386                         }
387                 }
388         }
389
390         if (coll.block < 0) {
391                 return false;
392         } else {
393                 coll.normal = glm::vec3(BlockAt(coll.block).Transform() * glm::vec4(coll.normal, 0.0f));
394                 return true;
395         }
396 }
397
398 bool Chunk::Intersection(
399         const AABB &box,
400         const glm::mat4 &Mbox,
401         const glm::mat4 &Mchunk,
402         std::vector<WorldCollision> &col
403 ) noexcept {
404         bool any = false;
405         float penetration;
406         glm::vec3 normal;
407
408         if (!blank::Intersection(box, Mbox, Bounds(), Mchunk, penetration, normal)) {
409                 return false;
410         }
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) {
416                                         continue;
417                                 }
418                                 if (type.shape->Intersects(Mchunk * ToTransform(Pos(x, y, z), idx), box, Mbox, penetration, normal)) {
419                                         col.emplace_back(this, idx, penetration, normal);
420                                         any = true;
421                                 }
422                         }
423                 }
424         }
425         return any;
426 }
427
428
429 namespace {
430
431 BlockMesh::Buffer buf;
432
433 }
434
435 void Chunk::Update(BlockMesh &model) noexcept {
436         int vtx_count = 0, idx_count = 0;
437         for (const auto &block : blocks) {
438                 const Shape *shape = Type(block).shape;
439                 vtx_count += shape->VertexCount();
440                 idx_count += shape->VertexIndexCount();
441         }
442         buf.Clear();
443         buf.Reserve(vtx_count, idx_count);
444
445         int idx = 0;
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);
452
453                                 if (!type.visible || Obstructed(pos).All()) continue;
454
455                                 type.FillBlockMesh(buf, ToTransform(pos, idx), vtx_counter);
456                                 size_t vtx_begin = vtx_counter;
457                                 vtx_counter += type.shape->VertexCount();
458
459                                 for (size_t vtx = vtx_begin; vtx < vtx_counter; ++vtx) {
460                                         buf.lights.emplace_back(GetVertexLight(
461                                                 pos,
462                                                 buf.vertices[vtx],
463                                                 type.shape->VertexNormal(vtx - vtx_begin, BlockAt(idx).Transform())
464                                         ));
465                                 }
466                         }
467                 }
468         }
469
470         model.Update(buf);
471         ClearMesh();
472 }
473
474 Block::FaceSet Chunk::Obstructed(const Pos &pos) const noexcept {
475         Block::FaceSet result;
476
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))) {
481                         result.Set(face);
482                 }
483         }
484
485         return result;
486 }
487
488 glm::mat4 Chunk::ToTransform(const Pos &pos, int idx) const noexcept {
489         return glm::translate(ToCoords(pos)) * BlockAt(idx).Transform();
490 }
491
492
493 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p) noexcept
494 : chunk(c), pos(p) {
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;
499                 } else {
500                         chunk = nullptr;
501                         return;
502                 }
503         }
504         while (pos.x < 0) {
505                 if (chunk->HasNeighbor(Block::FACE_LEFT)) {
506                         chunk = &chunk->GetNeighbor(Block::FACE_LEFT);
507                         pos.x += Chunk::width;
508                 } else {
509                         chunk = nullptr;
510                         return;
511                 }
512         }
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;
517                 } else {
518                         chunk = nullptr;
519                         return;
520                 }
521         }
522         while (pos.y < 0) {
523                 if (chunk->HasNeighbor(Block::FACE_DOWN)) {
524                         chunk = &chunk->GetNeighbor(Block::FACE_DOWN);
525                         pos.y += Chunk::height;
526                 } else {
527                         chunk = nullptr;
528                         return;
529                 }
530         }
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;
535                 } else {
536                         chunk = nullptr;
537                         return;
538                 }
539         }
540         while (pos.z < 0) {
541                 if (chunk->HasNeighbor(Block::FACE_BACK)) {
542                         chunk = &chunk->GetNeighbor(Block::FACE_BACK);
543                         pos.z += Chunk::depth;
544                 } else {
545                         chunk = nullptr;
546                         return;
547                 }
548         }
549 }
550
551 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p, Block::Face face) noexcept
552 : chunk(c), pos(p) {
553         pos += Block::FaceNormal(face);
554         if (!Chunk::InBounds(pos)) {
555                 pos -= Block::FaceNormal(face) * Chunk::Extent();
556                 chunk = &chunk->GetNeighbor(face);
557         }
558 }
559
560
561 ChunkLoader::ChunkLoader(
562         ChunkStore &store,
563         const Generator &gen,
564         const WorldSave &save
565 ) noexcept
566 : store(store)
567 , gen(gen)
568 , save(save) {
569
570 }
571
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;
577         int loaded = 0;
578         int generated = 0;
579         while (loaded < max_load && generated < max_gen && store.HasMissing()) {
580                 if (LoadOne()) {
581                         ++generated;
582                 } else {
583                         ++loaded;
584                 }
585         }
586
587         // store a few chunks as well
588         constexpr int max_save = 10;
589         int saved = 0;
590         for (Chunk &chunk : store) {
591                 if (chunk.ShouldUpdateSave()) {
592                         save.Write(chunk);
593                         ++saved;
594                         if (saved >= max_save) {
595                                 break;
596                         }
597                 }
598         }
599 }
600
601 int ChunkLoader::ToLoad() const noexcept {
602         return store.EstimateMissing();
603 }
604
605 bool ChunkLoader::LoadOne() {
606         if (!store.HasMissing()) return false;
607
608         Chunk::Pos pos = store.NextMissing();
609         Chunk *chunk = store.Allocate(pos);
610         if (!chunk) {
611                 // chunk store corrupted?
612                 return false;
613         }
614
615         bool generated = false;
616         if (save.Exists(pos)) {
617                 save.Read(*chunk);
618         } else {
619                 gen(*chunk);
620                 generated = true;
621         }
622
623         ChunkIndex *index = store.ClosestIndex(pos);
624         if (!index) {
625                 return generated;
626         }
627
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();
638                                 }
639                         }
640                 }
641         }
642
643         return generated;
644 }
645
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) {
649                 LoadOne();
650         }
651 }
652
653
654 ChunkRenderer::ChunkRenderer(ChunkIndex &index)
655 : index(index)
656 , models(index.TotalChunks())
657 , block_tex()
658 , fog_density(0.0f) {
659
660 }
661
662 ChunkRenderer::~ChunkRenderer() {
663
664 }
665
666 int ChunkRenderer::MissingChunks() const noexcept {
667         return index.MissingChunks();
668 }
669
670 void ChunkRenderer::LoadTextures(const AssetLoader &loader, const TextureIndex &tex_index) {
671         block_tex.Bind();
672         loader.LoadTextures(tex_index, block_tex);
673         block_tex.FilterNearest();
674 }
675
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();
681                 }
682                 if (index[i]->ShouldUpdateMesh()) {
683                         index[i]->Update(models[i]);
684                         ++updates;
685                 }
686         }
687 }
688
689 void ChunkRenderer::Render(Viewport &viewport) {
690         BlockLighting &chunk_prog = viewport.ChunkProgram();
691         chunk_prog.SetTexture(block_tex);
692         chunk_prog.SetFogDensity(fog_density);
693
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]);
701                         }
702                         chunk_prog.SetM(m);
703                         models[i].Draw();
704                 }
705         }
706 }
707
708
709 ChunkIndex::ChunkIndex(ChunkStore &store, const Chunk::Pos &base, int extent)
710 : store(store)
711 , base(base)
712 , extent(extent)
713 , side_length(2 * extent + 1)
714 , total_length(side_length * side_length * side_length)
715 , total_indexed(0)
716 , last_missing(0)
717 , stride(1, side_length, side_length * side_length)
718 , chunks(total_length, nullptr) {
719         Scan();
720 }
721
722 ChunkIndex::~ChunkIndex() {
723         Clear();
724 }
725
726 bool ChunkIndex::InRange(const Chunk::Pos &pos) const noexcept {
727         return Distance(pos) <= extent;
728 }
729
730 bool ChunkIndex::IsBorder(const Chunk::Pos &pos) const noexcept {
731         return Distance(pos) == extent;
732 }
733
734 int ChunkIndex::Distance(const Chunk::Pos &pos) const noexcept {
735         return manhattan_radius(pos - base);
736 }
737
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;
745                         }
746                 }
747         }
748         return true;
749 }
750
751 int ChunkIndex::IndexOf(const Chunk::Pos &pos) const noexcept {
752         Chunk::Pos mod_pos(
753                 GetCol(pos.x),
754                 GetCol(pos.y),
755                 GetCol(pos.z)
756         );
757         return mod_pos.x * stride.x
758                 +  mod_pos.y * stride.y
759                 +  mod_pos.z * stride.z;
760 }
761
762 Chunk::Pos ChunkIndex::PositionOf(int i) const noexcept {
763         Chunk::Pos zero_pos(
764                 (i / stride.x) % side_length,
765                 (i / stride.y) % side_length,
766                 (i / stride.z) % side_length
767         );
768         Chunk::Pos zero_base(
769                 GetCol(base.x),
770                 GetCol(base.y),
771                 GetCol(base.z)
772         );
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;
781 }
782
783 Chunk *ChunkIndex::Get(const Chunk::Pos &pos) noexcept {
784         if (InRange(pos)) {
785                 return chunks[IndexOf(pos)];
786         } else {
787                 return nullptr;
788         }
789 }
790
791 const Chunk *ChunkIndex::Get(const Chunk::Pos &pos) const noexcept {
792         if (InRange(pos)) {
793                 return chunks[IndexOf(pos)];
794         } else {
795                 return nullptr;
796         }
797 }
798
799 void ChunkIndex::Rebase(const Chunk::Pos &new_base) {
800         if (new_base == base) return;
801
802         Chunk::Pos diff(new_base - base);
803
804         if (manhattan_radius(diff) > extent) {
805                 // that's more than half, so probably not worth shifting
806                 base = new_base;
807                 Clear();
808                 Scan();
809                 store.Clean();
810                 return;
811         }
812
813         while (diff.x > 0) {
814                 Shift(Block::FACE_RIGHT);
815                 --diff.x;
816         }
817         while (diff.x < 0) {
818                 Shift(Block::FACE_LEFT);
819                 ++diff.x;
820         }
821         while (diff.y > 0) {
822                 Shift(Block::FACE_UP);
823                 --diff.y;
824         }
825         while (diff.y < 0) {
826                 Shift(Block::FACE_DOWN);
827                 ++diff.y;
828         }
829         while (diff.z > 0) {
830                 Shift(Block::FACE_FRONT);
831                 --diff.z;
832         }
833         while (diff.z < 0) {
834                 Shift(Block::FACE_BACK);
835                 ++diff.z;
836         }
837         store.Clean();
838 }
839
840 int ChunkIndex::GetCol(int c) const noexcept {
841         c %= side_length;
842         if (c < 0) c += side_length;
843         return c;
844 }
845
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);
851         base[a_axis] += dir;
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;
859                         Unset(index);
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));
863                         }
864                 }
865         }
866 }
867
868 void ChunkIndex::Clear() noexcept {
869         for (int i = 0; i < total_length && total_indexed > 0; ++i) {
870                 Unset(i);
871         }
872 }
873
874 void ChunkIndex::Scan() noexcept {
875         for (Chunk &chunk : store) {
876                 Register(chunk);
877         }
878 }
879
880 void ChunkIndex::Register(Chunk &chunk) noexcept {
881         if (InRange(chunk.Position())) {
882                 Set(IndexOf(chunk.Position()), chunk);
883         }
884 }
885
886 void ChunkIndex::Set(int index, Chunk &chunk) noexcept {
887         Unset(index);
888         chunks[index] = &chunk;
889         chunk.Ref();
890         ++total_indexed;
891 }
892
893 void ChunkIndex::Unset(int index) noexcept {
894         if (chunks[index]) {
895                 chunks[index]->UnRef();
896                 chunks[index] = nullptr;
897                 --total_indexed;
898         }
899 }
900
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) {
908                                 break;
909                         }
910                 }
911         }
912         return PositionOf(last_missing);
913 }
914
915
916 ChunkStore::ChunkStore(const BlockTypeRegistry &types)
917 : types(types)
918 , loaded()
919 , free()
920 , indices() {
921
922 }
923
924 ChunkStore::~ChunkStore() {
925
926 }
927
928 ChunkIndex &ChunkStore::MakeIndex(const Chunk::Pos &pos, int extent) {
929         indices.emplace_back(*this, pos, extent);
930         return indices.back();
931 }
932
933 void ChunkStore::UnregisterIndex(ChunkIndex &index) {
934         for (auto i = indices.begin(), end = indices.end(); i != end; ++i) {
935                 if (&*i == &index) {
936                         indices.erase(i);
937                         return;
938                 } else {
939                         ++i;
940                 }
941         }
942 }
943
944 ChunkIndex *ChunkStore::ClosestIndex(const Chunk::Pos &pos) {
945         ChunkIndex *closest_index = nullptr;
946         int closest_distance = std::numeric_limits<int>::max();
947
948         for (ChunkIndex &index : indices) {
949                 int distance = index.Distance(pos);
950                 if (distance < closest_distance) {
951                         closest_index = &index;
952                         closest_distance = distance;
953                 }
954         }
955
956         return closest_index;
957 }
958
959 Chunk *ChunkStore::Get(const Chunk::Pos &pos) {
960         for (ChunkIndex &index : indices) {
961                 Chunk *chunk = index.Get(pos);
962                 if (chunk) {
963                         return chunk;
964                 }
965         }
966         return nullptr;
967 }
968
969 Chunk *ChunkStore::Allocate(const Chunk::Pos &pos) {
970         Chunk *chunk = Get(pos);
971         if (chunk) {
972                 return chunk;
973         }
974         if (free.empty()) {
975                 loaded.emplace(loaded.begin(), types);
976         } else {
977                 loaded.splice(loaded.begin(), free, free.begin());
978                 loaded.front().Unlink();
979         }
980         chunk = &loaded.front();
981         chunk->Position(pos);
982         for (ChunkIndex &index : indices) {
983                 if (index.InRange(pos)) {
984                         index.Register(*chunk);
985                 }
986         }
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);
991                 if (neighbor) {
992                         chunk->SetNeighbor(face, *neighbor);
993                 }
994         }
995         return chunk;
996 }
997
998 bool ChunkStore::HasMissing() const noexcept {
999         for (const ChunkIndex &index : indices) {
1000                 if (index.MissingChunks() > 0) {
1001                         return true;
1002                 }
1003         }
1004         return false;
1005 }
1006
1007 int ChunkStore::EstimateMissing() const noexcept {
1008         int missing = 0;
1009         for (const ChunkIndex &index : indices) {
1010                 missing += index.MissingChunks();
1011         }
1012         return missing;
1013 }
1014
1015 Chunk::Pos ChunkStore::NextMissing() noexcept {
1016         for (ChunkIndex &index : indices) {
1017                 if (index.MissingChunks()) {
1018                         return index.NextMissing();
1019                 }
1020         }
1021         return Chunk::Pos(0, 0, 0);
1022 }
1023
1024 void ChunkStore::Clean() {
1025         for (auto i = loaded.begin(), end = loaded.end(); i != end;) {
1026                 if (i->Referenced() || i->ShouldUpdateSave()) {
1027                         ++i;
1028                 } else {
1029                         auto chunk = i;
1030                         ++i;
1031                         free.splice(free.end(), loaded, chunk);
1032                         chunk->Unlink();
1033                         chunk->InvalidateMesh();
1034                 }
1035         }
1036 }
1037
1038 }