]> git.localhorst.tv Git - blank.git/blob - src/world/world.cpp
split input handling
[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
132 }
133
134 Player::~Player() {
135
136 }
137
138 void Player::Update(int dt) {
139         chunks.Rebase(entity.ChunkCoords());
140 }
141
142
143 World::World(const BlockTypeRegistry &types, const Config &config)
144 : config(config)
145 , block_type(types)
146 , chunks(types)
147 // TODO: set spawn base and extent from config
148 , spawn_index(chunks.MakeIndex(Chunk::Pos(0, 0, 0), 3))
149 , players()
150 , entities()
151 , light_direction(config.light_direction)
152 , fog_density(config.fog_density) {
153
154 }
155
156 World::~World() {
157         chunks.UnregisterIndex(spawn_index);
158 }
159
160
161 Player *World::AddPlayer(const std::string &name) {
162         for (Player &p : players) {
163                 if (p.Name() == name) {
164                         return nullptr;
165                 }
166         }
167         Entity &entity = AddEntity();
168         entity.Name(name);
169         // TODO: load from save file here
170         entity.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
171         entity.WorldCollidable(true);
172         entity.Position(config.spawn);
173         ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
174         players.emplace_back(entity, index);
175         return &players.back();
176 }
177
178 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
179         for (Player &p : players) {
180                 if (p.Name() == name) {
181                         return nullptr;
182                 }
183         }
184         Entity *entity = AddEntity(id);
185         if (!entity) {
186                 return nullptr;
187         }
188         entity->Name(name);
189         // TODO: load from save file here
190         entity->Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
191         entity->WorldCollidable(true);
192         entity->Position(config.spawn);
193         ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
194         players.emplace_back(*entity, index);
195         return &players.back();
196 }
197
198 Entity &World::AddEntity() {
199         if (entities.empty()) {
200                 entities.emplace_back();
201                 entities.back().ID(1);
202                 return entities.back();
203         }
204         if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
205                 std::uint32_t id = entities.back().ID() + 1;
206                 entities.emplace_back();
207                 entities.back().ID(id);
208                 return entities.back();
209         }
210         std::uint32_t id = 1;
211         auto position = entities.begin();
212         auto end = entities.end();
213         while (position != end && position->ID() == id) {
214                 ++id;
215                 ++position;
216         }
217         auto entity = entities.emplace(position);
218         entity->ID(id);
219         return *entity;
220 }
221
222 Entity *World::AddEntity(std::uint32_t id) {
223         if (entities.empty() || entities.back().ID() < id) {
224                 entities.emplace_back();
225                 entities.back().ID(id);
226                 return &entities.back();
227         }
228
229         auto position = entities.begin();
230         auto end = entities.end();
231         while (position != end && position->ID() < id) {
232                 ++position;
233         }
234         if (position != end && position->ID() == id) {
235                 return nullptr;
236         }
237         auto entity = entities.emplace(position);
238         entity->ID(id);
239         return &*entity;
240 }
241
242 Entity &World::ForceAddEntity(std::uint32_t id) {
243         if (entities.empty() || entities.back().ID() < id) {
244                 entities.emplace_back();
245                 entities.back().ID(id);
246                 return entities.back();
247         }
248
249         auto position = entities.begin();
250         auto end = entities.end();
251         while (position != end && position->ID() < id) {
252                 ++position;
253         }
254         if (position != end && position->ID() == id) {
255                 return *position;
256         }
257         auto entity = entities.emplace(position);
258         entity->ID(id);
259         return *entity;
260 }
261
262
263 namespace {
264
265 struct Candidate {
266         Chunk *chunk;
267         float dist;
268 };
269
270 bool CandidateLess(const Candidate &a, const Candidate &b) {
271         return a.dist < b.dist;
272 }
273
274 std::vector<Candidate> candidates;
275
276 }
277
278 bool World::Intersection(
279         const Ray &ray,
280         const glm::mat4 &M,
281         const Chunk::Pos &reference,
282         WorldCollision &coll
283 ) {
284         candidates.clear();
285
286         for (Chunk &cur_chunk : chunks) {
287                 float cur_dist;
288                 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
289                         candidates.push_back({ &cur_chunk, cur_dist });
290                 }
291         }
292
293         if (candidates.empty()) return false;
294
295         std::sort(candidates.begin(), candidates.end(), CandidateLess);
296
297         coll.chunk = nullptr;
298         coll.block = -1;
299         coll.depth = std::numeric_limits<float>::infinity();
300
301         for (Candidate &cand : candidates) {
302                 if (cand.dist > coll.depth) continue;
303                 WorldCollision cur_coll;
304                 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
305                         if (cur_coll.depth < coll.depth) {
306                                 coll = cur_coll;
307                         }
308                 }
309         }
310
311         return coll.chunk;
312 }
313
314 bool World::Intersection(
315         const Ray &ray,
316         const glm::mat4 &M,
317         const Entity &reference,
318         EntityCollision &coll
319 ) {
320         coll.entity = nullptr;
321         coll.depth = std::numeric_limits<float>::infinity();
322         for (Entity &cur_entity : entities) {
323                 if (&cur_entity == &reference) {
324                         continue;
325                 }
326                 float cur_dist;
327                 glm::vec3 cur_normal;
328                 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
329                         // TODO: fine grained check goes here? maybe?
330                         if (cur_dist < coll.depth) {
331                                 coll.entity = &cur_entity;
332                                 coll.depth = cur_dist;
333                                 coll.normal = cur_normal;
334                         }
335                 }
336         }
337
338         return coll.entity;
339 }
340
341 bool World::Intersection(const Entity &e, std::vector<WorldCollision> &col) {
342         AABB box = e.Bounds();
343         Chunk::Pos reference = e.ChunkCoords();
344         glm::mat4 M = e.Transform(reference);
345         bool any = false;
346         for (Chunk &cur_chunk : chunks) {
347                 if (manhattan_radius(cur_chunk.Position() - e.ChunkCoords()) > 1) {
348                         // chunk is not one of the 3x3x3 surrounding the entity
349                         // since there's no entity which can extent over 16 blocks, they can be skipped
350                         continue;
351                 }
352                 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
353                         any = true;
354                 }
355         }
356         return any;
357 }
358
359
360 namespace {
361
362 std::vector<WorldCollision> col;
363
364 }
365
366 void World::Update(int dt) {
367         for (Entity &entity : entities) {
368                 entity.Update(dt);
369         }
370         for (Entity &entity : entities) {
371                 col.clear();
372                 if (entity.WorldCollidable() && Intersection(entity, col)) {
373                         // entity collides with the world
374                         Resolve(entity, col);
375                 }
376         }
377         for (Player &player : players) {
378                 player.Update(dt);
379         }
380         for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
381                 if (iter->CanRemove()) {
382                         iter = RemoveEntity(iter);
383                 } else {
384                         ++iter;
385                 }
386         }
387 }
388
389 void World::Resolve(Entity &e, std::vector<WorldCollision> &col) {
390         // determine displacement for each cardinal axis and move entity accordingly
391         glm::vec3 min_disp(0.0f);
392         glm::vec3 max_disp(0.0f);
393         for (const WorldCollision &c : col) {
394                 if (!c.Blocks()) continue;
395                 glm::vec3 local_disp(c.normal * c.depth);
396                 // swap if neccessary (normal may point away from the entity)
397                 if (dot(c.normal, e.Position() - c.BlockCoords()) < 0) {
398                         local_disp *= -1;
399                 }
400                 min_disp = min(min_disp, local_disp);
401                 max_disp = max(max_disp, local_disp);
402         }
403         // for each axis
404         // if only one direction is set, use that as the final
405         // if both directions are set, use average
406         glm::vec3 final_disp(0.0f);
407         for (int axis = 0; axis < 3; ++axis) {
408                 if (std::abs(min_disp[axis]) > std::numeric_limits<float>::epsilon()) {
409                         if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
410                                 final_disp[axis] = (min_disp[axis] + max_disp[axis]) * 0.5f;
411                         } else {
412                                 final_disp[axis] = min_disp[axis];
413                         }
414                 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
415                         final_disp[axis] = max_disp[axis];
416                 }
417         }
418         e.Position(e.Position() + final_disp);
419 }
420
421 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
422         // check for player
423         for (auto player = players.begin(), end = players.end(); player != end;) {
424                 if (&player->GetEntity() == &*eh) {
425                         chunks.UnregisterIndex(player->GetChunks());
426                         player = players.erase(player);
427                         end = players.end();
428                 } else {
429                         ++player;
430                 }
431         }
432         return entities.erase(eh);
433 }
434
435
436 void World::Render(Viewport &viewport) {
437         DirectionalLighting &entity_prog = viewport.EntityProgram();
438         entity_prog.SetLightDirection(light_direction);
439         entity_prog.SetFogDensity(fog_density);
440
441         for (Entity &entity : entities) {
442                 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);
443         }
444 }
445
446 }