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