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 "../geometry/rotation.hpp"
16 #include "../graphics/Format.hpp"
17 #include "../graphics/Viewport.hpp"
23 #include <glm/gtx/euler_angles.hpp>
24 #include <glm/gtx/io.hpp>
25 #include <glm/gtx/projection.hpp>
26 #include <glm/gtx/quaternion.hpp>
27 #include <glm/gtx/rotate_vector.hpp>
28 #include <glm/gtx/transform.hpp>
35 /// used as a buffer for merging collisions
36 std::vector<WorldCollision> col;
40 Entity::Entity() noexcept
49 , model_transform(1.0f)
50 , view_transform(1.0f)
52 , heading(0.0f, 0.0f, -1.0f)
56 , world_collision(false)
58 , owns_controller(false) {
62 Entity::~Entity() noexcept {
66 Entity::Entity(const Entity &other) noexcept
72 , bounds(other.bounds)
74 , model_transform(1.0f)
75 , view_transform(1.0f)
77 , heading(0.0f, 0.0f, -1.0f)
78 , max_vel(other.max_vel)
79 , max_force(other.max_force)
81 , world_collision(other.world_collision)
83 , owns_controller(false) {
87 void Entity::SetController(EntityController *c) noexcept {
90 owns_controller = true;
93 void Entity::SetController(EntityController &c) noexcept {
96 owns_controller = false;
99 void Entity::UnsetController() noexcept {
100 if (ctrl && owns_controller) {
106 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
107 return steering.Force(s);
110 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
115 void Entity::Position(const glm::vec3 &pos) noexcept {
116 state.pos.block = pos;
117 state.AdjustPosition();
120 void Entity::TurnHead(float dp, float dy) noexcept {
121 SetHead(state.pitch + dp, state.yaw + dy);
124 void Entity::SetHead(float p, float y) noexcept {
129 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
130 return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
133 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
134 return Transform(reference) * view_transform;
137 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
138 glm::mat4 transform = ViewTransform(chunk_offset);
139 Ray ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]), { } };
144 void Entity::Update(World &world, float dt) {
145 if (HasController()) {
146 GetController().Update(*this, dt);
148 steering.Update(world, dt);
149 UpdatePhysics(world, dt);
155 void Entity::UpdatePhysics(World &world, float dt) {
156 EntityState s(state);
158 EntityDerivative a(CalculateStep(world, s, 0.0f, EntityDerivative()));
159 EntityDerivative b(CalculateStep(world, s, dt * 0.5f, a));
160 EntityDerivative c(CalculateStep(world, s, dt * 0.5f, b));
161 EntityDerivative d(CalculateStep(world, s, dt, c));
164 constexpr float sixth = 1.0f / 6.0f;
165 f.position = sixth * (a.position + 2.0f * (b.position + c.position) + d.position);
166 f.velocity = sixth * (a.velocity + 2.0f * (b.velocity + c.velocity) + d.velocity);
168 s.pos.block += f.position * dt;
169 s.velocity += f.velocity * dt;
170 limit(s.velocity, max_vel);
171 world.ResolveWorldCollision(*this, s);
177 EntityDerivative Entity::CalculateStep(
179 const EntityState &cur,
181 const EntityDerivative &delta
183 EntityState next(cur);
184 next.pos.block += delta.position * dt;
185 next.velocity += delta.velocity * dt;
186 limit(next.velocity, max_vel);
187 next.AdjustPosition();
189 EntityDerivative out;
190 out.position = next.velocity;
191 out.velocity = ControlForce(next) + world.GravityAt(next.pos); // by mass = 1kg
196 void Entity::UpdateTransforms() noexcept {
197 // model transform is the one given by current state
198 model_transform = state.Transform(state.pos.chunk);
199 // view transform is either the model's eyes transform or,
200 // should the entity have no model, the pitch (yaw already is
201 // in model transform)
203 view_transform = model.EyesTransform();
205 view_transform = glm::toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
209 void Entity::UpdateHeading() noexcept {
210 speed = glm::length(Velocity());
211 if (speed > std::numeric_limits<float>::epsilon()) {
212 heading = Velocity() / speed;
215 // use -Z (forward axis) of model transform (our "chest")
216 heading = -glm::vec3(model_transform[2]);
220 void Entity::UpdateModel(float dt) noexcept {
221 // first, sanitize the pitch and yaw fields of state (our input)
222 // those indicate the head orientation in the entity's local cosystem
223 state.AdjustHeading();
224 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
229 void Entity::OrientBody(float dt) noexcept {
230 // maximum body rotation per second (due to velocity orientation) (90°)
231 constexpr float max_body_turn_per_second = PI_0p5;
232 const float max_body_turn = max_body_turn_per_second * dt;
233 // minimum speed to apply body correction
234 constexpr float min_speed = 0.0625f;
236 const glm::vec3 up(model_transform[1]);
237 if (speed > min_speed) {
238 // check if our orientation and velocity are aligned
239 const glm::vec3 forward(-model_transform[2]);
240 // facing is local -Z rotated about local Y by yaw and transformed into world space
241 const glm::vec3 facing(glm::normalize(glm::vec3(glm::vec4(glm::rotateY(glm::vec3(0.0f, 0.0f, -1.0f), state.yaw), 0.0f) * glm::transpose(model_transform))));
242 // only adjust if velocity isn't almost parallel to up
243 float vel_dot_up = glm::dot(Velocity(), up);
244 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
245 // get direction of velocity projected onto model plane
246 glm::vec3 direction(glm::normalize(Velocity() - (Velocity() * vel_dot_up)));
247 // if velocity points away from our facing (with a little bias), flip it around
248 // (the entity is "walking backwards")
249 if (glm::dot(facing, direction) < -0.1f) {
250 direction = -direction;
252 // calculate the difference between forward and direction
253 const float absolute_difference = std::acos(glm::dot(forward, direction));
254 // if direction is clockwise with respect to up vector, invert the angle
255 const float relative_difference = glm::dot(glm::cross(forward, direction), up) < 0.0f
256 ? -absolute_difference
257 : absolute_difference;
258 // only correct by half the difference max
259 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
261 std::cout << "orientation before: " << state.orient << std::endl;
262 std::cout << "up: " << up << std::endl;
263 std::cout << "forward: " << forward << std::endl;
264 std::cout << "facing: " << facing << std::endl;
265 std::cout << "direction: " << direction << std::endl;
266 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
267 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
268 std::cout << std::endl;
270 // now rotate body by correction and head by -correction
271 state.orient = glm::rotate(state.orient, correction, up);
272 state.yaw -= correction;
277 void Entity::OrientHead(float) noexcept {
278 // maximum yaw of head (60°)
279 constexpr float max_head_yaw = PI / 3.0f;
281 const glm::vec3 up(model_transform[1]);
282 // if yaw is bigger than max, rotate the body to accomodate
283 if (std::abs(state.yaw) > max_head_yaw) {
284 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
285 // rotate the entity by deviation about local Y
286 state.orient = glm::rotate(state.orient, deviation, up);
287 // and remove from head yaw
288 state.yaw -= deviation;
289 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
290 state.AdjustHeading();
292 // update model if any
294 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
299 EntityCollision::EntityCollision(Entity *e, float d, const glm::vec3 &n)
308 EntityCollision::~EntityCollision() {
314 EntityCollision::EntityCollision(const EntityCollision &other)
316 , normal(other.normal)
317 , entity(other.entity) {
323 EntityCollision &EntityCollision::operator =(const EntityCollision &other) {
328 normal = other.normal;
329 entity = other.entity;
337 EntityController::~EntityController() {
342 EntityState::EntityState()
345 , orient(1.0f, 0.0f, 0.0f, 0.0f)
351 void EntityState::AdjustPosition() noexcept {
355 void EntityState::AdjustHeading() noexcept {
356 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
365 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
366 const glm::vec3 translation = RelativePosition(reference);
367 glm::mat4 transform(glm::toMat4(orient));
368 transform[3] = glm::vec4(translation, 1.0f);
373 Player::Player(Entity &e, ChunkIndex &c)
384 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
385 if (!spawn_block || spawn_block.GetType().collide_block) {
389 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
390 if (!head_block || head_block.GetType().collide_block) {
397 void Player::Update(int) {
398 chunks.Rebase(entity.ChunkCoords());
402 Steering::Steering(const Entity &e)
404 , target_entity(nullptr)
405 , target_velocity(0.0f)
407 , speed(entity.MaxVelocity())
408 , wander_radius(1.0f)
411 , wander_pos(1.0f, 0.0f, 0.0f)
417 Steering::~Steering() {
421 Steering &Steering::SetTargetEntity(Entity &e) noexcept {
428 Steering &Steering::ClearTargetEntity() noexcept {
430 target_entity->UnRef();
431 target_entity = nullptr;
436 void Steering::Update(World &world, float dt) {
437 if (AnyEnabled(WANDER)) {
438 UpdateWander(world, dt);
440 if (AnyEnabled(OBSTACLE_AVOIDANCE)) {
441 UpdateObstacle(world);
445 void Steering::UpdateWander(World &world, float dt) {
446 glm::vec3 displacement(
447 world.Random().SNorm() * wander_disp,
448 world.Random().SNorm() * wander_disp,
449 world.Random().SNorm() * wander_disp
451 if (!iszero(displacement)) {
452 wander_pos = glm::normalize(wander_pos + displacement * dt) * wander_radius;
456 void Steering::UpdateObstacle(World &world) {
457 if (!entity.Moving()) {
458 obstacle_dir = glm::vec3(0.0f);
461 AABB box(entity.Bounds());
462 box.min.z = -entity.Speed();
464 glm::mat4 transform(find_rotation(glm::vec3(0.0f, 0.0f, -1.0f), entity.Heading()));
465 transform[3] = glm::vec4(entity.Position(), 1.0f);
466 // check if that box intersects with any blocks
468 if (!world.Intersection(box, transform, entity.ChunkCoords(), col)) {
469 obstacle_dir = glm::vec3(0.0f);
472 // if so, pick the nearest collision
473 const WorldCollision *nearest = nullptr;
474 glm::vec3 difference(0.0f);
475 float distance = std::numeric_limits<float>::infinity();
476 for (const WorldCollision &c : col) {
477 // diff points from block to state
478 glm::vec3 diff = entity.GetState().RelativePosition(c.ChunkPos()) - c.BlockCoords();
479 float dist = glm::length2(diff);
480 if (dist < distance) {
487 // intersection test lied to us
488 obstacle_dir = glm::vec3(0.0f);
491 // and try to avoid it
492 float to_go = glm::dot(difference, entity.Heading());
493 glm::vec3 point(entity.Position() + entity.Heading() * to_go);
494 obstacle_dir = glm::normalize(point - nearest->BlockCoords()) * (entity.Speed() / std::sqrt(distance));
497 glm::vec3 Steering::Force(const EntityState &state) const noexcept {
498 glm::vec3 force(0.0f);
502 const float max = entity.MaxControlForce();
503 if (AnyEnabled(HALT)) {
504 if (SumForce(force, Halt(state), max)) {
508 if (AnyEnabled(TARGET_VELOCITY)) {
509 if (SumForce(force, TargetVelocity(state, target_velocity), max)) {
513 if (AnyEnabled(OBSTACLE_AVOIDANCE)) {
514 if (SumForce(force, ObstacleAvoidance(state), max)) {
518 if (AnyEnabled(EVADE_TARGET)) {
519 if (HasTargetEntity()) {
520 if (SumForce(force, Evade(state, GetTargetEntity()), max)) {
524 std::cout << "Steering: evade enabled, but target entity not set" << std::endl;
527 if (AnyEnabled(PURSUE_TARGET)) {
528 if (HasTargetEntity()) {
529 if (SumForce(force, Pursuit(state, GetTargetEntity()), max)) {
533 std::cout << "Steering: pursuit enabled, but target entity not set" << std::endl;
536 if (AnyEnabled(WANDER)) {
537 if (SumForce(force, Wander(state), max)) {
544 bool Steering::SumForce(glm::vec3 &out, const glm::vec3 &in, float max) noexcept {
545 if (iszero(in) || glm::any(glm::isnan(in))) {
548 float current = iszero(out) ? 0.0f : glm::length(out);
549 float remain = max - current;
550 if (remain <= 0.0f) {
553 float additional = glm::length(in);
554 if (additional > remain) {
555 out += glm::normalize(in) * remain;
563 glm::vec3 Steering::Halt(const EntityState &state) const noexcept {
564 return state.velocity * -accel;
567 glm::vec3 Steering::TargetVelocity(const EntityState &state, const glm::vec3 &vel) const noexcept {
568 return (vel - state.velocity) * accel;
571 glm::vec3 Steering::Seek(const EntityState &state, const ExactLocation &loc) const noexcept {
572 const glm::vec3 diff(loc.Difference(state.pos).Absolute());
574 return glm::vec3(0.0f);
576 return TargetVelocity(state, glm::normalize(diff) * speed);
580 glm::vec3 Steering::Flee(const EntityState &state, const ExactLocation &loc) const noexcept {
581 const glm::vec3 diff(state.pos.Difference(loc).Absolute());
583 return glm::vec3(0.0f);
585 return TargetVelocity(state, glm::normalize(diff) * speed);
589 glm::vec3 Steering::Arrive(const EntityState &state, const ExactLocation &loc) const noexcept {
590 const glm::vec3 diff(loc.Difference(state.pos).Absolute());
591 const float dist = glm::length(diff);
592 if (dist < std::numeric_limits<float>::epsilon()) {
593 return glm::vec3(0.0f);
595 const float att_speed = std::min(dist * accel, speed);
596 return TargetVelocity(state, diff * att_speed / dist);
600 glm::vec3 Steering::Pursuit(const EntityState &state, const Entity &other) const noexcept {
601 const glm::vec3 diff(state.Diff(other.GetState()));
603 return TargetVelocity(state, other.Velocity());
605 const float time_estimate = glm::length(diff) / speed;
606 ExactLocation prediction(other.ChunkCoords(), other.Position() + (other.Velocity() * time_estimate));
607 return Seek(state, prediction);
611 glm::vec3 Steering::Evade(const EntityState &state, const Entity &other) const noexcept {
612 const glm::vec3 diff(state.Diff(other.GetState()));
614 return TargetVelocity(state, -other.Velocity());
616 const float time_estimate = glm::length(diff) / speed;
617 ExactLocation prediction(other.ChunkCoords(), other.Position() + (other.Velocity() * time_estimate));
618 return Flee(state, prediction);
622 glm::vec3 Steering::Wander(const EntityState &state) const noexcept {
623 return TargetVelocity(state, glm::normalize(entity.Heading() * wander_dist + wander_pos) * speed);
626 glm::vec3 Steering::ObstacleAvoidance(const EntityState &) const noexcept {
631 World::World(const BlockTypeRegistry &types, const Config &config)
638 #ifdef BLANK_PROFILING
644 , light_direction(config.light_direction)
645 , fog_density(config.fog_density) {
646 for (int i = 0; i < 4; ++i) {
652 for (Entity &e : entities) {
655 std::size_t removed = 0;
658 for (auto e = entities.begin(), end = entities.end(); e != end; ++e) {
659 if (e->CanRemove()) {
661 end = entities.end();
665 } while (removed > 0 && !entities.empty());
669 Player *World::AddPlayer(const std::string &name) {
670 for (Player &p : players) {
671 if (p.Name() == name) {
675 Entity &entity = AddEntity();
677 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
678 entity.WorldCollidable(true);
679 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
680 players.emplace_back(entity, index);
681 return &players.back();
684 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
685 for (Player &p : players) {
686 if (p.Name() == name) {
690 Entity *entity = AddEntity(id);
695 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
696 entity->WorldCollidable(true);
697 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
698 players.emplace_back(*entity, index);
699 return &players.back();
702 Entity &World::AddEntity() {
703 if (entities.empty()) {
704 entities.emplace_back();
705 entities.back().ID(1);
706 return entities.back();
708 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
709 std::uint32_t id = entities.back().ID() + 1;
710 entities.emplace_back();
711 entities.back().ID(id);
712 return entities.back();
714 std::uint32_t id = 1;
715 auto position = entities.begin();
716 auto end = entities.end();
717 while (position != end && position->ID() == id) {
721 auto entity = entities.emplace(position);
726 Entity *World::AddEntity(std::uint32_t id) {
727 if (entities.empty() || entities.back().ID() < id) {
728 entities.emplace_back();
729 entities.back().ID(id);
730 return &entities.back();
733 auto position = entities.begin();
734 auto end = entities.end();
735 while (position != end && position->ID() < id) {
738 if (position != end && position->ID() == id) {
741 auto entity = entities.emplace(position);
746 Entity &World::ForceAddEntity(std::uint32_t id) {
747 if (entities.empty() || entities.back().ID() < id) {
748 entities.emplace_back();
749 entities.back().ID(id);
750 return entities.back();
753 auto position = entities.begin();
754 auto end = entities.end();
755 while (position != end && position->ID() < id) {
758 if (position != end && position->ID() == id) {
761 auto entity = entities.emplace(position);
767 Player *World::FindPlayer(const std::string &name) {
768 for (Player &p : players) {
769 if (p.Name() == name) {
776 Entity *World::FindEntity(const std::string &name) {
777 // TODO: this may get inefficient
778 for (Entity &e : entities) {
779 if (e.Name() == name) {
794 bool CandidateLess(const Candidate &a, const Candidate &b) {
795 return a.dist < b.dist;
798 std::vector<Candidate> candidates;
802 bool World::Intersection(
804 const ExactLocation::Coarse &reference,
807 // only consider chunks of the index closest to reference
808 // this makes the ray not be infinite anymore (which means it's
809 // actually a line segment), but oh well
810 ChunkIndex *index = chunks.ClosestIndex(reference);
817 // maybe worht to try:
818 // change this so the test starts at the chunk of the ray's
819 // origin and "walks" forward until it hits (actually casting
820 // the ray, so to say). if this performs well (at least, better
821 // than now), this could also qualify for the chunk test itself
822 // see Bresenham's line algo or something similar
824 ExactLocation ray_loc(reference, ray.orig);
827 ExactLocation::Coarse begin(index->CoordsBegin());
828 ExactLocation::Coarse end(index->CoordsEnd());
830 // ignore chunks that are bind the ray's origin
831 for (int i = 0; i < 3; ++i) {
832 if (ray.dir[i] >= 0.0f) {
833 begin[i] = ray_loc.chunk[i];
835 if (ray.dir[i] <= 0.0f) {
836 end[i] = ray_loc.chunk[i] + 1;
840 for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
841 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
842 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
843 Chunk *cur_chunk = index->Get(pos);
845 if (cur_chunk && cur_chunk->Intersection(ray, reference, cur_dist)) {
846 candidates.push_back({ cur_chunk, cur_dist });
852 if (candidates.empty()) return false;
854 std::sort(candidates.begin(), candidates.end(), CandidateLess);
856 coll.chunk = nullptr;
858 coll.depth = std::numeric_limits<float>::infinity();
860 for (Candidate &cand : candidates) {
861 if (cand.dist > coll.depth) continue;
862 WorldCollision cur_coll;
863 if (cand.chunk->Intersection(ray, reference, cur_coll)) {
864 if (cur_coll.depth < coll.depth) {
873 bool World::Intersection(
875 const Entity &reference,
876 EntityCollision &coll
878 coll = EntityCollision(nullptr, std::numeric_limits<float>::infinity(), glm::vec3(0.0f));
879 for (Entity &cur_entity : entities) {
880 if (&cur_entity == &reference) {
884 glm::vec3 cur_normal;
885 if (blank::Intersection(ray, cur_entity.Bounds(), cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
886 // TODO: fine grained check goes here? maybe?
887 if (cur_dist < coll.depth) {
888 coll = EntityCollision(&cur_entity, cur_dist, cur_normal);
896 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
897 glm::ivec3 reference = s.pos.chunk;
898 glm::mat4 M = s.Transform(reference);
900 ExactLocation::Coarse begin(reference - 1);
901 ExactLocation::Coarse end(reference + 2);
904 for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
905 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
906 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
907 Chunk *chunk = chunks.Get(pos);
908 if (chunk && chunk->Intersection(e, M, chunk->Transform(reference), col)) {
917 bool World::Intersection(
920 const glm::ivec3 &reference,
921 std::vector<WorldCollision> &col
923 // this only works if box's diameter is < than 16
924 ExactLocation::Coarse begin(reference - 1);
925 ExactLocation::Coarse end(reference + 2);
928 for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
929 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
930 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
931 Chunk *chunk = chunks.Get(pos);
932 if (chunk && chunk->Intersection(box, M, chunk->Transform(reference), col)) {
941 void World::Update(int dt) {
942 float fdt(dt * 0.001f);
943 for (Entity &entity : entities) {
944 entity.Update(*this, fdt);
946 for (Player &player : players) {
949 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
950 if (iter->CanRemove()) {
951 iter = RemoveEntity(iter);
958 void World::ResolveWorldCollision(
959 const Entity &entity,
963 if (!entity.WorldCollidable() || !Intersection(entity, state, col)) {
964 // no collision, no fix
967 glm::vec3 correction = CombinedInterpenetration(state, col);
968 // correction may be zero in which case normalize() returns NaNs
969 if (iszero(correction)) {
972 // if entity is already going in the direction of correction,
973 // let the problem resolve itself
974 if (glm::dot(state.velocity, correction) >= 0.0f) {
977 // apply correction, maybe could use some damping, gotta test
978 state.pos.block += correction;
980 glm::vec3 normal_velocity(glm::proj(state.velocity, correction));
981 state.velocity -= normal_velocity;
984 glm::vec3 World::CombinedInterpenetration(
985 const EntityState &state,
986 const std::vector<WorldCollision> &col
988 // determine displacement for each cardinal axis and move entity accordingly
989 glm::vec3 min_pen(0.0f);
990 glm::vec3 max_pen(0.0f);
991 for (const WorldCollision &c : col) {
992 if (!c.Blocks()) continue;
993 glm::vec3 normal(c.normal);
994 // swap if neccessary (normal may point away from the entity)
995 if (glm::dot(normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) < 0) {
998 // check if block surface is "inside"
999 Block::Face coll_face = Block::NormalFace(normal);
1000 BlockLookup neighbor(c.chunk, c.BlockPos(), coll_face);
1001 if (neighbor && neighbor.FaceFilled(Block::Opposite(coll_face))) {
1002 // yep, so ignore this contact
1005 glm::vec3 local_pen(normal * c.depth);
1006 min_pen = glm::min(min_pen, local_pen);
1007 max_pen = glm::max(max_pen, local_pen);
1009 glm::vec3 pen(0.0f);
1010 // only apply correction for axes where penetration is only in one direction
1011 for (std::size_t i = 0; i < 3; ++i) {
1012 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
1013 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
1014 pen[i] = min_pen[i];
1017 pen[i] = max_pen[i];
1023 glm::vec3 World::GravityAt(const ExactLocation &loc) const noexcept {
1024 glm::vec3 force(0.0f);
1025 ExactLocation::Coarse begin(loc.chunk - 1);
1026 ExactLocation::Coarse end(loc.chunk + 2);
1028 for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
1029 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
1030 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
1031 const Chunk *chunk = chunks.Get(pos);
1033 force += chunk->GravityAt(loc);
1042 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
1044 for (auto player = players.begin(), end = players.end(); player != end;) {
1045 if (&player->GetEntity() == &*eh) {
1046 chunks.UnregisterIndex(player->GetChunks());
1047 player = players.erase(player);
1048 end = players.end();
1053 return entities.erase(eh);
1057 void World::Render(Viewport &viewport) {
1058 DirectionalLighting &entity_prog = viewport.EntityProgram();
1059 entity_prog.SetFogDensity(fog_density);
1061 glm::vec3 light_dir;
1062 glm::vec3 light_col;
1063 glm::vec3 ambient_col;
1064 for (Entity &entity : entities) {
1065 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
1066 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
1067 GetLight(entity, light_dir, light_col, ambient_col);
1068 entity_prog.SetLightDirection(light_dir);
1069 entity_prog.SetLightColor(light_col);
1070 entity_prog.SetAmbientColor(ambient_col);
1071 entity.Render(M, entity_prog);
1076 // this should interpolate based on the fractional part of entity's block position
1077 void World::GetLight(
1083 BlockLookup center(chunks.Get(e.ChunkCoords()), RoughLocation::Fine(e.Position()));
1085 // chunk unavailable, so make it really dark and from
1086 // some arbitrary direction
1087 dir = glm::vec3(1.0f, 2.0f, 3.0f);
1088 col = glm::vec3(0.025f); // ~0.8^15
1091 glm::ivec3 base(center.GetBlockPos());
1092 int base_light = center.GetLight();
1095 glm::ivec3 acc(0, 0, 0);
1096 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
1097 for (offset.y = -1; offset.y < 2; ++offset.y) {
1098 for (offset.x = -1; offset.x < 2; ++offset.x) {
1099 BlockLookup block(¢er.GetChunk(), center.GetBlockPos() + offset);
1101 // missing, just ignore it
1104 // otherwise, accumulate the difference times direction
1105 acc += offset * (base_light - block.GetLight());
1106 max_light = std::max(max_light, block.GetLight());
1107 min_light = std::min(min_light, block.GetLight());
1112 col = glm::vec3(std::pow(0.8f, 15 - max_light));
1113 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
1118 PrimitiveMesh::Buffer debug_buf;
1122 void World::RenderDebug(Viewport &viewport) {
1123 PrimitiveMesh debug_mesh;
1124 PlainColor &prog = viewport.WorldColorProgram();
1125 for (const Entity &entity : entities) {
1126 debug_buf.OutlineBox(entity.Bounds(), PrimitiveMesh::Color(255, 0, 0, 255));
1127 debug_mesh.Update(debug_buf);
1128 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
1129 debug_mesh.DrawLines();