]> git.localhorst.tv Git - blank.git/blob - src/world/world.cpp
fixed some initialization issues
[blank.git] / src / world / world.cpp
1 #include "Entity.hpp"
2 #include "EntityState.hpp"
3 #include "Player.hpp"
4 #include "World.hpp"
5
6 #include "ChunkIndex.hpp"
7 #include "EntityCollision.hpp"
8 #include "WorldCollision.hpp"
9 #include "../app/Assets.hpp"
10 #include "../graphics/Format.hpp"
11 #include "../graphics/Viewport.hpp"
12
13 #include <algorithm>
14 #include <cmath>
15 #include <limits>
16 #include <glm/gtx/io.hpp>
17 #include <glm/gtx/quaternion.hpp>
18 #include <glm/gtx/transform.hpp>
19
20
21 namespace blank {
22
23 Entity::Entity() noexcept
24 : model()
25 , id(-1)
26 , name("anonymous")
27 , bounds()
28 , state()
29 , ref_count(0)
30 , world_collision(false)
31 , dead(false) {
32
33 }
34
35
36 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
37         state.chunk_pos = c;
38         state.block_pos = b;
39 }
40
41 void Entity::Position(const glm::vec3 &pos) noexcept {
42         state.block_pos = pos;
43         state.AdjustPosition();
44 }
45
46 Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
47         glm::mat4 transform = Transform(chunk_offset);
48         glm::vec4 from = transform * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
49         from /= from.w;
50         glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
51         to /= to.w;
52         return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
53 }
54
55 namespace {
56
57 glm::quat delta_rot(const glm::vec3 &av, float dt) {
58         glm::vec3 half(av * dt * 0.5f);
59         float mag = length(half);
60         if (mag > 0.0f) {
61                 float smag = std::sin(mag) / mag;
62                 return glm::quat(std::cos(mag), half * smag);
63         } else {
64                 return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
65         }
66 }
67
68 }
69
70 void Entity::Update(int dt) noexcept {
71         state.Update(dt);
72 }
73
74
75 EntityState::EntityState()
76 : chunk_pos(0)
77 , block_pos(0.0f)
78 , velocity(0.0f)
79 , orient(1.0f, 0.0f, 0.0f, 0.0f)
80 , ang_vel(0.0f) {
81
82 }
83
84 void EntityState::Update(int dt) noexcept {
85         float fdt = float(dt);
86         block_pos += velocity * fdt;
87         orient = delta_rot(ang_vel, fdt) * orient;
88         AdjustPosition();
89 }
90
91 void EntityState::AdjustPosition() noexcept {
92         while (block_pos.x >= Chunk::width) {
93                 block_pos.x -= Chunk::width;
94                 ++chunk_pos.x;
95         }
96         while (block_pos.x < 0) {
97                 block_pos.x += Chunk::width;
98                 --chunk_pos.x;
99         }
100         while (block_pos.y >= Chunk::height) {
101                 block_pos.y -= Chunk::height;
102                 ++chunk_pos.y;
103         }
104         while (block_pos.y < 0) {
105                 block_pos.y += Chunk::height;
106                 --chunk_pos.y;
107         }
108         while (block_pos.z >= Chunk::depth) {
109                 block_pos.z -= Chunk::depth;
110                 ++chunk_pos.z;
111         }
112         while (block_pos.z < 0) {
113                 block_pos.z += Chunk::depth;
114                 --chunk_pos.z;
115         }
116 }
117
118 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
119         const glm::vec3 translation = RelativePosition(reference);
120         glm::mat4 transform(toMat4(orient));
121         transform[3].x = translation.x;
122         transform[3].y = translation.y;
123         transform[3].z = translation.z;
124         return transform;
125 }
126
127
128 Player::Player(Entity &e, ChunkIndex &c)
129 : entity(e)
130 , chunks(c)
131 , inv_slot(0) {
132
133 }
134
135 Player::~Player() {
136
137 }
138
139 void Player::Update(int dt) {
140         chunks.Rebase(entity.ChunkCoords());
141 }
142
143
144 World::World(const BlockTypeRegistry &types, const Config &config)
145 : config(config)
146 , block_type(types)
147 , chunks(types)
148 // TODO: set spawn base and extent from config
149 , spawn_index(chunks.MakeIndex(Chunk::Pos(0, 0, 0), 3))
150 , players()
151 , entities()
152 , light_direction(config.light_direction)
153 , fog_density(config.fog_density) {
154
155 }
156
157 World::~World() {
158         chunks.UnregisterIndex(spawn_index);
159 }
160
161
162 Player *World::AddPlayer(const std::string &name) {
163         for (Player &p : players) {
164                 if (p.Name() == name) {
165                         return nullptr;
166                 }
167         }
168         Entity &entity = AddEntity();
169         entity.Name(name);
170         // TODO: load from save file here
171         entity.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
172         entity.WorldCollidable(true);
173         entity.Position(config.spawn);
174         ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
175         players.emplace_back(entity, index);
176         return &players.back();
177 }
178
179 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
180         for (Player &p : players) {
181                 if (p.Name() == name) {
182                         return nullptr;
183                 }
184         }
185         Entity *entity = AddEntity(id);
186         if (!entity) {
187                 return nullptr;
188         }
189         entity->Name(name);
190         // TODO: load from save file here
191         entity->Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
192         entity->WorldCollidable(true);
193         entity->Position(config.spawn);
194         ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
195         players.emplace_back(*entity, index);
196         return &players.back();
197 }
198
199 Entity &World::AddEntity() {
200         if (entities.empty()) {
201                 entities.emplace_back();
202                 entities.back().ID(1);
203                 return entities.back();
204         }
205         if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
206                 std::uint32_t id = entities.back().ID() + 1;
207                 entities.emplace_back();
208                 entities.back().ID(id);
209                 return entities.back();
210         }
211         std::uint32_t id = 1;
212         auto position = entities.begin();
213         auto end = entities.end();
214         while (position != end && position->ID() == id) {
215                 ++id;
216                 ++position;
217         }
218         auto entity = entities.emplace(position);
219         entity->ID(id);
220         return *entity;
221 }
222
223 Entity *World::AddEntity(std::uint32_t id) {
224         if (entities.empty() || entities.back().ID() < id) {
225                 entities.emplace_back();
226                 entities.back().ID(id);
227                 return &entities.back();
228         }
229
230         auto position = entities.begin();
231         auto end = entities.end();
232         while (position != end && position->ID() < id) {
233                 ++position;
234         }
235         if (position != end && position->ID() == id) {
236                 return nullptr;
237         }
238         auto entity = entities.emplace(position);
239         entity->ID(id);
240         return &*entity;
241 }
242
243 Entity &World::ForceAddEntity(std::uint32_t id) {
244         if (entities.empty() || entities.back().ID() < id) {
245                 entities.emplace_back();
246                 entities.back().ID(id);
247                 return entities.back();
248         }
249
250         auto position = entities.begin();
251         auto end = entities.end();
252         while (position != end && position->ID() < id) {
253                 ++position;
254         }
255         if (position != end && position->ID() == id) {
256                 return *position;
257         }
258         auto entity = entities.emplace(position);
259         entity->ID(id);
260         return *entity;
261 }
262
263
264 namespace {
265
266 struct Candidate {
267         Chunk *chunk;
268         float dist;
269 };
270
271 bool CandidateLess(const Candidate &a, const Candidate &b) {
272         return a.dist < b.dist;
273 }
274
275 std::vector<Candidate> candidates;
276
277 }
278
279 bool World::Intersection(
280         const Ray &ray,
281         const glm::mat4 &M,
282         const Chunk::Pos &reference,
283         WorldCollision &coll
284 ) {
285         candidates.clear();
286
287         for (Chunk &cur_chunk : chunks) {
288                 float cur_dist;
289                 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
290                         candidates.push_back({ &cur_chunk, cur_dist });
291                 }
292         }
293
294         if (candidates.empty()) return false;
295
296         std::sort(candidates.begin(), candidates.end(), CandidateLess);
297
298         coll.chunk = nullptr;
299         coll.block = -1;
300         coll.depth = std::numeric_limits<float>::infinity();
301
302         for (Candidate &cand : candidates) {
303                 if (cand.dist > coll.depth) continue;
304                 WorldCollision cur_coll;
305                 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
306                         if (cur_coll.depth < coll.depth) {
307                                 coll = cur_coll;
308                         }
309                 }
310         }
311
312         return coll.chunk;
313 }
314
315 bool World::Intersection(
316         const Ray &ray,
317         const glm::mat4 &M,
318         const Entity &reference,
319         EntityCollision &coll
320 ) {
321         coll.entity = nullptr;
322         coll.depth = std::numeric_limits<float>::infinity();
323         for (Entity &cur_entity : entities) {
324                 if (&cur_entity == &reference) {
325                         continue;
326                 }
327                 float cur_dist;
328                 glm::vec3 cur_normal;
329                 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
330                         // TODO: fine grained check goes here? maybe?
331                         if (cur_dist < coll.depth) {
332                                 coll.entity = &cur_entity;
333                                 coll.depth = cur_dist;
334                                 coll.normal = cur_normal;
335                         }
336                 }
337         }
338
339         return coll.entity;
340 }
341
342 bool World::Intersection(const Entity &e, std::vector<WorldCollision> &col) {
343         AABB box = e.Bounds();
344         Chunk::Pos reference = e.ChunkCoords();
345         glm::mat4 M = e.Transform(reference);
346         bool any = false;
347         for (Chunk &cur_chunk : chunks) {
348                 if (manhattan_radius(cur_chunk.Position() - e.ChunkCoords()) > 1) {
349                         // chunk is not one of the 3x3x3 surrounding the entity
350                         // since there's no entity which can extent over 16 blocks, they can be skipped
351                         continue;
352                 }
353                 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
354                         any = true;
355                 }
356         }
357         return any;
358 }
359
360
361 namespace {
362
363 std::vector<WorldCollision> col;
364
365 }
366
367 void World::Update(int dt) {
368         for (Entity &entity : entities) {
369                 entity.Update(dt);
370         }
371         for (Entity &entity : entities) {
372                 col.clear();
373                 if (entity.WorldCollidable() && Intersection(entity, col)) {
374                         // entity collides with the world
375                         Resolve(entity, col);
376                 }
377         }
378         for (Player &player : players) {
379                 player.Update(dt);
380         }
381         for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
382                 if (iter->CanRemove()) {
383                         iter = RemoveEntity(iter);
384                 } else {
385                         ++iter;
386                 }
387         }
388 }
389
390 void World::Resolve(Entity &e, std::vector<WorldCollision> &col) {
391         // determine displacement for each cardinal axis and move entity accordingly
392         glm::vec3 min_disp(0.0f);
393         glm::vec3 max_disp(0.0f);
394         for (const WorldCollision &c : col) {
395                 if (!c.Blocks()) continue;
396                 glm::vec3 local_disp(c.normal * c.depth);
397                 // swap if neccessary (normal may point away from the entity)
398                 if (dot(c.normal, e.Position() - c.BlockCoords()) < 0) {
399                         local_disp *= -1;
400                 }
401                 min_disp = min(min_disp, local_disp);
402                 max_disp = max(max_disp, local_disp);
403         }
404         // for each axis
405         // if only one direction is set, use that as the final
406         // if both directions are set, use average
407         glm::vec3 final_disp(0.0f);
408         for (int axis = 0; axis < 3; ++axis) {
409                 if (std::abs(min_disp[axis]) > std::numeric_limits<float>::epsilon()) {
410                         if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
411                                 final_disp[axis] = (min_disp[axis] + max_disp[axis]) * 0.5f;
412                         } else {
413                                 final_disp[axis] = min_disp[axis];
414                         }
415                 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
416                         final_disp[axis] = max_disp[axis];
417                 }
418         }
419         e.Position(e.Position() + final_disp);
420 }
421
422 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
423         // check for player
424         for (auto player = players.begin(), end = players.end(); player != end;) {
425                 if (&player->GetEntity() == &*eh) {
426                         chunks.UnregisterIndex(player->GetChunks());
427                         player = players.erase(player);
428                         end = players.end();
429                 } else {
430                         ++player;
431                 }
432         }
433         return entities.erase(eh);
434 }
435
436
437 void World::Render(Viewport &viewport) {
438         DirectionalLighting &entity_prog = viewport.EntityProgram();
439         entity_prog.SetLightDirection(light_direction);
440         entity_prog.SetFogDensity(fog_density);
441
442         for (Entity &entity : entities) {
443                 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);
444         }
445 }
446
447 }