2 #include "EntityController.hpp"
3 #include "EntityDerivative.hpp"
4 #include "EntityState.hpp"
8 #include "ChunkIndex.hpp"
9 #include "EntityCollision.hpp"
10 #include "WorldCollision.hpp"
11 #include "../app/Assets.hpp"
12 #include "../graphics/Format.hpp"
13 #include "../graphics/Viewport.hpp"
19 #include <glm/gtx/euler_angles.hpp>
20 #include <glm/gtx/io.hpp>
21 #include <glm/gtx/quaternion.hpp>
22 #include <glm/gtx/rotate_vector.hpp>
23 #include <glm/gtx/transform.hpp>
28 Entity::Entity() noexcept
35 , heading(0.0f, 0.0f, -1.0f)
39 , world_collision(false)
41 , owns_controller(false) {
45 Entity::~Entity() noexcept {
49 Entity::Entity(const Entity &other) noexcept
54 , bounds(other.bounds)
56 , model_transform(1.0f)
57 , view_transform(1.0f)
59 , heading(0.0f, 0.0f, -1.0f)
60 , max_vel(other.max_vel)
61 , max_force(other.max_force)
63 , world_collision(other.world_collision)
65 , owns_controller(false) {
69 void Entity::SetController(EntityController *c) noexcept {
72 owns_controller = true;
75 void Entity::SetController(EntityController &c) noexcept {
78 owns_controller = false;
81 void Entity::UnsetController() noexcept {
82 if (ctrl && owns_controller) {
88 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
89 if (HasController()) {
90 return GetController().ControlForce(*this, s);
96 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
101 void Entity::Position(const glm::vec3 &pos) noexcept {
102 state.block_pos = pos;
103 state.AdjustPosition();
106 void Entity::TurnHead(float dp, float dy) noexcept {
107 SetHead(state.pitch + dp, state.yaw + dy);
110 void Entity::SetHead(float p, float y) noexcept {
115 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
116 return glm::translate(glm::vec3((state.chunk_pos - reference) * Chunk::Extent())) * model_transform;
119 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
120 return Transform(reference) * view_transform;
123 Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
124 glm::mat4 transform = ViewTransform(chunk_offset);
125 return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
128 void Entity::Update(float dt) {
131 if (HasController()) {
132 GetController().Update(*this, dt);
137 void Entity::UpdateTransforms() noexcept {
138 // model transform is the one given by current state
139 model_transform = state.Transform(state.chunk_pos);
140 // view transform is either the model's eyes transform or,
141 // should the entity have no model, the pitch (yaw already is
142 // in model transform)
144 view_transform = model.EyesTransform();
146 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
150 void Entity::UpdateHeading() noexcept {
151 speed = length(Velocity());
152 if (speed > std::numeric_limits<float>::epsilon()) {
153 heading = Velocity() / speed;
156 // use -Z (forward axis) of model transform (our "chest")
157 heading = -glm::vec3(model_transform[2]);
161 void Entity::UpdateModel(float dt) noexcept {
162 // first, sanitize the pitch and yaw fields of state (our input)
163 // those indicate the head orientation in the entity's local cosystem
164 state.AdjustHeading();
165 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
170 void Entity::OrientBody(float dt) noexcept {
171 // maximum body rotation per second (due to velocity orientation) (90°)
172 constexpr float max_body_turn_per_second = PI_0p5;
173 const float max_body_turn = max_body_turn_per_second * dt;
174 // minimum speed to apply body correction
175 constexpr float min_speed = 0.0625f;
177 const glm::vec3 up(model_transform[1]);
178 if (speed > min_speed) {
179 // check if our orientation and velocity are aligned
180 const glm::vec3 forward(-model_transform[2]);
181 // facing is local -Z rotated about local Y by yaw and transformed into world space
182 const glm::vec3 facing(normalize(glm::vec3(glm::vec4(rotateY(glm::vec3(0.0f, 0.0f, -1.0f), state.yaw), 0.0f) * transpose(model_transform))));
183 // only adjust if velocity isn't almost parallel to up
184 float vel_dot_up = dot(Velocity(), up);
185 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
186 // get direction of velocity projected onto model plane
187 glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
188 // if velocity points away from our facing (with a little bias), flip it around
189 // (the entity is "walking backwards")
190 if (dot(facing, direction) < -0.1f) {
191 direction = -direction;
193 // calculate the difference between forward and direction
194 const float absolute_difference = std::acos(dot(forward, direction));
195 // if direction is clockwise with respect to up vector, invert the angle
196 const float relative_difference = dot(cross(forward, direction), up) < 0.0f
197 ? -absolute_difference
198 : absolute_difference;
199 // only correct by half the difference max
200 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
202 std::cout << "orientation before: " << state.orient << std::endl;
203 std::cout << "up: " << up << std::endl;
204 std::cout << "forward: " << forward << std::endl;
205 std::cout << "facing: " << facing << std::endl;
206 std::cout << "direction: " << direction << std::endl;
207 std::cout << "difference: " << rad2deg(relative_difference) << "°" << std::endl;
208 std::cout << "correction: " << rad2deg(correction) << "°" << std::endl;
209 std::cout << std::endl;
211 // now rotate body by correction and head by -correction
212 state.orient = rotate(state.orient, correction, up);
213 state.yaw -= correction;
218 void Entity::OrientHead(float dt) noexcept {
219 // maximum yaw of head (90°)
220 constexpr float max_head_yaw = PI_0p5;
222 const glm::vec3 up(model_transform[1]);
223 // if yaw is bigger than max, rotate the body to accomodate
224 if (std::abs(state.yaw) > max_head_yaw) {
225 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
226 // rotate the entity by deviation about local Y
227 state.orient = rotate(state.orient, deviation, up);
228 // and remove from head yaw
229 state.yaw -= deviation;
230 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
231 state.AdjustHeading();
233 // update model if any
235 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
240 EntityController::~EntityController() {
244 bool EntityController::MaxOutForce(
246 const glm::vec3 &add,
249 if (iszero(add) || any(isnan(add))) {
252 float current = iszero(out) ? 0.0f : length(out);
253 float remain = max - current;
254 if (remain <= 0.0f) {
257 float additional = length(add);
258 if (additional > remain) {
259 out += normalize(add) * remain;
268 EntityState::EntityState()
272 , orient(1.0f, 0.0f, 0.0f, 0.0f)
278 void EntityState::AdjustPosition() noexcept {
279 while (block_pos.x >= Chunk::width) {
280 block_pos.x -= Chunk::width;
283 while (block_pos.x < 0) {
284 block_pos.x += Chunk::width;
287 while (block_pos.y >= Chunk::height) {
288 block_pos.y -= Chunk::height;
291 while (block_pos.y < 0) {
292 block_pos.y += Chunk::height;
295 while (block_pos.z >= Chunk::depth) {
296 block_pos.z -= Chunk::depth;
299 while (block_pos.z < 0) {
300 block_pos.z += Chunk::depth;
305 void EntityState::AdjustHeading() noexcept {
306 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
315 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
316 const glm::vec3 translation = RelativePosition(reference);
317 glm::mat4 transform(toMat4(orient));
318 transform[3] = glm::vec4(translation, 1.0f);
323 Player::Player(Entity &e, ChunkIndex &c)
334 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
335 if (!spawn_block || spawn_block.GetType().collide_block) {
339 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
340 if (!head_block || head_block.GetType().collide_block) {
347 void Player::Update(int dt) {
348 chunks.Rebase(entity.ChunkCoords());
352 World::World(const BlockTypeRegistry &types, const Config &config)
358 , light_direction(config.light_direction)
359 , fog_density(config.fog_density) {
368 Player *World::AddPlayer(const std::string &name) {
369 for (Player &p : players) {
370 if (p.Name() == name) {
374 Entity &entity = AddEntity();
376 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
377 entity.WorldCollidable(true);
378 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
379 players.emplace_back(entity, index);
380 return &players.back();
383 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
384 for (Player &p : players) {
385 if (p.Name() == name) {
389 Entity *entity = AddEntity(id);
394 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
395 entity->WorldCollidable(true);
396 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
397 players.emplace_back(*entity, index);
398 return &players.back();
401 Entity &World::AddEntity() {
402 if (entities.empty()) {
403 entities.emplace_back();
404 entities.back().ID(1);
405 return entities.back();
407 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
408 std::uint32_t id = entities.back().ID() + 1;
409 entities.emplace_back();
410 entities.back().ID(id);
411 return entities.back();
413 std::uint32_t id = 1;
414 auto position = entities.begin();
415 auto end = entities.end();
416 while (position != end && position->ID() == id) {
420 auto entity = entities.emplace(position);
425 Entity *World::AddEntity(std::uint32_t id) {
426 if (entities.empty() || entities.back().ID() < id) {
427 entities.emplace_back();
428 entities.back().ID(id);
429 return &entities.back();
432 auto position = entities.begin();
433 auto end = entities.end();
434 while (position != end && position->ID() < id) {
437 if (position != end && position->ID() == id) {
440 auto entity = entities.emplace(position);
445 Entity &World::ForceAddEntity(std::uint32_t id) {
446 if (entities.empty() || entities.back().ID() < id) {
447 entities.emplace_back();
448 entities.back().ID(id);
449 return entities.back();
452 auto position = entities.begin();
453 auto end = entities.end();
454 while (position != end && position->ID() < id) {
457 if (position != end && position->ID() == id) {
460 auto entity = entities.emplace(position);
473 bool CandidateLess(const Candidate &a, const Candidate &b) {
474 return a.dist < b.dist;
477 std::vector<Candidate> candidates;
481 bool World::Intersection(
484 const Chunk::Pos &reference,
489 for (Chunk &cur_chunk : chunks) {
491 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
492 candidates.push_back({ &cur_chunk, cur_dist });
496 if (candidates.empty()) return false;
498 std::sort(candidates.begin(), candidates.end(), CandidateLess);
500 coll.chunk = nullptr;
502 coll.depth = std::numeric_limits<float>::infinity();
504 for (Candidate &cand : candidates) {
505 if (cand.dist > coll.depth) continue;
506 WorldCollision cur_coll;
507 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
508 if (cur_coll.depth < coll.depth) {
517 bool World::Intersection(
520 const Entity &reference,
521 EntityCollision &coll
523 coll.entity = nullptr;
524 coll.depth = std::numeric_limits<float>::infinity();
525 for (Entity &cur_entity : entities) {
526 if (&cur_entity == &reference) {
530 glm::vec3 cur_normal;
531 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
532 // TODO: fine grained check goes here? maybe?
533 if (cur_dist < coll.depth) {
534 coll.entity = &cur_entity;
535 coll.depth = cur_dist;
536 coll.normal = cur_normal;
544 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
545 AABB box = e.Bounds();
546 Chunk::Pos reference = s.chunk_pos;
547 glm::mat4 M = s.Transform(reference);
548 return Intersection(box, M, reference, col);
551 bool World::Intersection(
554 const glm::ivec3 &reference,
555 std::vector<WorldCollision> &col
558 for (Chunk &cur_chunk : chunks) {
559 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
560 // chunk is not one of the 3x3x3 surrounding the entity
561 // since there's no entity which can extent over 16 blocks, they can be skipped
564 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
571 void World::Update(int dt) {
572 float fdt(dt * 0.001f);
573 for (Entity &entity : entities) {
576 for (Entity &entity : entities) {
579 for (Player &player : players) {
582 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
583 if (iter->CanRemove()) {
584 iter = RemoveEntity(iter);
591 void World::Update(Entity &entity, float dt) {
592 EntityState state(entity.GetState());
594 EntityDerivative a(CalculateStep(entity, state, 0.0f, EntityDerivative()));
595 EntityDerivative b(CalculateStep(entity, state, dt * 0.5f, a));
596 EntityDerivative c(CalculateStep(entity, state, dt * 0.5f, b));
597 EntityDerivative d(CalculateStep(entity, state, dt, c));
600 constexpr float sixth = 1.0f / 6.0f;
601 f.position = sixth * ((a.position + 2.0f * (b.position + c.position)) + d.position);
602 f.velocity = sixth * ((a.velocity + 2.0f * (b.velocity + c.velocity)) + d.velocity);
604 state.block_pos += f.position * dt;
605 state.velocity += f.velocity * dt;
606 state.AdjustPosition();
608 entity.SetState(state);
611 EntityDerivative World::CalculateStep(
612 const Entity &entity,
613 const EntityState &cur,
615 const EntityDerivative &delta
617 EntityState next(cur);
618 next.block_pos += delta.position * dt;
619 next.velocity += delta.velocity * dt;
620 next.AdjustPosition();
622 if (dot(next.velocity, next.velocity) > entity.MaxVelocity() * entity.MaxVelocity()) {
623 next.velocity = normalize(next.velocity) * entity.MaxVelocity();
626 EntityDerivative out;
627 out.position = next.velocity;
628 out.velocity = CalculateForce(entity, next); // by mass = 1kg
632 glm::vec3 World::CalculateForce(
633 const Entity &entity,
634 const EntityState &state
636 glm::vec3 force(ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state));
637 if (dot(force, force) > entity.MaxControlForce() * entity.MaxControlForce()) {
638 return normalize(force) * entity.MaxControlForce();
644 glm::vec3 World::ControlForce(
645 const Entity &entity,
646 const EntityState &state
648 return entity.ControlForce(state);
653 std::vector<WorldCollision> col;
657 glm::vec3 World::CollisionForce(
658 const Entity &entity,
659 const EntityState &state
662 if (entity.WorldCollidable() && Intersection(entity, state, col)) {
663 // determine displacement for each cardinal axis and move entity accordingly
664 glm::vec3 min_pen(0.0f);
665 glm::vec3 max_pen(0.0f);
666 for (const WorldCollision &c : col) {
667 if (!c.Blocks()) continue;
668 glm::vec3 local_pen(c.normal * c.depth);
669 // swap if neccessary (normal may point away from the entity)
670 if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
673 min_pen = min(min_pen, local_pen);
674 max_pen = max(max_pen, local_pen);
676 glm::vec3 correction(0.0f);
677 // only apply correction for axes where penetration is only in one direction
678 for (std::size_t i = 0; i < 3; ++i) {
679 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
680 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
681 correction[i] = -min_pen[i];
684 correction[i] = -max_pen[i];
687 // correction may be zero in which case normalize() returns NaNs
688 if (dot(correction, correction) < std::numeric_limits<float>::epsilon()) {
689 return glm::vec3(0.0f);
691 glm::vec3 normal(normalize(correction));
692 glm::vec3 normal_velocity(normal * dot(state.velocity, normal));
693 // apply force proportional to penetration
694 // use velocity projected onto normal as damper
695 constexpr float k = 1000.0f; // spring constant
696 constexpr float b = 10.0f; // damper constant
697 const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
698 const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
699 return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
701 return glm::vec3(0.0f);
705 glm::vec3 World::Gravity(
706 const Entity &entity,
707 const EntityState &state
709 return glm::vec3(0.0f);
712 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
714 for (auto player = players.begin(), end = players.end(); player != end;) {
715 if (&player->GetEntity() == &*eh) {
716 chunks.UnregisterIndex(player->GetChunks());
717 player = players.erase(player);
723 return entities.erase(eh);
727 void World::Render(Viewport &viewport) {
728 DirectionalLighting &entity_prog = viewport.EntityProgram();
729 entity_prog.SetFogDensity(fog_density);
733 glm::vec3 ambient_col;
734 for (Entity &entity : entities) {
735 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
736 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
737 GetLight(entity, light_dir, light_col, ambient_col);
738 entity_prog.SetLightDirection(light_dir);
739 entity_prog.SetLightColor(light_col);
740 entity_prog.SetAmbientColor(ambient_col);
741 entity.Render(M, entity_prog);
746 // this should interpolate based on the fractional part of entity's block position
747 void World::GetLight(
753 Chunk *chunk = chunks.Get(e.ChunkCoords());
755 // chunk unavailable, so make it really dark and from
756 // some arbitrary direction
757 dir = glm::vec3(1.0f, 2.0f, 3.0f);
758 col = glm::vec3(0.025f); // ~0.8^15
761 glm::ivec3 base(e.Position());
762 int base_light = chunk->GetLight(base);
765 glm::ivec3 acc(0, 0, 0);
766 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
767 for (offset.y = -1; offset.y < 2; ++offset.y) {
768 for (offset.x = -1; offset.x < 2; ++offset.x) {
769 BlockLookup block(chunk, base + offset);
771 // missing, just ignore it
774 // otherwise, accumulate the difference times direction
775 acc += offset * (base_light - block.GetLight());
776 max_light = std::max(max_light, block.GetLight());
777 min_light = std::min(min_light, block.GetLight());
782 col = glm::vec3(std::pow(0.8f, 15 - max_light));
783 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
788 PrimitiveMesh::Buffer debug_buf;
792 void World::RenderDebug(Viewport &viewport) {
793 PrimitiveMesh debug_mesh;
794 PlainColor &prog = viewport.WorldColorProgram();
795 for (const Entity &entity : entities) {
796 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
797 debug_mesh.Update(debug_buf);
798 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
799 debug_mesh.DrawLines();