2 #include "EntityState.hpp"
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"
16 #include <glm/gtx/io.hpp>
17 #include <glm/gtx/quaternion.hpp>
18 #include <glm/gtx/transform.hpp>
23 Entity::Entity() noexcept
30 , world_collision(false)
36 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
41 void Entity::Position(const glm::vec3 &pos) noexcept {
42 state.block_pos = pos;
43 state.AdjustPosition();
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);
50 glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
52 return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
57 glm::quat delta_rot(const glm::vec3 &av, float dt) {
58 glm::vec3 half(av * dt * 0.5f);
59 float mag = length(half);
61 float smag = std::sin(mag) / mag;
62 return glm::quat(std::cos(mag), half * smag);
64 return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
70 void Entity::Update(int dt) noexcept {
75 EntityState::EntityState()
79 , orient(1.0f, 0.0f, 0.0f, 0.0f)
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;
91 void EntityState::AdjustPosition() noexcept {
92 while (block_pos.x >= Chunk::width) {
93 block_pos.x -= Chunk::width;
96 while (block_pos.x < 0) {
97 block_pos.x += Chunk::width;
100 while (block_pos.y >= Chunk::height) {
101 block_pos.y -= Chunk::height;
104 while (block_pos.y < 0) {
105 block_pos.y += Chunk::height;
108 while (block_pos.z >= Chunk::depth) {
109 block_pos.z -= Chunk::depth;
112 while (block_pos.z < 0) {
113 block_pos.z += Chunk::depth;
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;
128 Player::Player(Entity &e, ChunkIndex &c)
138 void Player::Update(int dt) {
139 chunks.Rebase(entity.ChunkCoords());
143 World::World(const BlockTypeRegistry &types, const Config &config)
147 // TODO: set spawn base and extent from config
148 , spawn_index(chunks.MakeIndex(Chunk::Pos(0, 0, 0), 3))
151 , light_direction(config.light_direction)
152 , fog_density(config.fog_density) {
157 chunks.UnregisterIndex(spawn_index);
161 Player *World::AddPlayer(const std::string &name) {
162 for (Player &p : players) {
163 if (p.Name() == name) {
167 Entity &entity = AddEntity();
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();
178 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
179 for (Player &p : players) {
180 if (p.Name() == name) {
184 Entity *entity = AddEntity(id);
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();
198 Entity &World::AddEntity() {
199 if (entities.empty()) {
200 entities.emplace_back();
201 entities.back().ID(1);
202 return entities.back();
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();
210 std::uint32_t id = 1;
211 auto position = entities.begin();
212 auto end = entities.end();
213 while (position != end && position->ID() == id) {
217 auto entity = entities.emplace(position);
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();
229 auto position = entities.begin();
230 auto end = entities.end();
231 while (position != end && position->ID() < id) {
234 if (position != end && position->ID() == id) {
237 auto entity = entities.emplace(position);
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();
249 auto position = entities.begin();
250 auto end = entities.end();
251 while (position != end && position->ID() < id) {
254 if (position != end && position->ID() == id) {
257 auto entity = entities.emplace(position);
270 bool CandidateLess(const Candidate &a, const Candidate &b) {
271 return a.dist < b.dist;
274 std::vector<Candidate> candidates;
278 bool World::Intersection(
281 const Chunk::Pos &reference,
286 for (Chunk &cur_chunk : chunks) {
288 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
289 candidates.push_back({ &cur_chunk, cur_dist });
293 if (candidates.empty()) return false;
295 std::sort(candidates.begin(), candidates.end(), CandidateLess);
297 coll.chunk = nullptr;
299 coll.depth = std::numeric_limits<float>::infinity();
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) {
314 bool World::Intersection(
317 const Entity &reference,
318 EntityCollision &coll
320 coll.entity = nullptr;
321 coll.depth = std::numeric_limits<float>::infinity();
322 for (Entity &cur_entity : entities) {
323 if (&cur_entity == &reference) {
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;
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);
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
352 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
362 std::vector<WorldCollision> col;
366 void World::Update(int dt) {
367 for (Entity &entity : entities) {
370 for (Entity &entity : entities) {
372 if (entity.WorldCollidable() && Intersection(entity, col)) {
373 // entity collides with the world
374 Resolve(entity, col);
377 for (Player &player : players) {
380 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
381 if (iter->CanRemove()) {
382 iter = RemoveEntity(iter);
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) {
400 min_disp = min(min_disp, local_disp);
401 max_disp = max(max_disp, local_disp);
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;
412 final_disp[axis] = min_disp[axis];
414 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
415 final_disp[axis] = max_disp[axis];
418 e.Position(e.Position() + final_disp);
421 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
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);
432 return entities.erase(eh);
436 void World::Render(Viewport &viewport) {
437 DirectionalLighting &entity_prog = viewport.EntityProgram();
438 entity_prog.SetLightDirection(light_direction);
439 entity_prog.SetFogDensity(fog_density);
441 for (Entity &entity : entities) {
442 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);