2 #include "EntityCollision.hpp"
3 #include "EntityController.hpp"
4 #include "EntityDerivative.hpp"
5 #include "EntityState.hpp"
9 #include "ChunkIndex.hpp"
10 #include "EntityCollision.hpp"
11 #include "WorldCollision.hpp"
12 #include "../app/Assets.hpp"
13 #include "../geometry/const.hpp"
14 #include "../geometry/distance.hpp"
15 #include "../graphics/Format.hpp"
16 #include "../graphics/Viewport.hpp"
22 #include <glm/gtx/euler_angles.hpp>
23 #include <glm/gtx/io.hpp>
24 #include <glm/gtx/projection.hpp>
25 #include <glm/gtx/quaternion.hpp>
26 #include <glm/gtx/rotate_vector.hpp>
27 #include <glm/gtx/transform.hpp>
32 Entity::Entity() noexcept
40 , heading(0.0f, 0.0f, -1.0f)
44 , world_collision(false)
46 , owns_controller(false) {
50 Entity::~Entity() noexcept {
54 Entity::Entity(const Entity &other) noexcept
59 , bounds(other.bounds)
61 , model_transform(1.0f)
62 , view_transform(1.0f)
64 , heading(0.0f, 0.0f, -1.0f)
65 , max_vel(other.max_vel)
66 , max_force(other.max_force)
68 , world_collision(other.world_collision)
70 , owns_controller(false) {
74 void Entity::SetController(EntityController *c) noexcept {
77 owns_controller = true;
80 void Entity::SetController(EntityController &c) noexcept {
83 owns_controller = false;
86 void Entity::UnsetController() noexcept {
87 if (ctrl && owns_controller) {
93 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
95 if (HasController()) {
96 force = GetController().ControlForce(*this, s);
100 limit(force, max_force);
104 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
109 void Entity::Position(const glm::vec3 &pos) noexcept {
110 state.pos.block = pos;
111 state.AdjustPosition();
114 void Entity::TurnHead(float dp, float dy) noexcept {
115 SetHead(state.pitch + dp, state.yaw + dy);
118 void Entity::SetHead(float p, float y) noexcept {
123 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
124 return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
127 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
128 return Transform(reference) * view_transform;
131 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
132 glm::mat4 transform = ViewTransform(chunk_offset);
133 return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
136 void Entity::Update(World &world, float dt) {
137 if (HasController()) {
138 GetController().Update(*this, dt);
140 UpdatePhysics(world, dt);
146 void Entity::UpdatePhysics(World &world, float dt) {
147 EntityState s(state);
149 EntityDerivative a(CalculateStep(world, s, 0.0f, EntityDerivative()));
150 EntityDerivative b(CalculateStep(world, s, dt * 0.5f, a));
151 EntityDerivative c(CalculateStep(world, s, dt * 0.5f, b));
152 EntityDerivative d(CalculateStep(world, s, dt, c));
155 constexpr float sixth = 1.0f / 6.0f;
156 f.position = sixth * (a.position + 2.0f * (b.position + c.position) + d.position);
157 f.velocity = sixth * (a.velocity + 2.0f * (b.velocity + c.velocity) + d.velocity);
159 s.pos.block += f.position * dt;
160 s.velocity += f.velocity * dt;
161 limit(s.velocity, max_vel);
162 world.ResolveWorldCollision(*this, s);
168 EntityDerivative Entity::CalculateStep(
170 const EntityState &cur,
172 const EntityDerivative &delta
174 EntityState next(cur);
175 next.pos.block += delta.position * dt;
176 next.velocity += delta.velocity * dt;
177 limit(next.velocity, max_vel);
178 world.ResolveWorldCollision(*this, next);
179 next.AdjustPosition();
181 EntityDerivative out;
182 out.position = next.velocity;
183 out.velocity = ControlForce(next) + world.GravityAt(next.pos); // by mass = 1kg
188 void Entity::UpdateTransforms() noexcept {
189 // model transform is the one given by current state
190 model_transform = state.Transform(state.pos.chunk);
191 // view transform is either the model's eyes transform or,
192 // should the entity have no model, the pitch (yaw already is
193 // in model transform)
195 view_transform = model.EyesTransform();
197 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
201 void Entity::UpdateHeading() noexcept {
202 speed = length(Velocity());
203 if (speed > std::numeric_limits<float>::epsilon()) {
204 heading = Velocity() / speed;
207 // use -Z (forward axis) of model transform (our "chest")
208 heading = -glm::vec3(model_transform[2]);
212 void Entity::UpdateModel(float dt) noexcept {
213 // first, sanitize the pitch and yaw fields of state (our input)
214 // those indicate the head orientation in the entity's local cosystem
215 state.AdjustHeading();
216 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
221 void Entity::OrientBody(float dt) noexcept {
222 // maximum body rotation per second (due to velocity orientation) (90°)
223 constexpr float max_body_turn_per_second = PI_0p5;
224 const float max_body_turn = max_body_turn_per_second * dt;
225 // minimum speed to apply body correction
226 constexpr float min_speed = 0.0625f;
228 const glm::vec3 up(model_transform[1]);
229 if (speed > min_speed) {
230 // check if our orientation and velocity are aligned
231 const glm::vec3 forward(-model_transform[2]);
232 // facing is local -Z rotated about local Y by yaw and transformed into world space
233 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))));
234 // only adjust if velocity isn't almost parallel to up
235 float vel_dot_up = dot(Velocity(), up);
236 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
237 // get direction of velocity projected onto model plane
238 glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
239 // if velocity points away from our facing (with a little bias), flip it around
240 // (the entity is "walking backwards")
241 if (dot(facing, direction) < -0.1f) {
242 direction = -direction;
244 // calculate the difference between forward and direction
245 const float absolute_difference = std::acos(dot(forward, direction));
246 // if direction is clockwise with respect to up vector, invert the angle
247 const float relative_difference = dot(cross(forward, direction), up) < 0.0f
248 ? -absolute_difference
249 : absolute_difference;
250 // only correct by half the difference max
251 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
253 std::cout << "orientation before: " << state.orient << std::endl;
254 std::cout << "up: " << up << std::endl;
255 std::cout << "forward: " << forward << std::endl;
256 std::cout << "facing: " << facing << std::endl;
257 std::cout << "direction: " << direction << std::endl;
258 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
259 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
260 std::cout << std::endl;
262 // now rotate body by correction and head by -correction
263 state.orient = rotate(state.orient, correction, up);
264 state.yaw -= correction;
269 void Entity::OrientHead(float dt) noexcept {
270 // maximum yaw of head (60°)
271 constexpr float max_head_yaw = PI / 3.0f;
273 const glm::vec3 up(model_transform[1]);
274 // if yaw is bigger than max, rotate the body to accomodate
275 if (std::abs(state.yaw) > max_head_yaw) {
276 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
277 // rotate the entity by deviation about local Y
278 state.orient = rotate(state.orient, deviation, up);
279 // and remove from head yaw
280 state.yaw -= deviation;
281 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
282 state.AdjustHeading();
284 // update model if any
286 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
291 EntityCollision::EntityCollision(Entity *e, float d, const glm::vec3 &n)
300 EntityCollision::~EntityCollision() {
306 EntityCollision::EntityCollision(const EntityCollision &other)
308 , normal(other.normal)
309 , entity(other.entity) {
315 EntityCollision &EntityCollision::operator =(const EntityCollision &other) {
320 normal = other.normal;
321 entity = other.entity;
329 EntityController::~EntityController() {
333 bool EntityController::MaxOutForce(
335 const glm::vec3 &add,
338 if (iszero(add) || any(isnan(add))) {
341 float current = iszero(out) ? 0.0f : length(out);
342 float remain = max - current;
343 if (remain <= 0.0f) {
346 float additional = length(add);
347 if (additional > remain) {
348 out += normalize(add) * remain;
357 EntityState::EntityState()
360 , orient(1.0f, 0.0f, 0.0f, 0.0f)
366 void EntityState::AdjustPosition() noexcept {
370 void EntityState::AdjustHeading() noexcept {
371 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
380 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
381 const glm::vec3 translation = RelativePosition(reference);
382 glm::mat4 transform(toMat4(orient));
383 transform[3] = glm::vec4(translation, 1.0f);
388 Player::Player(Entity &e, ChunkIndex &c)
399 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
400 if (!spawn_block || spawn_block.GetType().collide_block) {
404 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
405 if (!head_block || head_block.GetType().collide_block) {
412 void Player::Update(int dt) {
413 chunks.Rebase(entity.ChunkCoords());
417 World::World(const BlockTypeRegistry &types, const Config &config)
423 , light_direction(config.light_direction)
424 , fog_density(config.fog_density) {
429 for (Entity &e : entities) {
432 std::size_t removed = 0;
435 for (auto e = entities.begin(), end = entities.end(); e != end; ++e) {
436 if (e->CanRemove()) {
438 end = entities.end();
442 } while (removed > 0 && !entities.empty());
446 Player *World::AddPlayer(const std::string &name) {
447 for (Player &p : players) {
448 if (p.Name() == name) {
452 Entity &entity = AddEntity();
454 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
455 entity.WorldCollidable(true);
456 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
457 players.emplace_back(entity, index);
458 return &players.back();
461 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
462 for (Player &p : players) {
463 if (p.Name() == name) {
467 Entity *entity = AddEntity(id);
472 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
473 entity->WorldCollidable(true);
474 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
475 players.emplace_back(*entity, index);
476 return &players.back();
479 Entity &World::AddEntity() {
480 if (entities.empty()) {
481 entities.emplace_back();
482 entities.back().ID(1);
483 return entities.back();
485 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
486 std::uint32_t id = entities.back().ID() + 1;
487 entities.emplace_back();
488 entities.back().ID(id);
489 return entities.back();
491 std::uint32_t id = 1;
492 auto position = entities.begin();
493 auto end = entities.end();
494 while (position != end && position->ID() == id) {
498 auto entity = entities.emplace(position);
503 Entity *World::AddEntity(std::uint32_t id) {
504 if (entities.empty() || entities.back().ID() < id) {
505 entities.emplace_back();
506 entities.back().ID(id);
507 return &entities.back();
510 auto position = entities.begin();
511 auto end = entities.end();
512 while (position != end && position->ID() < id) {
515 if (position != end && position->ID() == id) {
518 auto entity = entities.emplace(position);
523 Entity &World::ForceAddEntity(std::uint32_t id) {
524 if (entities.empty() || entities.back().ID() < id) {
525 entities.emplace_back();
526 entities.back().ID(id);
527 return entities.back();
530 auto position = entities.begin();
531 auto end = entities.end();
532 while (position != end && position->ID() < id) {
535 if (position != end && position->ID() == id) {
538 auto entity = entities.emplace(position);
551 bool CandidateLess(const Candidate &a, const Candidate &b) {
552 return a.dist < b.dist;
555 std::vector<Candidate> candidates;
559 bool World::Intersection(
561 const ExactLocation::Coarse &reference,
566 for (Chunk &cur_chunk : chunks) {
568 if (cur_chunk.Intersection(ray, reference, cur_dist)) {
569 candidates.push_back({ &cur_chunk, cur_dist });
573 if (candidates.empty()) return false;
575 std::sort(candidates.begin(), candidates.end(), CandidateLess);
577 coll.chunk = nullptr;
579 coll.depth = std::numeric_limits<float>::infinity();
581 for (Candidate &cand : candidates) {
582 if (cand.dist > coll.depth) continue;
583 WorldCollision cur_coll;
584 if (cand.chunk->Intersection(ray, reference, cur_coll)) {
585 if (cur_coll.depth < coll.depth) {
594 bool World::Intersection(
596 const Entity &reference,
597 EntityCollision &coll
599 coll = EntityCollision(nullptr, std::numeric_limits<float>::infinity(), glm::vec3(0.0f));
600 for (Entity &cur_entity : entities) {
601 if (&cur_entity == &reference) {
605 glm::vec3 cur_normal;
606 if (blank::Intersection(ray, cur_entity.Bounds(), cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
607 // TODO: fine grained check goes here? maybe?
608 if (cur_dist < coll.depth) {
609 coll = EntityCollision(&cur_entity, cur_dist, cur_normal);
617 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
618 glm::ivec3 reference = s.pos.chunk;
619 glm::mat4 M = s.Transform(reference);
621 ExactLocation::Coarse begin(reference - 1);
622 ExactLocation::Coarse end(reference + 2);
625 for (ExactLocation::Coarse pos(begin); pos.z < end.y; ++pos.z) {
626 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
627 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
628 Chunk *chunk = chunks.Get(pos);
629 if (chunk && chunk->Intersection(e, M, chunk->Transform(reference), col)) {
638 bool World::Intersection(
641 const glm::ivec3 &reference,
642 std::vector<WorldCollision> &col
645 for (Chunk &cur_chunk : chunks) {
646 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
647 // chunk is not one of the 3x3x3 surrounding the entity
648 // since there's no entity which can extent over 16 blocks, they can be skipped
649 // TODO: change to indexed (like with entity)
652 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
659 void World::Update(int dt) {
660 float fdt(dt * 0.001f);
661 for (Entity &entity : entities) {
662 entity.Update(*this, fdt);
664 for (Player &player : players) {
667 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
668 if (iter->CanRemove()) {
669 iter = RemoveEntity(iter);
678 std::vector<WorldCollision> col;
682 void World::ResolveWorldCollision(
683 const Entity &entity,
687 if (!entity.WorldCollidable() || !Intersection(entity, state, col)) {
688 // no collision, no fix
691 glm::vec3 correction = CombinedInterpenetration(state, col);
692 // correction may be zero in which case normalize() returns NaNs
693 if (iszero(correction)) {
696 // if entity is already going in the direction of correction,
697 // let the problem resolve itself
698 if (dot(state.velocity, correction) >= 0.0f) {
701 // apply correction, maybe could use some damping, gotta test
702 state.pos.block += correction;
704 glm::vec3 normal_velocity(proj(state.velocity, correction));
705 state.velocity -= normal_velocity;
708 glm::vec3 World::CombinedInterpenetration(
709 const EntityState &state,
710 const std::vector<WorldCollision> &col
712 // determine displacement for each cardinal axis and move entity accordingly
713 glm::vec3 min_pen(0.0f);
714 glm::vec3 max_pen(0.0f);
715 for (const WorldCollision &c : col) {
716 if (!c.Blocks()) continue;
717 glm::vec3 normal(c.normal);
718 // swap if neccessary (normal may point away from the entity)
719 if (dot(normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) < 0) {
722 // check if block surface is "inside"
723 Block::Face coll_face = Block::NormalFace(normal);
724 BlockLookup neighbor(c.chunk, c.BlockPos(), coll_face);
725 if (neighbor && neighbor.FaceFilled(Block::Opposite(coll_face))) {
726 // yep, so ignore this contact
729 glm::vec3 local_pen(normal * c.depth);
730 min_pen = min(min_pen, local_pen);
731 max_pen = max(max_pen, local_pen);
734 // only apply correction for axes where penetration is only in one direction
735 for (std::size_t i = 0; i < 3; ++i) {
736 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
737 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
747 glm::vec3 World::GravityAt(const ExactLocation &loc) const noexcept {
748 glm::vec3 force(0.0f);
749 ExactLocation::Coarse begin(loc.chunk - 1);
750 ExactLocation::Coarse end(loc.chunk + 2);
752 for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
753 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
754 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
755 const Chunk *chunk = chunks.Get(pos);
757 force += chunk->GravityAt(loc);
766 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
768 for (auto player = players.begin(), end = players.end(); player != end;) {
769 if (&player->GetEntity() == &*eh) {
770 chunks.UnregisterIndex(player->GetChunks());
771 player = players.erase(player);
777 return entities.erase(eh);
781 void World::Render(Viewport &viewport) {
782 DirectionalLighting &entity_prog = viewport.EntityProgram();
783 entity_prog.SetFogDensity(fog_density);
787 glm::vec3 ambient_col;
788 for (Entity &entity : entities) {
789 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
790 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
791 GetLight(entity, light_dir, light_col, ambient_col);
792 entity_prog.SetLightDirection(light_dir);
793 entity_prog.SetLightColor(light_col);
794 entity_prog.SetAmbientColor(ambient_col);
795 entity.Render(M, entity_prog);
800 // this should interpolate based on the fractional part of entity's block position
801 void World::GetLight(
807 BlockLookup center(chunks.Get(e.ChunkCoords()), e.Position());
809 // chunk unavailable, so make it really dark and from
810 // some arbitrary direction
811 dir = glm::vec3(1.0f, 2.0f, 3.0f);
812 col = glm::vec3(0.025f); // ~0.8^15
815 glm::ivec3 base(center.GetBlockPos());
816 int base_light = center.GetLight();
819 glm::ivec3 acc(0, 0, 0);
820 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
821 for (offset.y = -1; offset.y < 2; ++offset.y) {
822 for (offset.x = -1; offset.x < 2; ++offset.x) {
823 BlockLookup block(¢er.GetChunk(), center.GetBlockPos() + offset);
825 // missing, just ignore it
828 // otherwise, accumulate the difference times direction
829 acc += offset * (base_light - block.GetLight());
830 max_light = std::max(max_light, block.GetLight());
831 min_light = std::min(min_light, block.GetLight());
836 col = glm::vec3(std::pow(0.8f, 15 - max_light));
837 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
842 PrimitiveMesh::Buffer debug_buf;
846 void World::RenderDebug(Viewport &viewport) {
847 PrimitiveMesh debug_mesh;
848 PlainColor &prog = viewport.WorldColorProgram();
849 for (const Entity &entity : entities) {
850 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
851 debug_mesh.Update(debug_buf);
852 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
853 debug_mesh.DrawLines();