]> git.localhorst.tv Git - blank.git/blob - src/chunk.hpp
limit chunks allocated/freed per frame
[blank.git] / src / chunk.hpp
1 #ifndef BLANK_CHUNK_HPP_
2 #define BLANK_CHUNK_HPP_
3
4 #include "block.hpp"
5 #include "geometry.hpp"
6 #include "model.hpp"
7
8 #include <vector>
9 #include <glm/glm.hpp>
10
11
12 namespace blank {
13
14 /// cube of size 16 (256 tiles, 4096 blocks)
15 class Chunk {
16
17 public:
18         Chunk();
19
20         Chunk(Chunk &&);
21         Chunk &operator =(Chunk &&);
22
23         static constexpr int Width() { return 16; }
24         static constexpr int Height() { return 16; }
25         static constexpr int Depth() { return 16; }
26         static glm::tvec3<int> Extent() { return { Width(), Height(), Depth() }; }
27         static constexpr int Size() { return Width() * Height() * Depth(); }
28
29         static AABB Bounds() { return AABB{ { 0, 0, 0 }, Extent() }; }
30
31         static constexpr bool InBounds(const glm::vec3 &pos) {
32                 return
33                         pos.x >= 0 && pos.x < Width() &&
34                         pos.y >= 0 && pos.y < Height() &&
35                         pos.z >= 0 && pos.z < Depth();
36         }
37         static constexpr int ToIndex(const glm::vec3 &pos) {
38                 return int(pos.x) + int(pos.y) * Width() + int(pos.z) * Width() * Height();
39         }
40         static constexpr bool InBounds(int idx) {
41                 return idx >= 0 && idx < Size();
42         }
43         static glm::vec3 ToCoords(int idx) {
44                 return glm::vec3(
45                         0.5f + idx % Width(),
46                         0.5f + (idx / Width()) % Height(),
47                         0.5f + idx / (Width() * Height())
48                 );
49         }
50
51         void Allocate();
52         void Invalidate() { dirty = true; }
53
54         Block &BlockAt(int index) { return blocks[index]; }
55         const Block &BlockAt(int index) const { return blocks[index]; }
56         Block &BlockAt(const glm::vec3 &pos) { return BlockAt(ToIndex(pos)); }
57         const Block &BlockAt(const glm::vec3 &pos) const { return BlockAt(ToIndex(pos)); }
58
59         bool Intersection(
60                 const Ray &,
61                 const glm::mat4 &M,
62                 int *blkid = nullptr,
63                 float *dist = nullptr,
64                 glm::vec3 *normal = nullptr) const;
65
66         void Position(const glm::tvec3<int> &);
67         const glm::tvec3<int> &Position() const { return position; }
68         glm::mat4 Transform(const glm::tvec3<int> &offset) const;
69
70         void Draw();
71
72 private:
73         int VertexCount() const;
74         void Update();
75
76 private:
77         std::vector<Block> blocks;
78         Model model;
79         glm::tvec3<int> position;
80         bool dirty;
81
82 };
83
84 }
85
86 #endif