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/projection.hpp>
24 #include <glm/gtx/quaternion.hpp>
25 #include <glm/gtx/rotate_vector.hpp>
26 #include <glm/gtx/transform.hpp>
31 Entity::Entity() noexcept
39 , heading(0.0f, 0.0f, -1.0f)
43 , world_collision(false)
45 , owns_controller(false) {
49 Entity::~Entity() noexcept {
53 Entity::Entity(const Entity &other) noexcept
58 , bounds(other.bounds)
60 , model_transform(1.0f)
61 , view_transform(1.0f)
63 , heading(0.0f, 0.0f, -1.0f)
64 , max_vel(other.max_vel)
65 , max_force(other.max_force)
67 , world_collision(other.world_collision)
69 , owns_controller(false) {
73 void Entity::SetController(EntityController *c) noexcept {
76 owns_controller = true;
79 void Entity::SetController(EntityController &c) noexcept {
82 owns_controller = false;
85 void Entity::UnsetController() noexcept {
86 if (ctrl && owns_controller) {
92 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
93 if (HasController()) {
94 return GetController().ControlForce(*this, s);
100 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
105 void Entity::Position(const glm::vec3 &pos) noexcept {
106 state.pos.block = pos;
107 state.AdjustPosition();
110 void Entity::TurnHead(float dp, float dy) noexcept {
111 SetHead(state.pitch + dp, state.yaw + dy);
114 void Entity::SetHead(float p, float y) noexcept {
119 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
120 return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
123 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
124 return Transform(reference) * view_transform;
127 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
128 glm::mat4 transform = ViewTransform(chunk_offset);
129 return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
132 void Entity::Update(float dt) {
135 if (HasController()) {
136 GetController().Update(*this, dt);
141 void Entity::UpdateTransforms() noexcept {
142 // model transform is the one given by current state
143 model_transform = state.Transform(state.pos.chunk);
144 // view transform is either the model's eyes transform or,
145 // should the entity have no model, the pitch (yaw already is
146 // in model transform)
148 view_transform = model.EyesTransform();
150 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
154 void Entity::UpdateHeading() noexcept {
155 speed = length(Velocity());
156 if (speed > std::numeric_limits<float>::epsilon()) {
157 heading = Velocity() / speed;
160 // use -Z (forward axis) of model transform (our "chest")
161 heading = -glm::vec3(model_transform[2]);
165 void Entity::UpdateModel(float dt) noexcept {
166 // first, sanitize the pitch and yaw fields of state (our input)
167 // those indicate the head orientation in the entity's local cosystem
168 state.AdjustHeading();
169 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
174 void Entity::OrientBody(float dt) noexcept {
175 // maximum body rotation per second (due to velocity orientation) (90°)
176 constexpr float max_body_turn_per_second = PI_0p5;
177 const float max_body_turn = max_body_turn_per_second * dt;
178 // minimum speed to apply body correction
179 constexpr float min_speed = 0.0625f;
181 const glm::vec3 up(model_transform[1]);
182 if (speed > min_speed) {
183 // check if our orientation and velocity are aligned
184 const glm::vec3 forward(-model_transform[2]);
185 // facing is local -Z rotated about local Y by yaw and transformed into world space
186 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))));
187 // only adjust if velocity isn't almost parallel to up
188 float vel_dot_up = dot(Velocity(), up);
189 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
190 // get direction of velocity projected onto model plane
191 glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
192 // if velocity points away from our facing (with a little bias), flip it around
193 // (the entity is "walking backwards")
194 if (dot(facing, direction) < -0.1f) {
195 direction = -direction;
197 // calculate the difference between forward and direction
198 const float absolute_difference = std::acos(dot(forward, direction));
199 // if direction is clockwise with respect to up vector, invert the angle
200 const float relative_difference = dot(cross(forward, direction), up) < 0.0f
201 ? -absolute_difference
202 : absolute_difference;
203 // only correct by half the difference max
204 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
206 std::cout << "orientation before: " << state.orient << std::endl;
207 std::cout << "up: " << up << std::endl;
208 std::cout << "forward: " << forward << std::endl;
209 std::cout << "facing: " << facing << std::endl;
210 std::cout << "direction: " << direction << std::endl;
211 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
212 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
213 std::cout << std::endl;
215 // now rotate body by correction and head by -correction
216 state.orient = rotate(state.orient, correction, up);
217 state.yaw -= correction;
222 void Entity::OrientHead(float dt) noexcept {
223 // maximum yaw of head (60°)
224 constexpr float max_head_yaw = PI / 3.0f;
226 const glm::vec3 up(model_transform[1]);
227 // if yaw is bigger than max, rotate the body to accomodate
228 if (std::abs(state.yaw) > max_head_yaw) {
229 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
230 // rotate the entity by deviation about local Y
231 state.orient = rotate(state.orient, deviation, up);
232 // and remove from head yaw
233 state.yaw -= deviation;
234 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
235 state.AdjustHeading();
237 // update model if any
239 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
244 EntityController::~EntityController() {
248 bool EntityController::MaxOutForce(
250 const glm::vec3 &add,
253 if (iszero(add) || any(isnan(add))) {
256 float current = iszero(out) ? 0.0f : length(out);
257 float remain = max - current;
258 if (remain <= 0.0f) {
261 float additional = length(add);
262 if (additional > remain) {
263 out += normalize(add) * remain;
272 EntityState::EntityState()
275 , orient(1.0f, 0.0f, 0.0f, 0.0f)
281 void EntityState::AdjustPosition() noexcept {
285 void EntityState::AdjustHeading() noexcept {
286 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
295 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
296 const glm::vec3 translation = RelativePosition(reference);
297 glm::mat4 transform(toMat4(orient));
298 transform[3] = glm::vec4(translation, 1.0f);
303 Player::Player(Entity &e, ChunkIndex &c)
314 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
315 if (!spawn_block || spawn_block.GetType().collide_block) {
319 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
320 if (!head_block || head_block.GetType().collide_block) {
327 void Player::Update(int dt) {
328 chunks.Rebase(entity.ChunkCoords());
332 World::World(const BlockTypeRegistry &types, const Config &config)
338 , light_direction(config.light_direction)
339 , fog_density(config.fog_density) {
344 for (Entity &e : entities) {
347 std::size_t removed = 0;
350 for (auto e = entities.begin(), end = entities.end(); e != end; ++e) {
351 if (e->CanRemove()) {
353 end = entities.end();
357 } while (removed > 0 && !entities.empty());
361 Player *World::AddPlayer(const std::string &name) {
362 for (Player &p : players) {
363 if (p.Name() == name) {
367 Entity &entity = AddEntity();
369 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
370 entity.WorldCollidable(true);
371 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
372 players.emplace_back(entity, index);
373 return &players.back();
376 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
377 for (Player &p : players) {
378 if (p.Name() == name) {
382 Entity *entity = AddEntity(id);
387 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
388 entity->WorldCollidable(true);
389 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
390 players.emplace_back(*entity, index);
391 return &players.back();
394 Entity &World::AddEntity() {
395 if (entities.empty()) {
396 entities.emplace_back();
397 entities.back().ID(1);
398 return entities.back();
400 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
401 std::uint32_t id = entities.back().ID() + 1;
402 entities.emplace_back();
403 entities.back().ID(id);
404 return entities.back();
406 std::uint32_t id = 1;
407 auto position = entities.begin();
408 auto end = entities.end();
409 while (position != end && position->ID() == id) {
413 auto entity = entities.emplace(position);
418 Entity *World::AddEntity(std::uint32_t id) {
419 if (entities.empty() || entities.back().ID() < id) {
420 entities.emplace_back();
421 entities.back().ID(id);
422 return &entities.back();
425 auto position = entities.begin();
426 auto end = entities.end();
427 while (position != end && position->ID() < id) {
430 if (position != end && position->ID() == id) {
433 auto entity = entities.emplace(position);
438 Entity &World::ForceAddEntity(std::uint32_t id) {
439 if (entities.empty() || entities.back().ID() < id) {
440 entities.emplace_back();
441 entities.back().ID(id);
442 return entities.back();
445 auto position = entities.begin();
446 auto end = entities.end();
447 while (position != end && position->ID() < id) {
450 if (position != end && position->ID() == id) {
453 auto entity = entities.emplace(position);
466 bool CandidateLess(const Candidate &a, const Candidate &b) {
467 return a.dist < b.dist;
470 std::vector<Candidate> candidates;
474 bool World::Intersection(
476 const ExactLocation::Coarse &reference,
481 for (Chunk &cur_chunk : chunks) {
483 if (cur_chunk.Intersection(ray, reference, cur_dist)) {
484 candidates.push_back({ &cur_chunk, cur_dist });
488 if (candidates.empty()) return false;
490 std::sort(candidates.begin(), candidates.end(), CandidateLess);
492 coll.chunk = nullptr;
494 coll.depth = std::numeric_limits<float>::infinity();
496 for (Candidate &cand : candidates) {
497 if (cand.dist > coll.depth) continue;
498 WorldCollision cur_coll;
499 if (cand.chunk->Intersection(ray, reference, cur_coll)) {
500 if (cur_coll.depth < coll.depth) {
509 bool World::Intersection(
511 const Entity &reference,
512 EntityCollision &coll
514 coll.entity = nullptr;
515 coll.depth = std::numeric_limits<float>::infinity();
516 for (Entity &cur_entity : entities) {
517 if (&cur_entity == &reference) {
521 glm::vec3 cur_normal;
522 if (blank::Intersection(ray, cur_entity.Bounds(), cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
523 // TODO: fine grained check goes here? maybe?
524 if (cur_dist < coll.depth) {
525 coll.entity = &cur_entity;
526 coll.depth = cur_dist;
527 coll.normal = cur_normal;
535 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
536 // TODO: make special case for entities here and in Chunk::Intersection so entity's bounding radius
537 // doesn't have to be calculated over and over again (sqrt)
538 glm::ivec3 reference = s.pos.chunk;
539 glm::mat4 M = s.Transform(reference);
541 ExactLocation::Coarse begin(reference - 1);
542 ExactLocation::Coarse end(reference + 2);
545 for (ExactLocation::Coarse pos(begin); pos.z < end.y; ++pos.z) {
546 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
547 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
548 Chunk *chunk = chunks.Get(pos);
549 if (chunk && chunk->Intersection(e, M, chunk->Transform(reference), col)) {
558 bool World::Intersection(
561 const glm::ivec3 &reference,
562 std::vector<WorldCollision> &col
565 for (Chunk &cur_chunk : chunks) {
566 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
567 // chunk is not one of the 3x3x3 surrounding the entity
568 // since there's no entity which can extent over 16 blocks, they can be skipped
571 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
578 void World::Update(int dt) {
579 float fdt(dt * 0.001f);
580 for (Entity &entity : entities) {
583 for (Entity &entity : entities) {
586 for (Player &player : players) {
589 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
590 if (iter->CanRemove()) {
591 iter = RemoveEntity(iter);
598 void World::Update(Entity &entity, float dt) {
599 EntityState state(entity.GetState());
601 EntityDerivative a(CalculateStep(entity, state, 0.0f, EntityDerivative()));
602 EntityDerivative b(CalculateStep(entity, state, dt * 0.5f, a));
603 EntityDerivative c(CalculateStep(entity, state, dt * 0.5f, b));
604 EntityDerivative d(CalculateStep(entity, state, dt, c));
607 constexpr float sixth = 1.0f / 6.0f;
608 f.position = sixth * ((a.position + 2.0f * (b.position + c.position)) + d.position);
609 f.velocity = sixth * ((a.velocity + 2.0f * (b.velocity + c.velocity)) + d.velocity);
611 state.pos.block += f.position * dt;
612 state.velocity += f.velocity * dt;
613 state.AdjustPosition();
615 entity.SetState(state);
618 EntityDerivative World::CalculateStep(
619 const Entity &entity,
620 const EntityState &cur,
622 const EntityDerivative &delta
624 EntityState next(cur);
625 next.pos.block += delta.position * dt;
626 next.velocity += delta.velocity * dt;
627 next.AdjustPosition();
629 if (dot(next.velocity, next.velocity) > entity.MaxVelocity() * entity.MaxVelocity()) {
630 next.velocity = normalize(next.velocity) * entity.MaxVelocity();
633 EntityDerivative out;
634 out.position = next.velocity;
635 out.velocity = CalculateForce(entity, next); // by mass = 1kg
639 glm::vec3 World::CalculateForce(
640 const Entity &entity,
641 const EntityState &state
643 glm::vec3 force(ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state));
644 if (dot(force, force) > entity.MaxControlForce() * entity.MaxControlForce()) {
645 return normalize(force) * entity.MaxControlForce();
651 glm::vec3 World::ControlForce(
652 const Entity &entity,
653 const EntityState &state
655 return entity.ControlForce(state);
660 std::vector<WorldCollision> col;
664 glm::vec3 World::CollisionForce(
665 const Entity &entity,
666 const EntityState &state
669 if (entity.WorldCollidable() && Intersection(entity, state, col)) {
670 glm::vec3 correction = -CombinedInterpenetration(state, col);
671 // correction may be zero in which case normalize() returns NaNs
672 if (iszero(correction)) {
673 return glm::vec3(0.0f);
675 // if entity is already going in the direction of correction,
676 // let the problem resolve itself
677 if (dot(state.velocity, correction) >= 0.0f) {
678 return glm::vec3(0.0f);
680 glm::vec3 normal_velocity(proj(state.velocity, correction));
681 // apply force proportional to penetration
682 // use velocity projected onto correction as damper
683 constexpr float k = 1000.0f; // spring constant
684 constexpr float b = 10.0f; // damper constant
685 const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
686 const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
687 return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
689 return glm::vec3(0.0f);
693 glm::vec3 World::CombinedInterpenetration(
694 const EntityState &state,
695 const std::vector<WorldCollision> &col
697 // determine displacement for each cardinal axis and move entity accordingly
698 glm::vec3 min_pen(0.0f);
699 glm::vec3 max_pen(0.0f);
700 for (const WorldCollision &c : col) {
701 if (!c.Blocks()) continue;
702 glm::vec3 local_pen(c.normal * c.depth);
703 // swap if neccessary (normal may point away from the entity)
704 if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
707 min_pen = min(min_pen, local_pen);
708 max_pen = max(max_pen, local_pen);
711 // only apply correction for axes where penetration is only in one direction
712 for (std::size_t i = 0; i < 3; ++i) {
713 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
714 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
724 glm::vec3 World::Gravity(
725 const Entity &entity,
726 const EntityState &state
728 return glm::vec3(0.0f);
731 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
733 for (auto player = players.begin(), end = players.end(); player != end;) {
734 if (&player->GetEntity() == &*eh) {
735 chunks.UnregisterIndex(player->GetChunks());
736 player = players.erase(player);
742 return entities.erase(eh);
746 void World::Render(Viewport &viewport) {
747 DirectionalLighting &entity_prog = viewport.EntityProgram();
748 entity_prog.SetFogDensity(fog_density);
752 glm::vec3 ambient_col;
753 for (Entity &entity : entities) {
754 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
755 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
756 GetLight(entity, light_dir, light_col, ambient_col);
757 entity_prog.SetLightDirection(light_dir);
758 entity_prog.SetLightColor(light_col);
759 entity_prog.SetAmbientColor(ambient_col);
760 entity.Render(M, entity_prog);
765 // this should interpolate based on the fractional part of entity's block position
766 void World::GetLight(
772 Chunk *chunk = chunks.Get(e.ChunkCoords());
774 // chunk unavailable, so make it really dark and from
775 // some arbitrary direction
776 dir = glm::vec3(1.0f, 2.0f, 3.0f);
777 col = glm::vec3(0.025f); // ~0.8^15
780 glm::ivec3 base(e.Position());
781 int base_light = chunk->GetLight(base);
784 glm::ivec3 acc(0, 0, 0);
785 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
786 for (offset.y = -1; offset.y < 2; ++offset.y) {
787 for (offset.x = -1; offset.x < 2; ++offset.x) {
788 BlockLookup block(chunk, base + offset);
790 // missing, just ignore it
793 // otherwise, accumulate the difference times direction
794 acc += offset * (base_light - block.GetLight());
795 max_light = std::max(max_light, block.GetLight());
796 min_light = std::min(min_light, block.GetLight());
801 col = glm::vec3(std::pow(0.8f, 15 - max_light));
802 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
807 PrimitiveMesh::Buffer debug_buf;
811 void World::RenderDebug(Viewport &viewport) {
812 PrimitiveMesh debug_mesh;
813 PlainColor &prog = viewport.WorldColorProgram();
814 for (const Entity &entity : entities) {
815 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
816 debug_mesh.Update(debug_buf);
817 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
818 debug_mesh.DrawLines();