2 #include "EntityState.hpp"
5 #include "ChunkIndex.hpp"
6 #include "EntityCollision.hpp"
7 #include "WorldCollision.hpp"
8 #include "../app/Assets.hpp"
9 #include "../graphics/Format.hpp"
10 #include "../graphics/Viewport.hpp"
15 #include <glm/gtx/io.hpp>
16 #include <glm/gtx/quaternion.hpp>
17 #include <glm/gtx/transform.hpp>
22 Entity::Entity() noexcept
29 , world_collision(false)
35 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
40 void Entity::Position(const glm::vec3 &pos) noexcept {
41 state.block_pos = pos;
42 state.AdjustPosition();
45 Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
46 glm::mat4 transform = Transform(chunk_offset);
47 glm::vec4 from = transform * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
49 glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
51 return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
56 glm::quat delta_rot(const glm::vec3 &av, float dt) {
57 glm::vec3 half(av * dt * 0.5f);
58 float mag = length(half);
60 float smag = std::sin(mag) / mag;
61 return glm::quat(std::cos(mag), half * smag);
63 return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
69 void Entity::Update(int dt) noexcept {
74 EntityState::EntityState()
78 , orient(1.0f, 0.0f, 0.0f, 0.0f)
83 void EntityState::Update(int dt) noexcept {
84 float fdt = float(dt);
85 block_pos += velocity * fdt;
86 orient = delta_rot(ang_vel, fdt) * orient;
90 void EntityState::AdjustPosition() noexcept {
91 while (block_pos.x >= Chunk::width) {
92 block_pos.x -= Chunk::width;
95 while (block_pos.x < 0) {
96 block_pos.x += Chunk::width;
99 while (block_pos.y >= Chunk::height) {
100 block_pos.y -= Chunk::height;
103 while (block_pos.y < 0) {
104 block_pos.y += Chunk::height;
107 while (block_pos.z >= Chunk::depth) {
108 block_pos.z -= Chunk::depth;
111 while (block_pos.z < 0) {
112 block_pos.z += Chunk::depth;
117 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
118 const glm::vec3 translation = RelativePosition(reference);
119 glm::mat4 transform(toMat4(orient));
120 transform[3].x = translation.x;
121 transform[3].y = translation.y;
122 transform[3].z = translation.z;
127 World::World(const BlockTypeRegistry &types, const Config &config)
131 // TODO: set spawn base and extent from config
132 , spawn_index(chunks.MakeIndex(Chunk::Pos(0, 0, 0), 3))
135 , light_direction(config.light_direction)
136 , fog_density(config.fog_density) {
141 chunks.UnregisterIndex(spawn_index);
145 Player World::AddPlayer(const std::string &name) {
146 for (Player &p : players) {
147 if (p.entity->Name() == name) {
148 return { nullptr, nullptr };
151 Entity &entity = AddEntity();
153 // TODO: load from save file here
154 entity.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
155 entity.WorldCollidable(true);
156 entity.Position(config.spawn);
157 ChunkIndex *index = &chunks.MakeIndex(entity.ChunkCoords(), 6);
158 players.emplace_back(&entity, index);
159 return players.back();
162 Player World::AddPlayer(const std::string &name, std::uint32_t id) {
163 for (Player &p : players) {
164 if (p.entity->Name() == name) {
165 return { nullptr, nullptr };
168 Entity *entity = AddEntity(id);
170 return { nullptr, nullptr };
173 // TODO: load from save file here
174 entity->Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
175 entity->WorldCollidable(true);
176 entity->Position(config.spawn);
177 ChunkIndex *index = &chunks.MakeIndex(entity->ChunkCoords(), 6);
178 players.emplace_back(entity, index);
179 return players.back();
182 Entity &World::AddEntity() {
183 if (entities.empty()) {
184 entities.emplace_back();
185 entities.back().ID(1);
186 return entities.back();
188 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
189 std::uint32_t id = entities.back().ID() + 1;
190 entities.emplace_back();
191 entities.back().ID(id);
192 return entities.back();
194 std::uint32_t id = 1;
195 auto position = entities.begin();
196 auto end = entities.end();
197 while (position != end && position->ID() == id) {
201 auto entity = entities.emplace(position);
206 Entity *World::AddEntity(std::uint32_t id) {
207 if (entities.empty() || entities.back().ID() < id) {
208 entities.emplace_back();
209 entities.back().ID(id);
210 return &entities.back();
213 auto position = entities.begin();
214 auto end = entities.end();
215 while (position != end && position->ID() < id) {
218 if (position != end && position->ID() == id) {
221 auto entity = entities.emplace(position);
226 Entity &World::ForceAddEntity(std::uint32_t id) {
227 if (entities.empty() || entities.back().ID() < id) {
228 entities.emplace_back();
229 entities.back().ID(id);
230 return entities.back();
233 auto position = entities.begin();
234 auto end = entities.end();
235 while (position != end && position->ID() < id) {
238 if (position != end && position->ID() == id) {
241 auto entity = entities.emplace(position);
254 bool CandidateLess(const Candidate &a, const Candidate &b) {
255 return a.dist < b.dist;
258 std::vector<Candidate> candidates;
262 bool World::Intersection(
265 const Chunk::Pos &reference,
270 for (Chunk &cur_chunk : chunks) {
272 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
273 candidates.push_back({ &cur_chunk, cur_dist });
277 if (candidates.empty()) return false;
279 std::sort(candidates.begin(), candidates.end(), CandidateLess);
281 coll.chunk = nullptr;
283 coll.depth = std::numeric_limits<float>::infinity();
285 for (Candidate &cand : candidates) {
286 if (cand.dist > coll.depth) continue;
287 WorldCollision cur_coll;
288 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
289 if (cur_coll.depth < coll.depth) {
298 bool World::Intersection(
301 const Entity &reference,
302 EntityCollision &coll
304 coll.entity = nullptr;
305 coll.depth = std::numeric_limits<float>::infinity();
306 for (Entity &cur_entity : entities) {
307 if (&cur_entity == &reference) {
311 glm::vec3 cur_normal;
312 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
313 // TODO: fine grained check goes here? maybe?
314 if (cur_dist < coll.depth) {
315 coll.entity = &cur_entity;
316 coll.depth = cur_dist;
317 coll.normal = cur_normal;
325 bool World::Intersection(const Entity &e, std::vector<WorldCollision> &col) {
326 AABB box = e.Bounds();
327 Chunk::Pos reference = e.ChunkCoords();
328 glm::mat4 M = e.Transform(reference);
330 for (Chunk &cur_chunk : chunks) {
331 if (manhattan_radius(cur_chunk.Position() - e.ChunkCoords()) > 1) {
332 // chunk is not one of the 3x3x3 surrounding the entity
333 // since there's no entity which can extent over 16 blocks, they can be skipped
336 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
346 std::vector<WorldCollision> col;
350 void World::Update(int dt) {
351 for (Entity &entity : entities) {
354 for (Entity &entity : entities) {
356 if (entity.WorldCollidable() && Intersection(entity, col)) {
357 // entity collides with the world
358 Resolve(entity, col);
361 for (Player &player : players) {
362 player.chunks->Rebase(player.entity->ChunkCoords());
364 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
365 if (iter->CanRemove()) {
366 iter = RemoveEntity(iter);
373 void World::Resolve(Entity &e, std::vector<WorldCollision> &col) {
374 // determine displacement for each cardinal axis and move entity accordingly
375 glm::vec3 min_disp(0.0f);
376 glm::vec3 max_disp(0.0f);
377 for (const WorldCollision &c : col) {
378 if (!c.Blocks()) continue;
379 glm::vec3 local_disp(c.normal * c.depth);
380 // swap if neccessary (normal may point away from the entity)
381 if (dot(c.normal, e.Position() - c.BlockCoords()) < 0) {
384 min_disp = min(min_disp, local_disp);
385 max_disp = max(max_disp, local_disp);
388 // if only one direction is set, use that as the final
389 // if both directions are set, use average
390 glm::vec3 final_disp(0.0f);
391 for (int axis = 0; axis < 3; ++axis) {
392 if (std::abs(min_disp[axis]) > std::numeric_limits<float>::epsilon()) {
393 if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
394 final_disp[axis] = (min_disp[axis] + max_disp[axis]) * 0.5f;
396 final_disp[axis] = min_disp[axis];
398 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
399 final_disp[axis] = max_disp[axis];
402 e.Position(e.Position() + final_disp);
405 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
407 for (auto player = players.begin(), end = players.end(); player != end;) {
408 if (player->entity == &*eh) {
409 chunks.UnregisterIndex(*player->chunks);
410 player = players.erase(player);
416 return entities.erase(eh);
420 void World::Render(Viewport &viewport) {
421 DirectionalLighting &entity_prog = viewport.EntityProgram();
422 entity_prog.SetLightDirection(light_direction);
423 entity_prog.SetFogDensity(fog_density);
425 for (Entity &entity : entities) {
426 entity.Render(entity.Transform(players[0].entity->ChunkCoords()), entity_prog);