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)
139 void Player::Update(int dt) {
140 chunks.Rebase(entity.ChunkCoords());
144 World::World(const BlockTypeRegistry &types, const Config &config)
148 // TODO: set spawn base and extent from config
149 , spawn_index(chunks.MakeIndex(Chunk::Pos(0, 0, 0), 3))
152 , light_direction(config.light_direction)
153 , fog_density(config.fog_density) {
158 chunks.UnregisterIndex(spawn_index);
162 Player *World::AddPlayer(const std::string &name) {
163 for (Player &p : players) {
164 if (p.Name() == name) {
168 Entity &entity = AddEntity();
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();
179 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
180 for (Player &p : players) {
181 if (p.Name() == name) {
185 Entity *entity = AddEntity(id);
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();
199 Entity &World::AddEntity() {
200 if (entities.empty()) {
201 entities.emplace_back();
202 entities.back().ID(1);
203 return entities.back();
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();
211 std::uint32_t id = 1;
212 auto position = entities.begin();
213 auto end = entities.end();
214 while (position != end && position->ID() == id) {
218 auto entity = entities.emplace(position);
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();
230 auto position = entities.begin();
231 auto end = entities.end();
232 while (position != end && position->ID() < id) {
235 if (position != end && position->ID() == id) {
238 auto entity = entities.emplace(position);
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();
250 auto position = entities.begin();
251 auto end = entities.end();
252 while (position != end && position->ID() < id) {
255 if (position != end && position->ID() == id) {
258 auto entity = entities.emplace(position);
271 bool CandidateLess(const Candidate &a, const Candidate &b) {
272 return a.dist < b.dist;
275 std::vector<Candidate> candidates;
279 bool World::Intersection(
282 const Chunk::Pos &reference,
287 for (Chunk &cur_chunk : chunks) {
289 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
290 candidates.push_back({ &cur_chunk, cur_dist });
294 if (candidates.empty()) return false;
296 std::sort(candidates.begin(), candidates.end(), CandidateLess);
298 coll.chunk = nullptr;
300 coll.depth = std::numeric_limits<float>::infinity();
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) {
315 bool World::Intersection(
318 const Entity &reference,
319 EntityCollision &coll
321 coll.entity = nullptr;
322 coll.depth = std::numeric_limits<float>::infinity();
323 for (Entity &cur_entity : entities) {
324 if (&cur_entity == &reference) {
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;
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);
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
353 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
363 std::vector<WorldCollision> col;
367 void World::Update(int dt) {
368 for (Entity &entity : entities) {
371 for (Entity &entity : entities) {
373 if (entity.WorldCollidable() && Intersection(entity, col)) {
374 // entity collides with the world
375 Resolve(entity, col);
378 for (Player &player : players) {
381 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
382 if (iter->CanRemove()) {
383 iter = RemoveEntity(iter);
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) {
401 min_disp = min(min_disp, local_disp);
402 max_disp = max(max_disp, local_disp);
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;
413 final_disp[axis] = min_disp[axis];
415 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
416 final_disp[axis] = max_disp[axis];
419 e.Position(e.Position() + final_disp);
422 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
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);
433 return entities.erase(eh);
437 void World::Render(Viewport &viewport) {
438 DirectionalLighting &entity_prog = viewport.EntityProgram();
439 entity_prog.SetLightDirection(light_direction);
440 entity_prog.SetFogDensity(fog_density);
442 for (Entity &entity : entities) {
443 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);