2 #include "EntityDerivative.hpp"
3 #include "EntityState.hpp"
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"
18 #include <glm/gtx/io.hpp>
19 #include <glm/gtx/quaternion.hpp>
20 #include <glm/gtx/transform.hpp>
25 Entity::Entity() noexcept
33 , world_collision(false)
39 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
44 void Entity::Position(const glm::vec3 &pos) noexcept {
45 state.block_pos = pos;
46 state.AdjustPosition();
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);
53 glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
55 return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
60 glm::quat delta_rot(const glm::vec3 &av, float dt) {
61 glm::vec3 half(av * dt * 0.5f);
62 float mag = length(half);
64 float smag = std::sin(mag) / mag;
65 return glm::quat(std::cos(mag), half * smag);
67 return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
73 void Entity::Update(int dt) noexcept {
74 float fdt = float(dt);
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();
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));
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);
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();
100 EntityDerivative Entity::CalculateStep(
101 const EntityState &cur,
103 const EntityDerivative &delta
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();
111 EntityDerivative out;
112 out.position = next.velocity;
113 out.velocity = ControlForce(next); // plus other forces and then by mass
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
127 EntityState::EntityState()
131 , orient(1.0f, 0.0f, 0.0f, 0.0f)
136 void EntityState::AdjustPosition() noexcept {
137 while (block_pos.x >= Chunk::width) {
138 block_pos.x -= Chunk::width;
141 while (block_pos.x < 0) {
142 block_pos.x += Chunk::width;
145 while (block_pos.y >= Chunk::height) {
146 block_pos.y -= Chunk::height;
149 while (block_pos.y < 0) {
150 block_pos.y += Chunk::height;
153 while (block_pos.z >= Chunk::depth) {
154 block_pos.z -= Chunk::depth;
157 while (block_pos.z < 0) {
158 block_pos.z += Chunk::depth;
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;
173 Player::Player(Entity &e, ChunkIndex &c)
184 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
185 if (!spawn_block || spawn_block.GetType().collide_block) {
189 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
190 if (!head_block || head_block.GetType().collide_block) {
197 void Player::Update(int dt) {
198 chunks.Rebase(entity.ChunkCoords());
202 World::World(const BlockTypeRegistry &types, const Config &config)
208 , light_direction(config.light_direction)
209 , fog_density(config.fog_density) {
218 Player *World::AddPlayer(const std::string &name) {
219 for (Player &p : players) {
220 if (p.Name() == name) {
224 Entity &entity = AddEntity();
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();
233 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
234 for (Player &p : players) {
235 if (p.Name() == name) {
239 Entity *entity = AddEntity(id);
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();
251 Entity &World::AddEntity() {
252 if (entities.empty()) {
253 entities.emplace_back();
254 entities.back().ID(1);
255 return entities.back();
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();
263 std::uint32_t id = 1;
264 auto position = entities.begin();
265 auto end = entities.end();
266 while (position != end && position->ID() == id) {
270 auto entity = entities.emplace(position);
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();
282 auto position = entities.begin();
283 auto end = entities.end();
284 while (position != end && position->ID() < id) {
287 if (position != end && position->ID() == id) {
290 auto entity = entities.emplace(position);
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();
302 auto position = entities.begin();
303 auto end = entities.end();
304 while (position != end && position->ID() < id) {
307 if (position != end && position->ID() == id) {
310 auto entity = entities.emplace(position);
323 bool CandidateLess(const Candidate &a, const Candidate &b) {
324 return a.dist < b.dist;
327 std::vector<Candidate> candidates;
331 bool World::Intersection(
334 const Chunk::Pos &reference,
339 for (Chunk &cur_chunk : chunks) {
341 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
342 candidates.push_back({ &cur_chunk, cur_dist });
346 if (candidates.empty()) return false;
348 std::sort(candidates.begin(), candidates.end(), CandidateLess);
350 coll.chunk = nullptr;
352 coll.depth = std::numeric_limits<float>::infinity();
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) {
367 bool World::Intersection(
370 const Entity &reference,
371 EntityCollision &coll
373 coll.entity = nullptr;
374 coll.depth = std::numeric_limits<float>::infinity();
375 for (Entity &cur_entity : entities) {
376 if (&cur_entity == &reference) {
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;
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);
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
405 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
415 std::vector<WorldCollision> col;
419 void World::Update(int dt) {
420 for (Entity &entity : entities) {
423 for (Entity &entity : entities) {
425 if (entity.WorldCollidable() && Intersection(entity, col)) {
426 // entity collides with the world
427 Resolve(entity, col);
430 for (Player &player : players) {
433 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
434 if (iter->CanRemove()) {
435 iter = RemoveEntity(iter);
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) {
453 min_disp = min(min_disp, local_disp);
454 max_disp = max(max_disp, local_disp);
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;
465 final_disp[axis] = min_disp[axis];
467 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
468 final_disp[axis] = max_disp[axis];
471 e.Position(e.Position() + final_disp);
474 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
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);
485 return entities.erase(eh);
489 void World::Render(Viewport &viewport) {
490 DirectionalLighting &entity_prog = viewport.EntityProgram();
491 entity_prog.SetLightDirection(light_direction);
492 entity_prog.SetFogDensity(fog_density);
494 for (Entity &entity : entities) {
495 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);