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
38 , heading(0.0f, 0.0f, -1.0f)
42 , world_collision(false)
44 , owns_controller(false) {
48 Entity::~Entity() noexcept {
52 Entity::Entity(const Entity &other) noexcept
57 , bounds(other.bounds)
59 , model_transform(1.0f)
60 , view_transform(1.0f)
62 , heading(0.0f, 0.0f, -1.0f)
63 , max_vel(other.max_vel)
64 , max_force(other.max_force)
66 , world_collision(other.world_collision)
68 , owns_controller(false) {
72 void Entity::SetController(EntityController *c) noexcept {
75 owns_controller = true;
78 void Entity::SetController(EntityController &c) noexcept {
81 owns_controller = false;
84 void Entity::UnsetController() noexcept {
85 if (ctrl && owns_controller) {
91 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
92 if (HasController()) {
93 return GetController().ControlForce(*this, s);
99 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
104 void Entity::Position(const glm::vec3 &pos) noexcept {
105 state.pos.block = pos;
106 state.AdjustPosition();
109 void Entity::TurnHead(float dp, float dy) noexcept {
110 SetHead(state.pitch + dp, state.yaw + dy);
113 void Entity::SetHead(float p, float y) noexcept {
118 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
119 return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
122 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
123 return Transform(reference) * view_transform;
126 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
127 glm::mat4 transform = ViewTransform(chunk_offset);
128 return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
131 void Entity::Update(float dt) {
134 if (HasController()) {
135 GetController().Update(*this, dt);
140 void Entity::UpdateTransforms() noexcept {
141 // model transform is the one given by current state
142 model_transform = state.Transform(state.pos.chunk);
143 // view transform is either the model's eyes transform or,
144 // should the entity have no model, the pitch (yaw already is
145 // in model transform)
147 view_transform = model.EyesTransform();
149 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
153 void Entity::UpdateHeading() noexcept {
154 speed = length(Velocity());
155 if (speed > std::numeric_limits<float>::epsilon()) {
156 heading = Velocity() / speed;
159 // use -Z (forward axis) of model transform (our "chest")
160 heading = -glm::vec3(model_transform[2]);
164 void Entity::UpdateModel(float dt) noexcept {
165 // first, sanitize the pitch and yaw fields of state (our input)
166 // those indicate the head orientation in the entity's local cosystem
167 state.AdjustHeading();
168 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
173 void Entity::OrientBody(float dt) noexcept {
174 // maximum body rotation per second (due to velocity orientation) (90°)
175 constexpr float max_body_turn_per_second = PI_0p5;
176 const float max_body_turn = max_body_turn_per_second * dt;
177 // minimum speed to apply body correction
178 constexpr float min_speed = 0.0625f;
180 const glm::vec3 up(model_transform[1]);
181 if (speed > min_speed) {
182 // check if our orientation and velocity are aligned
183 const glm::vec3 forward(-model_transform[2]);
184 // facing is local -Z rotated about local Y by yaw and transformed into world space
185 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))));
186 // only adjust if velocity isn't almost parallel to up
187 float vel_dot_up = dot(Velocity(), up);
188 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
189 // get direction of velocity projected onto model plane
190 glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
191 // if velocity points away from our facing (with a little bias), flip it around
192 // (the entity is "walking backwards")
193 if (dot(facing, direction) < -0.1f) {
194 direction = -direction;
196 // calculate the difference between forward and direction
197 const float absolute_difference = std::acos(dot(forward, direction));
198 // if direction is clockwise with respect to up vector, invert the angle
199 const float relative_difference = dot(cross(forward, direction), up) < 0.0f
200 ? -absolute_difference
201 : absolute_difference;
202 // only correct by half the difference max
203 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
205 std::cout << "orientation before: " << state.orient << std::endl;
206 std::cout << "up: " << up << std::endl;
207 std::cout << "forward: " << forward << std::endl;
208 std::cout << "facing: " << facing << std::endl;
209 std::cout << "direction: " << direction << std::endl;
210 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
211 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
212 std::cout << std::endl;
214 // now rotate body by correction and head by -correction
215 state.orient = rotate(state.orient, correction, up);
216 state.yaw -= correction;
221 void Entity::OrientHead(float dt) noexcept {
222 // maximum yaw of head (90°)
223 constexpr float max_head_yaw = PI_0p5;
225 const glm::vec3 up(model_transform[1]);
226 // if yaw is bigger than max, rotate the body to accomodate
227 if (std::abs(state.yaw) > max_head_yaw) {
228 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
229 // rotate the entity by deviation about local Y
230 state.orient = rotate(state.orient, deviation, up);
231 // and remove from head yaw
232 state.yaw -= deviation;
233 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
234 state.AdjustHeading();
236 // update model if any
238 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
243 EntityController::~EntityController() {
247 bool EntityController::MaxOutForce(
249 const glm::vec3 &add,
252 if (iszero(add) || any(isnan(add))) {
255 float current = iszero(out) ? 0.0f : length(out);
256 float remain = max - current;
257 if (remain <= 0.0f) {
260 float additional = length(add);
261 if (additional > remain) {
262 out += normalize(add) * remain;
271 EntityState::EntityState()
274 , orient(1.0f, 0.0f, 0.0f, 0.0f)
280 void EntityState::AdjustPosition() noexcept {
284 void EntityState::AdjustHeading() noexcept {
285 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
294 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
295 const glm::vec3 translation = RelativePosition(reference);
296 glm::mat4 transform(toMat4(orient));
297 transform[3] = glm::vec4(translation, 1.0f);
302 Player::Player(Entity &e, ChunkIndex &c)
313 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
314 if (!spawn_block || spawn_block.GetType().collide_block) {
318 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
319 if (!head_block || head_block.GetType().collide_block) {
326 void Player::Update(int dt) {
327 chunks.Rebase(entity.ChunkCoords());
331 World::World(const BlockTypeRegistry &types, const Config &config)
337 , light_direction(config.light_direction)
338 , fog_density(config.fog_density) {
347 Player *World::AddPlayer(const std::string &name) {
348 for (Player &p : players) {
349 if (p.Name() == name) {
353 Entity &entity = AddEntity();
355 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
356 entity.WorldCollidable(true);
357 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
358 players.emplace_back(entity, index);
359 return &players.back();
362 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
363 for (Player &p : players) {
364 if (p.Name() == name) {
368 Entity *entity = AddEntity(id);
373 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
374 entity->WorldCollidable(true);
375 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
376 players.emplace_back(*entity, index);
377 return &players.back();
380 Entity &World::AddEntity() {
381 if (entities.empty()) {
382 entities.emplace_back();
383 entities.back().ID(1);
384 return entities.back();
386 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
387 std::uint32_t id = entities.back().ID() + 1;
388 entities.emplace_back();
389 entities.back().ID(id);
390 return entities.back();
392 std::uint32_t id = 1;
393 auto position = entities.begin();
394 auto end = entities.end();
395 while (position != end && position->ID() == id) {
399 auto entity = entities.emplace(position);
404 Entity *World::AddEntity(std::uint32_t id) {
405 if (entities.empty() || entities.back().ID() < id) {
406 entities.emplace_back();
407 entities.back().ID(id);
408 return &entities.back();
411 auto position = entities.begin();
412 auto end = entities.end();
413 while (position != end && position->ID() < id) {
416 if (position != end && position->ID() == id) {
419 auto entity = entities.emplace(position);
424 Entity &World::ForceAddEntity(std::uint32_t id) {
425 if (entities.empty() || entities.back().ID() < id) {
426 entities.emplace_back();
427 entities.back().ID(id);
428 return entities.back();
431 auto position = entities.begin();
432 auto end = entities.end();
433 while (position != end && position->ID() < id) {
436 if (position != end && position->ID() == id) {
439 auto entity = entities.emplace(position);
452 bool CandidateLess(const Candidate &a, const Candidate &b) {
453 return a.dist < b.dist;
456 std::vector<Candidate> candidates;
460 bool World::Intersection(
462 const ExactLocation::Coarse &reference,
467 for (Chunk &cur_chunk : chunks) {
469 if (cur_chunk.Intersection(ray, reference, cur_dist)) {
470 candidates.push_back({ &cur_chunk, cur_dist });
474 if (candidates.empty()) return false;
476 std::sort(candidates.begin(), candidates.end(), CandidateLess);
478 coll.chunk = nullptr;
480 coll.depth = std::numeric_limits<float>::infinity();
482 for (Candidate &cand : candidates) {
483 if (cand.dist > coll.depth) continue;
484 WorldCollision cur_coll;
485 if (cand.chunk->Intersection(ray, reference, cur_coll)) {
486 if (cur_coll.depth < coll.depth) {
495 bool World::Intersection(
497 const Entity &reference,
498 EntityCollision &coll
500 coll.entity = nullptr;
501 coll.depth = std::numeric_limits<float>::infinity();
502 for (Entity &cur_entity : entities) {
503 if (&cur_entity == &reference) {
507 glm::vec3 cur_normal;
508 if (blank::Intersection(ray, cur_entity.Bounds(), cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
509 // TODO: fine grained check goes here? maybe?
510 if (cur_dist < coll.depth) {
511 coll.entity = &cur_entity;
512 coll.depth = cur_dist;
513 coll.normal = cur_normal;
521 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
522 // TODO: make special case for entities here and in Chunk::Intersection so entity's bounding radius
523 // doesn't have to be calculated over and over again (sqrt)
524 glm::ivec3 reference = s.pos.chunk;
525 glm::mat4 M = s.Transform(reference);
527 ExactLocation::Coarse begin(reference - 1);
528 ExactLocation::Coarse end(reference + 2);
531 for (ExactLocation::Coarse pos(begin); pos.z < end.y; ++pos.z) {
532 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
533 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
534 Chunk *chunk = chunks.Get(pos);
535 if (chunk && chunk->Intersection(e, M, chunk->Transform(reference), col)) {
544 bool World::Intersection(
547 const glm::ivec3 &reference,
548 std::vector<WorldCollision> &col
551 for (Chunk &cur_chunk : chunks) {
552 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
553 // chunk is not one of the 3x3x3 surrounding the entity
554 // since there's no entity which can extent over 16 blocks, they can be skipped
557 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
564 void World::Update(int dt) {
565 float fdt(dt * 0.001f);
566 for (Entity &entity : entities) {
569 for (Entity &entity : entities) {
572 for (Player &player : players) {
575 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
576 if (iter->CanRemove()) {
577 iter = RemoveEntity(iter);
584 void World::Update(Entity &entity, float dt) {
585 EntityState state(entity.GetState());
587 EntityDerivative a(CalculateStep(entity, state, 0.0f, EntityDerivative()));
588 EntityDerivative b(CalculateStep(entity, state, dt * 0.5f, a));
589 EntityDerivative c(CalculateStep(entity, state, dt * 0.5f, b));
590 EntityDerivative d(CalculateStep(entity, state, dt, c));
593 constexpr float sixth = 1.0f / 6.0f;
594 f.position = sixth * ((a.position + 2.0f * (b.position + c.position)) + d.position);
595 f.velocity = sixth * ((a.velocity + 2.0f * (b.velocity + c.velocity)) + d.velocity);
597 state.pos.block += f.position * dt;
598 state.velocity += f.velocity * dt;
599 state.AdjustPosition();
601 entity.SetState(state);
604 EntityDerivative World::CalculateStep(
605 const Entity &entity,
606 const EntityState &cur,
608 const EntityDerivative &delta
610 EntityState next(cur);
611 next.pos.block += delta.position * dt;
612 next.velocity += delta.velocity * dt;
613 next.AdjustPosition();
615 if (dot(next.velocity, next.velocity) > entity.MaxVelocity() * entity.MaxVelocity()) {
616 next.velocity = normalize(next.velocity) * entity.MaxVelocity();
619 EntityDerivative out;
620 out.position = next.velocity;
621 out.velocity = CalculateForce(entity, next); // by mass = 1kg
625 glm::vec3 World::CalculateForce(
626 const Entity &entity,
627 const EntityState &state
629 glm::vec3 force(ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state));
630 if (dot(force, force) > entity.MaxControlForce() * entity.MaxControlForce()) {
631 return normalize(force) * entity.MaxControlForce();
637 glm::vec3 World::ControlForce(
638 const Entity &entity,
639 const EntityState &state
641 return entity.ControlForce(state);
646 std::vector<WorldCollision> col;
650 glm::vec3 World::CollisionForce(
651 const Entity &entity,
652 const EntityState &state
655 if (entity.WorldCollidable() && Intersection(entity, state, col)) {
656 // determine displacement for each cardinal axis and move entity accordingly
657 glm::vec3 min_pen(0.0f);
658 glm::vec3 max_pen(0.0f);
659 for (const WorldCollision &c : col) {
660 if (!c.Blocks()) continue;
661 glm::vec3 local_pen(c.normal * c.depth);
662 // swap if neccessary (normal may point away from the entity)
663 if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
666 min_pen = min(min_pen, local_pen);
667 max_pen = max(max_pen, local_pen);
669 glm::vec3 correction(0.0f);
670 // only apply correction for axes where penetration is only in one direction
671 for (std::size_t i = 0; i < 3; ++i) {
672 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
673 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
674 correction[i] = -min_pen[i];
677 correction[i] = -max_pen[i];
680 // correction may be zero in which case normalize() returns NaNs
681 if (dot(correction, correction) < std::numeric_limits<float>::epsilon()) {
682 return glm::vec3(0.0f);
684 glm::vec3 normal(normalize(correction));
685 glm::vec3 normal_velocity(normal * dot(state.velocity, normal));
686 // apply force proportional to penetration
687 // use velocity projected onto normal as damper
688 constexpr float k = 1000.0f; // spring constant
689 constexpr float b = 10.0f; // damper constant
690 const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
691 const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
692 return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
694 return glm::vec3(0.0f);
698 glm::vec3 World::Gravity(
699 const Entity &entity,
700 const EntityState &state
702 return glm::vec3(0.0f);
705 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
707 for (auto player = players.begin(), end = players.end(); player != end;) {
708 if (&player->GetEntity() == &*eh) {
709 chunks.UnregisterIndex(player->GetChunks());
710 player = players.erase(player);
716 return entities.erase(eh);
720 void World::Render(Viewport &viewport) {
721 DirectionalLighting &entity_prog = viewport.EntityProgram();
722 entity_prog.SetFogDensity(fog_density);
726 glm::vec3 ambient_col;
727 for (Entity &entity : entities) {
728 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
729 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
730 GetLight(entity, light_dir, light_col, ambient_col);
731 entity_prog.SetLightDirection(light_dir);
732 entity_prog.SetLightColor(light_col);
733 entity_prog.SetAmbientColor(ambient_col);
734 entity.Render(M, entity_prog);
739 // this should interpolate based on the fractional part of entity's block position
740 void World::GetLight(
746 Chunk *chunk = chunks.Get(e.ChunkCoords());
748 // chunk unavailable, so make it really dark and from
749 // some arbitrary direction
750 dir = glm::vec3(1.0f, 2.0f, 3.0f);
751 col = glm::vec3(0.025f); // ~0.8^15
754 glm::ivec3 base(e.Position());
755 int base_light = chunk->GetLight(base);
758 glm::ivec3 acc(0, 0, 0);
759 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
760 for (offset.y = -1; offset.y < 2; ++offset.y) {
761 for (offset.x = -1; offset.x < 2; ++offset.x) {
762 BlockLookup block(chunk, base + offset);
764 // missing, just ignore it
767 // otherwise, accumulate the difference times direction
768 acc += offset * (base_light - block.GetLight());
769 max_light = std::max(max_light, block.GetLight());
770 min_light = std::min(min_light, block.GetLight());
775 col = glm::vec3(std::pow(0.8f, 15 - max_light));
776 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
781 PrimitiveMesh::Buffer debug_buf;
785 void World::RenderDebug(Viewport &viewport) {
786 PrimitiveMesh debug_mesh;
787 PlainColor &prog = viewport.WorldColorProgram();
788 for (const Entity &entity : entities) {
789 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
790 debug_mesh.Update(debug_buf);
791 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
792 debug_mesh.DrawLines();