]> git.localhorst.tv Git - blank.git/blob - src/world/chunk.cpp
77899e79d5da360506502ae8954e54bf56648a3c
[blank.git] / src / world / chunk.cpp
1 #include "BlockLookup.hpp"
2 #include "Chunk.hpp"
3 #include "ChunkLoader.hpp"
4
5 #include "Generator.hpp"
6 #include "WorldCollision.hpp"
7
8 #include <algorithm>
9 #include <iostream>
10 #include <limits>
11 #include <queue>
12
13
14 namespace blank {
15
16 constexpr int Chunk::width;
17 constexpr int Chunk::height;
18 constexpr int Chunk::depth;
19 constexpr int Chunk::size;
20
21
22 Chunk::Chunk(const BlockTypeRegistry &types) noexcept
23 : types(&types)
24 , neighbor{0}
25 , blocks{}
26 , light{0}
27 , model()
28 , position(0, 0, 0)
29 , dirty(false) {
30
31 }
32
33 Chunk::Chunk(Chunk &&other) noexcept
34 : types(other.types)
35 , model(std::move(other.model))
36 , position(other.position)
37 , dirty(other.dirty) {
38         std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
39         std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
40         std::copy(other.light, other.light + sizeof(light), light);
41 }
42
43 Chunk &Chunk::operator =(Chunk &&other) noexcept {
44         types = other.types;
45         std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
46         std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
47         std::copy(other.light, other.light + sizeof(light), light);
48         model = std::move(other.model);
49         position = other.position;
50         dirty = other.dirty;
51         return *this;
52 }
53
54
55 namespace {
56
57 struct SetNode {
58
59         Chunk *chunk;
60         Chunk::Pos pos;
61
62         SetNode(Chunk *chunk, Chunk::Pos pos)
63         : chunk(chunk), pos(pos) { }
64
65         int Get() const noexcept { return chunk->GetLight(pos); }
66         void Set(int level) noexcept { chunk->SetLight(pos, level); }
67
68         const BlockType &GetType() const noexcept { return chunk->Type(Chunk::ToIndex(pos)); }
69
70         bool HasNext(Block::Face face) noexcept {
71                 const BlockType &type = GetType();
72                 if (type.block_light && !type.luminosity) return false;
73                 const BlockLookup next(chunk, pos, face);
74                 return next;
75         }
76         SetNode GetNext(Block::Face face) noexcept {
77                 const BlockLookup next(chunk, pos, face);
78                 return SetNode(&next.GetChunk(), next.GetBlockPos());
79         }
80
81 };
82
83 struct UnsetNode
84 : public SetNode {
85
86         int level;
87
88         UnsetNode(Chunk *chunk, Chunk::Pos pos)
89         : SetNode(chunk, pos), level(Get()) { }
90
91         UnsetNode(const SetNode &set)
92         : SetNode(set), level(Get()) { }
93
94
95         bool HasNext(Block::Face face) noexcept {
96                 const BlockLookup next(chunk, pos, face);
97                 return next;
98         }
99         UnsetNode GetNext(Block::Face face) noexcept { return UnsetNode(SetNode::GetNext(face)); }
100
101 };
102
103 std::queue<SetNode> light_queue;
104 std::queue<UnsetNode> dark_queue;
105
106 void work_light() noexcept {
107         while (!light_queue.empty()) {
108                 SetNode node = light_queue.front();
109                 light_queue.pop();
110
111                 int level = node.Get() - 1;
112                 for (int face = 0; face < Block::FACE_COUNT; ++face) {
113                         if (node.HasNext(Block::Face(face))) {
114                                 SetNode other = node.GetNext(Block::Face(face));
115                                 if (other.Get() < level) {
116                                         other.Set(level);
117                                         light_queue.emplace(other);
118                                 }
119                         }
120                 }
121         }
122 }
123
124 void work_dark() noexcept {
125         while (!dark_queue.empty()) {
126                 UnsetNode node = dark_queue.front();
127                 dark_queue.pop();
128
129                 for (int face = 0; face < Block::FACE_COUNT; ++face) {
130                         if (node.HasNext(Block::Face(face))) {
131                                 UnsetNode other = node.GetNext(Block::Face(face));
132                                 // TODO: if there a light source here with the same level this will err
133                                 if (other.Get() != 0 && other.Get() < node.level) {
134                                         other.Set(0);
135                                         dark_queue.emplace(other);
136                                 } else {
137                                         light_queue.emplace(other);
138                                 }
139                         }
140                 }
141         }
142 }
143
144 }
145
146 void Chunk::SetBlock(int index, const Block &block) noexcept {
147         const BlockType &old_type = Type(blocks[index]);
148         const BlockType &new_type = Type(block);
149
150         blocks[index] = block;
151
152         if (&old_type == &new_type) return;
153
154         if (new_type.luminosity > old_type.luminosity) {
155                 // light added
156                 SetLight(index, new_type.luminosity);
157                 light_queue.emplace(this, ToPos(index));
158                 work_light();
159         } else if (new_type.luminosity < old_type.luminosity) {
160                 // light removed
161                 dark_queue.emplace(this, ToPos(index));
162                 SetLight(index, 0);
163                 work_dark();
164                 SetLight(index, new_type.luminosity);
165                 light_queue.emplace(this, ToPos(index));
166                 work_light();
167         } else if (new_type.block_light && !old_type.block_light) {
168                 // obstacle added
169                 if (GetLight(index) > 0) {
170                         dark_queue.emplace(this, ToPos(index));
171                         SetLight(index, 0);
172                         work_dark();
173                         work_light();
174                 }
175         } else if (!new_type.block_light && old_type.block_light) {
176                 // obstacle removed
177                 int level = 0;
178                 Pos pos(ToPos(index));
179                 for (int face = 0; face < Block::FACE_COUNT; ++face) {
180                         BlockLookup next_block(this, pos, Block::Face(face));
181                         if (next_block) {
182                                 level = std::max(level, next_block.GetLight());
183                         }
184                 }
185                 if (level > 1) {
186                         SetLight(index, level - 1);
187                         light_queue.emplace(this, pos);
188                         work_light();
189                 }
190         }
191 }
192
193 namespace {
194
195 // propagate light from a's edge to b
196 void edge_light(
197         Chunk &a, const Chunk::Pos &a_pos,
198         Chunk &b, const Chunk::Pos &b_pos
199 ) noexcept {
200         if (a.GetLight(a_pos) > 1) {
201                 const BlockType &b_type = b.Type(Chunk::ToIndex(b_pos));
202                 if (!b_type.block_light) {
203                         light_queue.emplace(&a, a_pos);
204                 }
205                 if (b_type.visible) {
206                         b.Invalidate();
207                 }
208         }
209 }
210
211 }
212
213 void Chunk::SetNeighbor(Chunk &other) noexcept {
214         if (other.position == position + Pos(-1, 0, 0)) {
215                 if (neighbor[Block::FACE_LEFT] != &other) {
216                         neighbor[Block::FACE_LEFT] = &other;
217                         other.neighbor[Block::FACE_RIGHT] = this;
218                         for (int z = 0; z < depth; ++z) {
219                                 for (int y = 0; y < height; ++y) {
220                                         Pos my_pos(0, y, z);
221                                         Pos other_pos(width - 1, y, z);
222                                         edge_light(*this, my_pos, other, other_pos);
223                                         edge_light(other, other_pos, *this, my_pos);
224                                 }
225                         }
226                         work_light();
227                 }
228         } else if (other.position == position + Pos(1, 0, 0)) {
229                 if (neighbor[Block::FACE_RIGHT] != &other) {
230                         neighbor[Block::FACE_RIGHT] = &other;
231                         other.neighbor[Block::FACE_LEFT] = this;
232                         for (int z = 0; z < depth; ++z) {
233                                 for (int y = 0; y < height; ++y) {
234                                         Pos my_pos(width - 1, y, z);
235                                         Pos other_pos(0, y, z);
236                                         edge_light(*this, my_pos, other, other_pos);
237                                         edge_light(other, other_pos, *this, my_pos);
238                                 }
239                         }
240                         work_light();
241                 }
242         } else if (other.position == position + Pos(0, -1, 0)) {
243                 if (neighbor[Block::FACE_DOWN] != &other) {
244                         neighbor[Block::FACE_DOWN] = &other;
245                         other.neighbor[Block::FACE_UP] = this;
246                         for (int z = 0; z < depth; ++z) {
247                                 for (int x = 0; x < width; ++x) {
248                                         Pos my_pos(x, 0, z);
249                                         Pos other_pos(x, height - 1, z);
250                                         edge_light(*this, my_pos, other, other_pos);
251                                         edge_light(other, other_pos, *this, my_pos);
252                                 }
253                         }
254                         work_light();
255                 }
256         } else if (other.position == position + Pos(0, 1, 0)) {
257                 if (neighbor[Block::FACE_UP] != &other) {
258                         neighbor[Block::FACE_UP] = &other;
259                         other.neighbor[Block::FACE_DOWN] = this;
260                         for (int z = 0; z < depth; ++z) {
261                                 for (int x = 0; x < width; ++x) {
262                                         Pos my_pos(x, height - 1, z);
263                                         Pos other_pos(x, 0, z);
264                                         edge_light(*this, my_pos, other, other_pos);
265                                         edge_light(other, other_pos, *this, my_pos);
266                                 }
267                         }
268                         work_light();
269                 }
270         } else if (other.position == position + Pos(0, 0, -1)) {
271                 if (neighbor[Block::FACE_BACK] != &other) {
272                         neighbor[Block::FACE_BACK] = &other;
273                         other.neighbor[Block::FACE_FRONT] = this;
274                         for (int y = 0; y < height; ++y) {
275                                 for (int x = 0; x < width; ++x) {
276                                         Pos my_pos(x, y, 0);
277                                         Pos other_pos(x, y, depth - 1);
278                                         edge_light(*this, my_pos, other, other_pos);
279                                         edge_light(other, other_pos, *this, my_pos);
280                                 }
281                         }
282                         work_light();
283                 }
284         } else if (other.position == position + Pos(0, 0, 1)) {
285                 if (neighbor[Block::FACE_FRONT] != &other) {
286                         neighbor[Block::FACE_FRONT] = &other;
287                         other.neighbor[Block::FACE_BACK] = this;
288                         for (int y = 0; y < height; ++y) {
289                                 for (int x = 0; x < width; ++x) {
290                                         Pos my_pos(x, y, depth - 1);
291                                         Pos other_pos(x, y, 0);
292                                         edge_light(*this, my_pos, other, other_pos);
293                                         edge_light(other, other_pos, *this, my_pos);
294                                 }
295                         }
296                         work_light();
297                 }
298         }
299 }
300
301 void Chunk::ClearNeighbors() noexcept {
302         for (int face = 0; face < Block::FACE_COUNT; ++face) {
303                 if (neighbor[face]) {
304                         neighbor[face]->neighbor[Block::Opposite(Block::Face(face))] = nullptr;
305                         neighbor[face] = nullptr;
306                 }
307         }
308 }
309
310
311 void Chunk::SetLight(int index, int level) noexcept {
312         if (light[index] != level) {
313                 light[index] = level;
314                 Invalidate();
315         }
316 }
317
318 int Chunk::GetLight(int index) const noexcept {
319         return light[index];
320 }
321
322 float Chunk::GetVertexLight(const Pos &pos, const BlockModel::Position &vtx, const EntityModel::Normal &norm) const noexcept {
323         int index = ToIndex(pos);
324         float light = GetLight(index);
325
326         Block::Face direct_face(Block::NormalFace(norm));
327         // tis okay
328         BlockLookup direct(const_cast<Chunk *>(this), pos, Block::NormalFace(norm));
329         if (direct) {
330                 float direct_light = direct.GetLight();
331                 if (direct_light > light) {
332                         light = direct_light;
333                 }
334         } else {
335                 return light;
336         }
337
338         if (Type(BlockAt(index)).luminosity > 0 || direct.GetType().block_light) {
339                 return light;
340         }
341
342         Block::Face edge[2];
343         switch (Block::Axis(direct_face)) {
344                 case 0: // X
345                         edge[0] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
346                         edge[1] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
347                         break;
348                 case 1: // Y
349                         edge[0] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
350                         edge[1] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
351                         break;
352                 case 2: // Z
353                         edge[0] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
354                         edge[1] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
355                         break;
356         }
357
358         int num = 1;
359         int occlusion = 0;
360
361         BlockLookup next[2] = {
362                 direct.Next(edge[0]),
363                 direct.Next(edge[1]),
364         };
365
366         if (next[0]) {
367                 if (next[0].GetType().block_light) {
368                         ++occlusion;
369                 } else {
370                         light += next[0].GetLight();
371                         ++num;
372                 }
373         }
374         if (next[1]) {
375                 if (next[1].GetType().block_light) {
376                         ++occlusion;
377                 } else {
378                         light += next[1].GetLight();
379                         ++num;
380                 }
381         }
382         if (occlusion < 2) {
383                 if (next[0]) {
384                         BlockLookup corner = next[0].Next(edge[1]);
385                         if (corner) {
386                                 if (corner.GetType().block_light) {
387                                         ++occlusion;
388                                 } else {
389                                         light += corner.GetLight();
390                                         ++num;
391                                 }
392                         }
393                 } else if (next[1]) {
394                         BlockLookup corner = next[1].Next(edge[0]);
395                         if (corner) {
396                                 if (corner.GetType().block_light) {
397                                         ++occlusion;
398                                 } else {
399                                         light += corner.GetLight();
400                                         ++num;
401                                 }
402                         }
403                 }
404         } else {
405                 ++occlusion;
406         }
407
408         return (light / num) - (occlusion * 0.8f);
409 }
410
411
412 bool Chunk::IsSurface(const Pos &pos) const noexcept {
413         const Block &block = BlockAt(pos);
414         if (!Type(block).visible) {
415                 return false;
416         }
417         for (int face = 0; face < Block::FACE_COUNT; ++face) {
418                 BlockLookup next = BlockLookup(const_cast<Chunk *>(this), pos, Block::Face(face));
419                 if (!next || !next.GetType().visible) {
420                         return true;
421                 }
422         }
423         return false;
424 }
425
426
427 void Chunk::Draw() noexcept {
428         if (dirty) {
429                 Update();
430         }
431         model.Draw();
432 }
433
434
435 bool Chunk::Intersection(
436         const Ray &ray,
437         const glm::mat4 &M,
438         int &blkid,
439         float &dist,
440         glm::vec3 &normal
441 ) const noexcept {
442         int idx = 0;
443         blkid = -1;
444         dist = std::numeric_limits<float>::infinity();
445         for (int z = 0; z < depth; ++z) {
446                 for (int y = 0; y < height; ++y) {
447                         for (int x = 0; x < width; ++x, ++idx) {
448                                 const BlockType &type = Type(idx);
449                                 if (!type.visible) {
450                                         continue;
451                                 }
452                                 float cur_dist;
453                                 glm::vec3 cur_norm;
454                                 if (type.shape->Intersects(ray, M * ToTransform(Pos(x, y, z), idx), cur_dist, cur_norm)) {
455                                         if (cur_dist < dist) {
456                                                 blkid = idx;
457                                                 dist = cur_dist;
458                                                 normal = cur_norm;
459                                         }
460                                 }
461                         }
462                 }
463         }
464
465         if (blkid < 0) {
466                 return false;
467         } else {
468                 normal = glm::vec3(BlockAt(blkid).Transform() * glm::vec4(normal, 0.0f));
469                 return true;
470         }
471 }
472
473 bool Chunk::Intersection(
474         const AABB &box,
475         const glm::mat4 &Mbox,
476         const glm::mat4 &Mchunk,
477         std::vector<WorldCollision> &col
478 ) const noexcept {
479         bool any = false;
480         float penetration;
481         glm::vec3 normal;
482
483         if (!blank::Intersection(box, Mbox, Bounds(), Mchunk, penetration, normal)) {
484                 return false;
485         }
486         for (int idx = 0, z = 0; z < depth; ++z) {
487                 for (int y = 0; y < height; ++y) {
488                         for (int x = 0; x < width; ++x, ++idx) {
489                                 const BlockType &type = Type(idx);
490                                 if (!type.collision) {
491                                         continue;
492                                 }
493                                 if (type.shape->Intersects(Mchunk * ToTransform(Pos(x, y, z), idx), box, Mbox, penetration, normal)) {
494                                         col.emplace_back(this, idx, penetration, normal);
495                                         any = true;
496                                 }
497                         }
498                 }
499         }
500         return any;
501 }
502
503
504 namespace {
505
506 BlockModel::Buffer buf;
507
508 }
509
510 void Chunk::CheckUpdate() noexcept {
511         if (dirty) {
512                 Update();
513         }
514 }
515
516 void Chunk::Update() noexcept {
517         int vtx_count = 0, idx_count = 0;
518         for (const auto &block : blocks) {
519                 const Shape *shape = Type(block).shape;
520                 vtx_count += shape->VertexCount();
521                 idx_count += shape->VertexIndexCount();
522         }
523         buf.Clear();
524         buf.Reserve(vtx_count, idx_count);
525
526         int idx = 0;
527         BlockModel::Index vtx_counter = 0;
528         for (size_t z = 0; z < depth; ++z) {
529                 for (size_t y = 0; y < height; ++y) {
530                         for (size_t x = 0; x < width; ++x, ++idx) {
531                                 const BlockType &type = Type(BlockAt(idx));
532                                 const Pos pos(x, y, z);
533
534                                 if (!type.visible || Obstructed(pos).All()) continue;
535
536                                 type.FillBlockModel(buf, ToTransform(pos, idx), vtx_counter);
537                                 size_t vtx_begin = vtx_counter;
538                                 vtx_counter += type.shape->VertexCount();
539
540                                 for (size_t vtx = vtx_begin; vtx < vtx_counter; ++vtx) {
541                                         buf.lights.emplace_back(GetVertexLight(
542                                                 pos,
543                                                 buf.vertices[vtx],
544                                                 type.shape->VertexNormal(vtx - vtx_begin, BlockAt(idx).Transform())
545                                         ));
546                                 }
547                         }
548                 }
549         }
550
551         model.Update(buf);
552         dirty = false;
553 }
554
555 Block::FaceSet Chunk::Obstructed(const Pos &pos) const noexcept {
556         Block::FaceSet result;
557
558         for (int f = 0; f < Block::FACE_COUNT; ++f) {
559                 Block::Face face = Block::Face(f);
560                 BlockLookup next(const_cast<Chunk *>(this), pos, face);
561                 if (next && next.GetType().FaceFilled(next.GetBlock(), Block::Opposite(face))) {
562                         result.Set(face);
563                 }
564         }
565
566         return result;
567 }
568
569 glm::mat4 Chunk::ToTransform(const Pos &pos, int idx) const noexcept {
570         return glm::translate(ToCoords(pos)) * BlockAt(idx).Transform();
571 }
572
573
574 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p) noexcept
575 : chunk(c), pos(p) {
576         while (pos.x >= Chunk::width) {
577                 if (chunk->HasNeighbor(Block::FACE_RIGHT)) {
578                         chunk = &chunk->GetNeighbor(Block::FACE_RIGHT);
579                         pos.x -= Chunk::width;
580                 } else {
581                         chunk = nullptr;
582                         return;
583                 }
584         }
585         while (pos.x < 0) {
586                 if (chunk->HasNeighbor(Block::FACE_LEFT)) {
587                         chunk = &chunk->GetNeighbor(Block::FACE_LEFT);
588                         pos.x += Chunk::width;
589                 } else {
590                         chunk = nullptr;
591                         return;
592                 }
593         }
594         while (pos.y >= Chunk::height) {
595                 if (chunk->HasNeighbor(Block::FACE_UP)) {
596                         chunk = &chunk->GetNeighbor(Block::FACE_UP);
597                         pos.y -= Chunk::height;
598                 } else {
599                         chunk = nullptr;
600                         return;
601                 }
602         }
603         while (pos.y < 0) {
604                 if (chunk->HasNeighbor(Block::FACE_DOWN)) {
605                         chunk = &chunk->GetNeighbor(Block::FACE_DOWN);
606                         pos.y += Chunk::height;
607                 } else {
608                         chunk = nullptr;
609                         return;
610                 }
611         }
612         while (pos.z >= Chunk::depth) {
613                 if (chunk->HasNeighbor(Block::FACE_FRONT)) {
614                         chunk = &chunk->GetNeighbor(Block::FACE_FRONT);
615                         pos.z -= Chunk::depth;
616                 } else {
617                         chunk = nullptr;
618                         return;
619                 }
620         }
621         while (pos.z < 0) {
622                 if (chunk->HasNeighbor(Block::FACE_BACK)) {
623                         chunk = &chunk->GetNeighbor(Block::FACE_BACK);
624                         pos.z += Chunk::depth;
625                 } else {
626                         chunk = nullptr;
627                         return;
628                 }
629         }
630 }
631
632 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p, Block::Face face) noexcept
633 : chunk(c), pos(p) {
634         pos += Block::FaceNormal(face);
635         if (!Chunk::InBounds(pos)) {
636                 pos -= Block::FaceNormal(face) * Chunk::Extent();
637                 chunk = &chunk->GetNeighbor(face);
638         }
639 }
640
641
642 ChunkLoader::ChunkLoader(const Config &config, const BlockTypeRegistry &reg, const Generator &gen) noexcept
643 : base(0, 0, 0)
644 , reg(reg)
645 , gen(gen)
646 , loaded()
647 , to_generate()
648 , to_free()
649 , gen_timer(config.gen_limit)
650 , load_dist(config.load_dist)
651 , unload_dist(config.unload_dist) {
652         gen_timer.Start();
653 }
654
655 namespace {
656
657 struct ChunkLess {
658
659         explicit ChunkLess(const Chunk::Pos &base) noexcept
660         : base(base) { }
661
662         bool operator ()(const Chunk::Pos &a, const Chunk::Pos &b) const noexcept {
663                 Chunk::Pos da(base - a);
664                 Chunk::Pos db(base - b);
665                 return
666                         da.x * da.x + da.y * da.y + da.z * da.z <
667                         db.x * db.x + db.y * db.y + db.z * db.z;
668         }
669
670         Chunk::Pos base;
671
672 };
673
674 }
675
676 void ChunkLoader::Generate(const Chunk::Pos &from, const Chunk::Pos &to) {
677         for (int z = from.z; z < to.z; ++z) {
678                 for (int y = from.y; y < to.y; ++y) {
679                         for (int x = from.x; x < to.x; ++x) {
680                                 Chunk::Pos pos(x, y, z);
681                                 if (Known(pos)) {
682                                         continue;
683                                 } else if (pos == base) {
684                                         Generate(pos);
685
686                                 //      light testing
687                                 //      for (int i = 0; i < 16; ++i) {
688                                 //              for (int j = 0; j < 16; ++j) {
689                                 //                      loaded.back().SetBlock(Chunk::Pos{  i, j,  0 }, Block(1));
690                                 //                      loaded.back().SetBlock(Chunk::Pos{  i, j, 15 }, Block(1));
691                                 //                      loaded.back().SetBlock(Chunk::Pos{  0, j,  i }, Block(1));
692                                 //                      loaded.back().SetBlock(Chunk::Pos{ 15, j,  i }, Block(1));
693                                 //              }
694                                 //      }
695                                 //      loaded.back().SetBlock(Chunk::Pos{  1,  0,  1 }, Block(13));
696                                 //      loaded.back().SetBlock(Chunk::Pos{ 14,  0,  1 }, Block(13));
697                                 //      loaded.back().SetBlock(Chunk::Pos{  1,  0, 14 }, Block(13));
698                                 //      loaded.back().SetBlock(Chunk::Pos{ 14,  0, 14 }, Block(13));
699                                 //      loaded.back().SetBlock(Chunk::Pos{  1, 15,  1 }, Block(13));
700                                 //      loaded.back().SetBlock(Chunk::Pos{ 14, 15,  1 }, Block(13));
701                                 //      loaded.back().SetBlock(Chunk::Pos{  1, 15, 14 }, Block(13));
702                                 //      loaded.back().SetBlock(Chunk::Pos{ 14, 15, 14 }, Block(13));
703                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  7,  0 }, Block(13));
704                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  7,  0 }, Block(13));
705                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  8,  0 }, Block(13));
706                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  8,  0 }, Block(13));
707                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  7, 15 }, Block(13));
708                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  7, 15 }, Block(13));
709                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  8, 15 }, Block(13));
710                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  8, 15 }, Block(13));
711                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  7,  7 }, Block(13));
712                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  7,  8 }, Block(13));
713                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  8,  7 }, Block(13));
714                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  8,  8 }, Block(13));
715                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  7,  7 }, Block(13));
716                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  7,  8 }, Block(13));
717                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  8,  7 }, Block(13));
718                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  8,  8 }, Block(13));
719                                 //      loaded.back().Invalidate();
720                                 //      loaded.back().CheckUpdate();
721
722                                 //      orientation testing
723                                 //      for (int i = 0; i < Block::FACE_COUNT; ++i) {
724                                 //              for (int j = 0; j < Block::TURN_COUNT; ++j) {
725                                 //                      loaded.back().BlockAt(512 * j + 2 * i) = Block(3 * (j + 1), Block::Face(i), Block::Turn(j));
726                                 //              }
727                                 //      }
728                                 //      loaded.back().Invalidate();
729                                 //      loaded.back().CheckUpdate();
730                                 } else {
731                                         to_generate.emplace_back(pos);
732                                 }
733                         }
734                 }
735         }
736         to_generate.sort(ChunkLess(base));
737 }
738
739 Chunk &ChunkLoader::Generate(const Chunk::Pos &pos) {
740         loaded.emplace_back(reg);
741         Chunk &chunk = loaded.back();
742         chunk.Position(pos);
743         gen(chunk);
744         Insert(chunk);
745         return chunk;
746 }
747
748 void ChunkLoader::Insert(Chunk &chunk) noexcept {
749         for (Chunk &other : loaded) {
750                 chunk.SetNeighbor(other);
751         }
752 }
753
754 std::list<Chunk>::iterator ChunkLoader::Remove(std::list<Chunk>::iterator chunk) noexcept {
755         // fetch next entry while chunk's still in the list
756         std::list<Chunk>::iterator next = chunk;
757         ++next;
758         // unlink neighbors so they won't reference a dead chunk
759         chunk->ClearNeighbors();
760         // and move it from loaded to free list
761         to_free.splice(to_free.end(), loaded, chunk);
762         return next;
763 }
764
765 Chunk *ChunkLoader::Loaded(const Chunk::Pos &pos) noexcept {
766         for (Chunk &chunk : loaded) {
767                 if (chunk.Position() == pos) {
768                         return &chunk;
769                 }
770         }
771         return nullptr;
772 }
773
774 bool ChunkLoader::Queued(const Chunk::Pos &pos) noexcept {
775         for (const Chunk::Pos &chunk : to_generate) {
776                 if (chunk == pos) {
777                         return true;
778                 }
779         }
780         return false;
781 }
782
783 bool ChunkLoader::Known(const Chunk::Pos &pos) noexcept {
784         if (Loaded(pos)) return true;
785         return Queued(pos);
786 }
787
788 Chunk &ChunkLoader::ForceLoad(const Chunk::Pos &pos) {
789         Chunk *chunk = Loaded(pos);
790         if (chunk) {
791                 return *chunk;
792         }
793
794         for (auto iter(to_generate.begin()), end(to_generate.end()); iter != end; ++iter) {
795                 if (*iter == pos) {
796                         to_generate.erase(iter);
797                         break;
798                 }
799         }
800
801         return Generate(pos);
802 }
803
804 bool ChunkLoader::OutOfRange(const Chunk::Pos &pos) const noexcept {
805         return std::abs(base.x - pos.x) > unload_dist
806                         || std::abs(base.y - pos.y) > unload_dist
807                         || std::abs(base.z - pos.z) > unload_dist;
808 }
809
810 void ChunkLoader::Rebase(const Chunk::Pos &new_base) {
811         if (new_base == base) {
812                 return;
813         }
814         base = new_base;
815
816         // unload far away chunks
817         for (auto iter(loaded.begin()), end(loaded.end()); iter != end;) {
818                 if (OutOfRange(*iter)) {
819                         iter = Remove(iter);
820                 } else {
821                         ++iter;
822                 }
823         }
824         // abort far away queued chunks
825         for (auto iter(to_generate.begin()), end(to_generate.end()); iter != end;) {
826                 if (OutOfRange(*iter)) {
827                         iter = to_generate.erase(iter);
828                 } else {
829                         ++iter;
830                 }
831         }
832         // add missing new chunks
833         GenerateSurrounding(base);
834 }
835
836 void ChunkLoader::GenerateSurrounding(const Chunk::Pos &pos) {
837         const Chunk::Pos offset(load_dist, load_dist, load_dist);
838         Generate(pos - offset, pos + offset);
839 }
840
841 void ChunkLoader::Update(int dt) {
842         // check if a chunk generation is scheduled for this frame
843         // and if there's a chunk waiting to be generated
844         gen_timer.Update(dt);
845         if (gen_timer.Hit()) {
846                 LoadOne();
847         }
848 }
849
850 void ChunkLoader::LoadN(std::size_t n) {
851         std::size_t end = std::min(n, ToLoad());
852         for (std::size_t i = 0; i < end; ++i) {
853                 LoadOne();
854         }
855 }
856
857 void ChunkLoader::LoadOne() {
858         if (to_generate.empty()) return;
859
860         // take position of next chunk in queue
861         Chunk::Pos pos(to_generate.front());
862         to_generate.pop_front();
863
864         // look if the same chunk was already generated and still lingering
865         for (auto iter(to_free.begin()), end(to_free.end()); iter != end; ++iter) {
866                 if (iter->Position() == pos) {
867                         loaded.splice(loaded.end(), to_free, iter);
868                         Insert(loaded.back());
869                         return;
870                 }
871         }
872
873         // if the free list is empty, allocate a new chunk
874         // otherwise clear an unused one
875         if (to_free.empty()) {
876                 loaded.emplace_back(reg);
877         } else {
878                 to_free.front().ClearNeighbors();
879                 loaded.splice(loaded.end(), to_free, to_free.begin());
880         }
881
882         Chunk &chunk = loaded.back();
883         chunk.Position(pos);
884         gen(chunk);
885         Insert(chunk);
886 }
887
888 }