]> git.localhorst.tv Git - blank.git/blob - src/world.hpp
block type colors
[blank.git] / src / world.hpp
1 #ifndef BLANK_WORLD_HPP_
2 #define BLANK_WORLD_HPP_
3
4 #include "model.hpp"
5
6 #include <vector>
7 #include <GL/glew.h>
8 #include <glm/glm.hpp>
9
10
11 namespace blank {
12
13 /// attributes of a type of block
14 struct BlockType {
15
16         int id;
17
18         bool visible;
19         glm::vec3 color;
20
21         constexpr explicit BlockType(
22                 bool v = false,
23                 const glm::vec3 &color = { 1, 1, 1 })
24         : id(-1), visible(v), color(color) { }
25
26         static const BlockType DEFAULT;
27
28
29         void FillVBO(
30                 const glm::vec3 &pos,
31                 std::vector<glm::vec3> &vertices,
32                 std::vector<glm::vec3> &colors,
33                 std::vector<glm::vec3> &normals
34         ) const;
35
36         void FillModel(const glm::vec3 &pos, Model &m) const {
37                 FillVBO(pos, m.vertices, m.colors, m.normals);
38         }
39
40 };
41
42
43 class BlockTypeRegistry {
44
45 public:
46         BlockTypeRegistry();
47
48 public:
49         int Add(const BlockType &);
50
51         BlockType *operator [](int id) { return &types[id]; }
52         const BlockType *Get(int id) const { return &types[id]; }
53
54 private:
55         std::vector<BlockType> types;
56
57 };
58
59
60 /// single 1x1x1 cube
61 struct Block {
62
63         const BlockType *type;
64
65         constexpr explicit Block(const BlockType *t = &BlockType::DEFAULT)
66         : type(t) { }
67
68 };
69
70
71 /// cube of size 16 (256 tiles, 4096 blocks)
72 class Chunk {
73
74 public:
75         Chunk();
76
77         static constexpr int Width() { return 16; }
78         static constexpr int Height() { return 16; }
79         static constexpr int Depth() { return 16; }
80         static constexpr int Size() { return Width() * Height() * Depth(); }
81
82         static constexpr int ToIndex(const glm::vec3 &pos) {
83                 return pos.x + pos.y * Width() + pos.z * Width() * Height();
84         }
85         static glm::vec3 ToCoords(int idx) {
86                 return glm::vec3(
87                         idx % Width(),
88                         (idx / Width()) % Height(),
89                         idx / (Width() * Height())
90                 );
91         }
92
93         void Invalidate() { dirty = true; }
94
95         Block &BlockAt(const glm::vec3 &pos) { return blocks[ToIndex(pos)]; }
96         const Block &BlockAt(const glm::vec3 &pos) const { return blocks[ToIndex(pos)]; }
97
98         void Draw();
99
100 private:
101         int VertexCount() const;
102         void Update();
103
104 private:
105         std::vector<Block> blocks;
106         Model model;
107         bool dirty;
108
109 };
110
111 }
112
113 #endif