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)
38 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
43 void Entity::Position(const glm::vec3 &pos) noexcept {
44 state.block_pos = pos;
45 state.AdjustPosition();
48 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
49 return state.Transform(reference);
52 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
53 glm::mat4 transform = Transform(reference);
55 transform *= model.EyesTransform();
60 Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
61 glm::mat4 transform = ViewTransform(chunk_offset);
62 glm::vec4 from = transform * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
64 glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
66 return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
70 EntityState::EntityState()
74 , orient(1.0f, 0.0f, 0.0f, 0.0f)
79 void EntityState::AdjustPosition() noexcept {
80 while (block_pos.x >= Chunk::width) {
81 block_pos.x -= Chunk::width;
84 while (block_pos.x < 0) {
85 block_pos.x += Chunk::width;
88 while (block_pos.y >= Chunk::height) {
89 block_pos.y -= Chunk::height;
92 while (block_pos.y < 0) {
93 block_pos.y += Chunk::height;
96 while (block_pos.z >= Chunk::depth) {
97 block_pos.z -= Chunk::depth;
100 while (block_pos.z < 0) {
101 block_pos.z += Chunk::depth;
106 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
107 const glm::vec3 translation = RelativePosition(reference);
108 glm::mat4 transform(toMat4(orient));
109 transform[3].x = translation.x;
110 transform[3].y = translation.y;
111 transform[3].z = translation.z;
116 Player::Player(Entity &e, ChunkIndex &c)
127 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
128 if (!spawn_block || spawn_block.GetType().collide_block) {
132 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
133 if (!head_block || head_block.GetType().collide_block) {
140 void Player::Update(int dt) {
141 chunks.Rebase(entity.ChunkCoords());
145 World::World(const BlockTypeRegistry &types, const Config &config)
151 , light_direction(config.light_direction)
152 , fog_density(config.fog_density) {
161 Player *World::AddPlayer(const std::string &name) {
162 for (Player &p : players) {
163 if (p.Name() == name) {
167 Entity &entity = AddEntity();
169 entity.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
170 entity.WorldCollidable(true);
171 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
172 players.emplace_back(entity, index);
173 return &players.back();
176 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
177 for (Player &p : players) {
178 if (p.Name() == name) {
182 Entity *entity = AddEntity(id);
187 entity->Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
188 entity->WorldCollidable(true);
189 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
190 players.emplace_back(*entity, index);
191 return &players.back();
194 Entity &World::AddEntity() {
195 if (entities.empty()) {
196 entities.emplace_back();
197 entities.back().ID(1);
198 return entities.back();
200 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
201 std::uint32_t id = entities.back().ID() + 1;
202 entities.emplace_back();
203 entities.back().ID(id);
204 return entities.back();
206 std::uint32_t id = 1;
207 auto position = entities.begin();
208 auto end = entities.end();
209 while (position != end && position->ID() == id) {
213 auto entity = entities.emplace(position);
218 Entity *World::AddEntity(std::uint32_t id) {
219 if (entities.empty() || entities.back().ID() < id) {
220 entities.emplace_back();
221 entities.back().ID(id);
222 return &entities.back();
225 auto position = entities.begin();
226 auto end = entities.end();
227 while (position != end && position->ID() < id) {
230 if (position != end && position->ID() == id) {
233 auto entity = entities.emplace(position);
238 Entity &World::ForceAddEntity(std::uint32_t id) {
239 if (entities.empty() || entities.back().ID() < id) {
240 entities.emplace_back();
241 entities.back().ID(id);
242 return entities.back();
245 auto position = entities.begin();
246 auto end = entities.end();
247 while (position != end && position->ID() < id) {
250 if (position != end && position->ID() == id) {
253 auto entity = entities.emplace(position);
266 bool CandidateLess(const Candidate &a, const Candidate &b) {
267 return a.dist < b.dist;
270 std::vector<Candidate> candidates;
274 bool World::Intersection(
277 const Chunk::Pos &reference,
282 for (Chunk &cur_chunk : chunks) {
284 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
285 candidates.push_back({ &cur_chunk, cur_dist });
289 if (candidates.empty()) return false;
291 std::sort(candidates.begin(), candidates.end(), CandidateLess);
293 coll.chunk = nullptr;
295 coll.depth = std::numeric_limits<float>::infinity();
297 for (Candidate &cand : candidates) {
298 if (cand.dist > coll.depth) continue;
299 WorldCollision cur_coll;
300 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
301 if (cur_coll.depth < coll.depth) {
310 bool World::Intersection(
313 const Entity &reference,
314 EntityCollision &coll
316 coll.entity = nullptr;
317 coll.depth = std::numeric_limits<float>::infinity();
318 for (Entity &cur_entity : entities) {
319 if (&cur_entity == &reference) {
323 glm::vec3 cur_normal;
324 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
325 // TODO: fine grained check goes here? maybe?
326 if (cur_dist < coll.depth) {
327 coll.entity = &cur_entity;
328 coll.depth = cur_dist;
329 coll.normal = cur_normal;
337 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
338 AABB box = e.Bounds();
339 Chunk::Pos reference = s.chunk_pos;
340 glm::mat4 M = s.Transform(reference);
342 for (Chunk &cur_chunk : chunks) {
343 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
344 // chunk is not one of the 3x3x3 surrounding the entity
345 // since there's no entity which can extent over 16 blocks, they can be skipped
348 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
356 void World::Update(int dt) {
357 float fdt(dt * 0.001f);
358 for (Entity &entity : entities) {
361 for (Player &player : players) {
364 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
365 if (iter->CanRemove()) {
366 iter = RemoveEntity(iter);
375 glm::quat delta_rot(const glm::vec3 &av, float dt) {
376 glm::vec3 half(av * dt * 0.5f);
377 float mag = length(half);
379 float smag = std::sin(mag) / mag;
380 return glm::quat(std::cos(mag), half * smag);
382 return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
388 void World::Update(Entity &entity, float dt) {
389 EntityState state(entity.GetState());
391 EntityDerivative a(CalculateStep(entity, state, 0.0f, EntityDerivative()));
392 EntityDerivative b(CalculateStep(entity, state, dt * 0.5f, a));
393 EntityDerivative c(CalculateStep(entity, state, dt * 0.5f, b));
394 EntityDerivative d(CalculateStep(entity, state, dt, c));
397 constexpr float sixth = 1.0f / 6.0f;
398 f.position = sixth * ((a.position + 2.0f * (b.position + c.position)) + d.position);
399 f.velocity = sixth * ((a.velocity + 2.0f * (b.velocity + c.velocity)) + d.velocity);
400 f.orient = sixth * ((a.orient + 2.0f * (b.orient + c.orient)) + d.orient);
402 state.block_pos += f.position * dt;
403 state.velocity += f.velocity * dt;
404 state.orient = delta_rot(f.orient, dt) * state.orient;
405 state.AdjustPosition();
407 entity.SetState(state);
410 EntityDerivative World::CalculateStep(
411 const Entity &entity,
412 const EntityState &cur,
414 const EntityDerivative &delta
416 EntityState next(cur);
417 next.block_pos += delta.position * dt;
418 next.velocity += delta.velocity * dt;
419 next.orient = delta_rot(cur.ang_vel, dt) * cur.orient;
420 next.AdjustPosition();
422 EntityDerivative out;
423 out.position = next.velocity;
424 out.velocity = CalculateForce(entity, next); // by mass = 1kg
428 glm::vec3 World::CalculateForce(
429 const Entity &entity,
430 const EntityState &state
432 return ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state);
435 glm::vec3 World::ControlForce(
436 const Entity &entity,
437 const EntityState &state
439 constexpr float k = 10.0f; // spring constant
440 constexpr float b = 10.0f; // damper constant
441 const glm::vec3 x(-entity.TargetVelocity()); // endpoint displacement from equilibrium, by 1s, in m
442 const glm::vec3 v(state.velocity); // relative velocity between endpoints in m/s
443 return ((-k) * x) - (b * v); // times 1kg/s, in kg*m/s²
448 std::vector<WorldCollision> col;
452 glm::vec3 World::CollisionForce(
453 const Entity &entity,
454 const EntityState &state
457 if (entity.WorldCollidable() && Intersection(entity, state, col)) {
458 // determine displacement for each cardinal axis and move entity accordingly
459 glm::vec3 min_pen(0.0f);
460 glm::vec3 max_pen(0.0f);
461 for (const WorldCollision &c : col) {
462 if (!c.Blocks()) continue;
463 glm::vec3 local_pen(c.normal * c.depth);
464 // swap if neccessary (normal may point away from the entity)
465 if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
468 min_pen = min(min_pen, local_pen);
469 max_pen = max(max_pen, local_pen);
471 glm::vec3 correction(0.0f);
472 // only apply correction for axes where penetration is only in one direction
473 for (std::size_t i = 0; i < 3; ++i) {
474 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
475 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
476 correction[i] = -min_pen[i];
479 correction[i] = -max_pen[i];
482 // correction may be zero in which case normalize() returns NaNs
483 if (dot(correction, correction) < std::numeric_limits<float>::epsilon()) {
484 return glm::vec3(0.0f);
486 glm::vec3 normal(normalize(correction));
487 glm::vec3 normal_velocity(normal * dot(state.velocity, normal));
488 // apply force proportional to penetration
489 // use velocity projected onto normal as damper
490 constexpr float k = 1000.0f; // spring constant
491 constexpr float b = 10.0f; // damper constant
492 const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
493 const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
494 return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
496 return glm::vec3(0.0f);
500 glm::vec3 World::Gravity(
501 const Entity &entity,
502 const EntityState &state
504 return glm::vec3(0.0f);
507 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
509 for (auto player = players.begin(), end = players.end(); player != end;) {
510 if (&player->GetEntity() == &*eh) {
511 chunks.UnregisterIndex(player->GetChunks());
512 player = players.erase(player);
518 return entities.erase(eh);
522 void World::Render(Viewport &viewport) {
523 DirectionalLighting &entity_prog = viewport.EntityProgram();
524 entity_prog.SetLightDirection(light_direction);
525 entity_prog.SetFogDensity(fog_density);
527 for (Entity &entity : entities) {
528 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);