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