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 "../geometry/const.hpp"
13 #include "../geometry/distance.hpp"
14 #include "../graphics/Format.hpp"
15 #include "../graphics/Viewport.hpp"
21 #include <glm/gtx/euler_angles.hpp>
22 #include <glm/gtx/io.hpp>
23 #include <glm/gtx/quaternion.hpp>
24 #include <glm/gtx/rotate_vector.hpp>
25 #include <glm/gtx/transform.hpp>
30 Entity::Entity() noexcept
37 , heading(0.0f, 0.0f, -1.0f)
41 , world_collision(false)
43 , owns_controller(false) {
47 Entity::~Entity() noexcept {
51 Entity::Entity(const Entity &other) noexcept
56 , bounds(other.bounds)
58 , model_transform(1.0f)
59 , view_transform(1.0f)
61 , heading(0.0f, 0.0f, -1.0f)
62 , max_vel(other.max_vel)
63 , max_force(other.max_force)
65 , world_collision(other.world_collision)
67 , owns_controller(false) {
71 void Entity::SetController(EntityController *c) noexcept {
74 owns_controller = true;
77 void Entity::SetController(EntityController &c) noexcept {
80 owns_controller = false;
83 void Entity::UnsetController() noexcept {
84 if (ctrl && owns_controller) {
90 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
91 if (HasController()) {
92 return GetController().ControlForce(*this, s);
98 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
103 void Entity::Position(const glm::vec3 &pos) noexcept {
104 state.block_pos = pos;
105 state.AdjustPosition();
108 void Entity::TurnHead(float dp, float dy) noexcept {
109 SetHead(state.pitch + dp, state.yaw + dy);
112 void Entity::SetHead(float p, float y) noexcept {
117 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
118 return glm::translate(glm::vec3((state.chunk_pos - reference) * Chunk::Extent())) * model_transform;
121 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
122 return Transform(reference) * view_transform;
125 Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
126 glm::mat4 transform = ViewTransform(chunk_offset);
127 return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
130 void Entity::Update(float dt) {
133 if (HasController()) {
134 GetController().Update(*this, dt);
139 void Entity::UpdateTransforms() noexcept {
140 // model transform is the one given by current state
141 model_transform = state.Transform(state.chunk_pos);
142 // view transform is either the model's eyes transform or,
143 // should the entity have no model, the pitch (yaw already is
144 // in model transform)
146 view_transform = model.EyesTransform();
148 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
152 void Entity::UpdateHeading() noexcept {
153 speed = length(Velocity());
154 if (speed > std::numeric_limits<float>::epsilon()) {
155 heading = Velocity() / speed;
158 // use -Z (forward axis) of model transform (our "chest")
159 heading = -glm::vec3(model_transform[2]);
163 void Entity::UpdateModel(float dt) noexcept {
164 // first, sanitize the pitch and yaw fields of state (our input)
165 // those indicate the head orientation in the entity's local cosystem
166 state.AdjustHeading();
167 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
172 void Entity::OrientBody(float dt) noexcept {
173 // maximum body rotation per second (due to velocity orientation) (90°)
174 constexpr float max_body_turn_per_second = PI_0p5;
175 const float max_body_turn = max_body_turn_per_second * dt;
176 // minimum speed to apply body correction
177 constexpr float min_speed = 0.0625f;
179 const glm::vec3 up(model_transform[1]);
180 if (speed > min_speed) {
181 // check if our orientation and velocity are aligned
182 const glm::vec3 forward(-model_transform[2]);
183 // facing is local -Z rotated about local Y by yaw and transformed into world space
184 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))));
185 // only adjust if velocity isn't almost parallel to up
186 float vel_dot_up = dot(Velocity(), up);
187 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
188 // get direction of velocity projected onto model plane
189 glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
190 // if velocity points away from our facing (with a little bias), flip it around
191 // (the entity is "walking backwards")
192 if (dot(facing, direction) < -0.1f) {
193 direction = -direction;
195 // calculate the difference between forward and direction
196 const float absolute_difference = std::acos(dot(forward, direction));
197 // if direction is clockwise with respect to up vector, invert the angle
198 const float relative_difference = dot(cross(forward, direction), up) < 0.0f
199 ? -absolute_difference
200 : absolute_difference;
201 // only correct by half the difference max
202 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
204 std::cout << "orientation before: " << state.orient << std::endl;
205 std::cout << "up: " << up << std::endl;
206 std::cout << "forward: " << forward << std::endl;
207 std::cout << "facing: " << facing << std::endl;
208 std::cout << "direction: " << direction << std::endl;
209 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
210 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
211 std::cout << std::endl;
213 // now rotate body by correction and head by -correction
214 state.orient = rotate(state.orient, correction, up);
215 state.yaw -= correction;
220 void Entity::OrientHead(float dt) noexcept {
221 // maximum yaw of head (90°)
222 constexpr float max_head_yaw = PI_0p5;
224 const glm::vec3 up(model_transform[1]);
225 // if yaw is bigger than max, rotate the body to accomodate
226 if (std::abs(state.yaw) > max_head_yaw) {
227 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
228 // rotate the entity by deviation about local Y
229 state.orient = rotate(state.orient, deviation, up);
230 // and remove from head yaw
231 state.yaw -= deviation;
232 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
233 state.AdjustHeading();
235 // update model if any
237 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
242 EntityController::~EntityController() {
246 bool EntityController::MaxOutForce(
248 const glm::vec3 &add,
251 if (iszero(add) || any(isnan(add))) {
254 float current = iszero(out) ? 0.0f : length(out);
255 float remain = max - current;
256 if (remain <= 0.0f) {
259 float additional = length(add);
260 if (additional > remain) {
261 out += normalize(add) * remain;
270 EntityState::EntityState()
274 , orient(1.0f, 0.0f, 0.0f, 0.0f)
280 void EntityState::AdjustPosition() noexcept {
281 while (block_pos.x >= Chunk::width) {
282 block_pos.x -= Chunk::width;
285 while (block_pos.x < 0) {
286 block_pos.x += Chunk::width;
289 while (block_pos.y >= Chunk::height) {
290 block_pos.y -= Chunk::height;
293 while (block_pos.y < 0) {
294 block_pos.y += Chunk::height;
297 while (block_pos.z >= Chunk::depth) {
298 block_pos.z -= Chunk::depth;
301 while (block_pos.z < 0) {
302 block_pos.z += Chunk::depth;
307 void EntityState::AdjustHeading() noexcept {
308 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
317 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
318 const glm::vec3 translation = RelativePosition(reference);
319 glm::mat4 transform(toMat4(orient));
320 transform[3] = glm::vec4(translation, 1.0f);
325 Player::Player(Entity &e, ChunkIndex &c)
336 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
337 if (!spawn_block || spawn_block.GetType().collide_block) {
341 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
342 if (!head_block || head_block.GetType().collide_block) {
349 void Player::Update(int dt) {
350 chunks.Rebase(entity.ChunkCoords());
354 World::World(const BlockTypeRegistry &types, const Config &config)
360 , light_direction(config.light_direction)
361 , fog_density(config.fog_density) {
370 Player *World::AddPlayer(const std::string &name) {
371 for (Player &p : players) {
372 if (p.Name() == name) {
376 Entity &entity = AddEntity();
378 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
379 entity.WorldCollidable(true);
380 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
381 players.emplace_back(entity, index);
382 return &players.back();
385 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
386 for (Player &p : players) {
387 if (p.Name() == name) {
391 Entity *entity = AddEntity(id);
396 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
397 entity->WorldCollidable(true);
398 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
399 players.emplace_back(*entity, index);
400 return &players.back();
403 Entity &World::AddEntity() {
404 if (entities.empty()) {
405 entities.emplace_back();
406 entities.back().ID(1);
407 return entities.back();
409 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
410 std::uint32_t id = entities.back().ID() + 1;
411 entities.emplace_back();
412 entities.back().ID(id);
413 return entities.back();
415 std::uint32_t id = 1;
416 auto position = entities.begin();
417 auto end = entities.end();
418 while (position != end && position->ID() == id) {
422 auto entity = entities.emplace(position);
427 Entity *World::AddEntity(std::uint32_t id) {
428 if (entities.empty() || entities.back().ID() < id) {
429 entities.emplace_back();
430 entities.back().ID(id);
431 return &entities.back();
434 auto position = entities.begin();
435 auto end = entities.end();
436 while (position != end && position->ID() < id) {
439 if (position != end && position->ID() == id) {
442 auto entity = entities.emplace(position);
447 Entity &World::ForceAddEntity(std::uint32_t id) {
448 if (entities.empty() || entities.back().ID() < id) {
449 entities.emplace_back();
450 entities.back().ID(id);
451 return entities.back();
454 auto position = entities.begin();
455 auto end = entities.end();
456 while (position != end && position->ID() < id) {
459 if (position != end && position->ID() == id) {
462 auto entity = entities.emplace(position);
475 bool CandidateLess(const Candidate &a, const Candidate &b) {
476 return a.dist < b.dist;
479 std::vector<Candidate> candidates;
483 bool World::Intersection(
486 const Chunk::Pos &reference,
491 for (Chunk &cur_chunk : chunks) {
493 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
494 candidates.push_back({ &cur_chunk, cur_dist });
498 if (candidates.empty()) return false;
500 std::sort(candidates.begin(), candidates.end(), CandidateLess);
502 coll.chunk = nullptr;
504 coll.depth = std::numeric_limits<float>::infinity();
506 for (Candidate &cand : candidates) {
507 if (cand.dist > coll.depth) continue;
508 WorldCollision cur_coll;
509 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
510 if (cur_coll.depth < coll.depth) {
519 bool World::Intersection(
522 const Entity &reference,
523 EntityCollision &coll
525 coll.entity = nullptr;
526 coll.depth = std::numeric_limits<float>::infinity();
527 for (Entity &cur_entity : entities) {
528 if (&cur_entity == &reference) {
532 glm::vec3 cur_normal;
533 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
534 // TODO: fine grained check goes here? maybe?
535 if (cur_dist < coll.depth) {
536 coll.entity = &cur_entity;
537 coll.depth = cur_dist;
538 coll.normal = cur_normal;
546 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
547 AABB box = e.Bounds();
548 Chunk::Pos reference = s.chunk_pos;
549 glm::mat4 M = s.Transform(reference);
550 return Intersection(box, M, reference, col);
553 bool World::Intersection(
556 const glm::ivec3 &reference,
557 std::vector<WorldCollision> &col
560 for (Chunk &cur_chunk : chunks) {
561 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
562 // chunk is not one of the 3x3x3 surrounding the entity
563 // since there's no entity which can extent over 16 blocks, they can be skipped
566 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
573 void World::Update(int dt) {
574 float fdt(dt * 0.001f);
575 for (Entity &entity : entities) {
578 for (Entity &entity : entities) {
581 for (Player &player : players) {
584 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
585 if (iter->CanRemove()) {
586 iter = RemoveEntity(iter);
593 void World::Update(Entity &entity, float dt) {
594 EntityState state(entity.GetState());
596 EntityDerivative a(CalculateStep(entity, state, 0.0f, EntityDerivative()));
597 EntityDerivative b(CalculateStep(entity, state, dt * 0.5f, a));
598 EntityDerivative c(CalculateStep(entity, state, dt * 0.5f, b));
599 EntityDerivative d(CalculateStep(entity, state, dt, c));
602 constexpr float sixth = 1.0f / 6.0f;
603 f.position = sixth * ((a.position + 2.0f * (b.position + c.position)) + d.position);
604 f.velocity = sixth * ((a.velocity + 2.0f * (b.velocity + c.velocity)) + d.velocity);
606 state.block_pos += f.position * dt;
607 state.velocity += f.velocity * dt;
608 state.AdjustPosition();
610 entity.SetState(state);
613 EntityDerivative World::CalculateStep(
614 const Entity &entity,
615 const EntityState &cur,
617 const EntityDerivative &delta
619 EntityState next(cur);
620 next.block_pos += delta.position * dt;
621 next.velocity += delta.velocity * dt;
622 next.AdjustPosition();
624 if (dot(next.velocity, next.velocity) > entity.MaxVelocity() * entity.MaxVelocity()) {
625 next.velocity = normalize(next.velocity) * entity.MaxVelocity();
628 EntityDerivative out;
629 out.position = next.velocity;
630 out.velocity = CalculateForce(entity, next); // by mass = 1kg
634 glm::vec3 World::CalculateForce(
635 const Entity &entity,
636 const EntityState &state
638 glm::vec3 force(ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state));
639 if (dot(force, force) > entity.MaxControlForce() * entity.MaxControlForce()) {
640 return normalize(force) * entity.MaxControlForce();
646 glm::vec3 World::ControlForce(
647 const Entity &entity,
648 const EntityState &state
650 return entity.ControlForce(state);
655 std::vector<WorldCollision> col;
659 glm::vec3 World::CollisionForce(
660 const Entity &entity,
661 const EntityState &state
664 if (entity.WorldCollidable() && Intersection(entity, state, col)) {
665 // determine displacement for each cardinal axis and move entity accordingly
666 glm::vec3 min_pen(0.0f);
667 glm::vec3 max_pen(0.0f);
668 for (const WorldCollision &c : col) {
669 if (!c.Blocks()) continue;
670 glm::vec3 local_pen(c.normal * c.depth);
671 // swap if neccessary (normal may point away from the entity)
672 if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
675 min_pen = min(min_pen, local_pen);
676 max_pen = max(max_pen, local_pen);
678 glm::vec3 correction(0.0f);
679 // only apply correction for axes where penetration is only in one direction
680 for (std::size_t i = 0; i < 3; ++i) {
681 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
682 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
683 correction[i] = -min_pen[i];
686 correction[i] = -max_pen[i];
689 // correction may be zero in which case normalize() returns NaNs
690 if (dot(correction, correction) < std::numeric_limits<float>::epsilon()) {
691 return glm::vec3(0.0f);
693 glm::vec3 normal(normalize(correction));
694 glm::vec3 normal_velocity(normal * dot(state.velocity, normal));
695 // apply force proportional to penetration
696 // use velocity projected onto normal as damper
697 constexpr float k = 1000.0f; // spring constant
698 constexpr float b = 10.0f; // damper constant
699 const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
700 const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
701 return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
703 return glm::vec3(0.0f);
707 glm::vec3 World::Gravity(
708 const Entity &entity,
709 const EntityState &state
711 return glm::vec3(0.0f);
714 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
716 for (auto player = players.begin(), end = players.end(); player != end;) {
717 if (&player->GetEntity() == &*eh) {
718 chunks.UnregisterIndex(player->GetChunks());
719 player = players.erase(player);
725 return entities.erase(eh);
729 void World::Render(Viewport &viewport) {
730 DirectionalLighting &entity_prog = viewport.EntityProgram();
731 entity_prog.SetFogDensity(fog_density);
735 glm::vec3 ambient_col;
736 for (Entity &entity : entities) {
737 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
738 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
739 GetLight(entity, light_dir, light_col, ambient_col);
740 entity_prog.SetLightDirection(light_dir);
741 entity_prog.SetLightColor(light_col);
742 entity_prog.SetAmbientColor(ambient_col);
743 entity.Render(M, entity_prog);
748 // this should interpolate based on the fractional part of entity's block position
749 void World::GetLight(
755 Chunk *chunk = chunks.Get(e.ChunkCoords());
757 // chunk unavailable, so make it really dark and from
758 // some arbitrary direction
759 dir = glm::vec3(1.0f, 2.0f, 3.0f);
760 col = glm::vec3(0.025f); // ~0.8^15
763 glm::ivec3 base(e.Position());
764 int base_light = chunk->GetLight(base);
767 glm::ivec3 acc(0, 0, 0);
768 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
769 for (offset.y = -1; offset.y < 2; ++offset.y) {
770 for (offset.x = -1; offset.x < 2; ++offset.x) {
771 BlockLookup block(chunk, base + offset);
773 // missing, just ignore it
776 // otherwise, accumulate the difference times direction
777 acc += offset * (base_light - block.GetLight());
778 max_light = std::max(max_light, block.GetLight());
779 min_light = std::min(min_light, block.GetLight());
784 col = glm::vec3(std::pow(0.8f, 15 - max_light));
785 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
790 PrimitiveMesh::Buffer debug_buf;
794 void World::RenderDebug(Viewport &viewport) {
795 PrimitiveMesh debug_mesh;
796 PlainColor &prog = viewport.WorldColorProgram();
797 for (const Entity &entity : entities) {
798 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
799 debug_mesh.Update(debug_buf);
800 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
801 debug_mesh.DrawLines();