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 , heading(0.0f, 0.0f, -1.0f)
53 , world_collision(false)
55 , owns_controller(false) {
59 Entity::~Entity() noexcept {
63 Entity::Entity(const Entity &other) noexcept
69 , bounds(other.bounds)
71 , model_transform(1.0f)
72 , view_transform(1.0f)
74 , heading(0.0f, 0.0f, -1.0f)
75 , max_vel(other.max_vel)
76 , max_force(other.max_force)
78 , world_collision(other.world_collision)
80 , owns_controller(false) {
84 void Entity::SetController(EntityController *c) noexcept {
87 owns_controller = true;
90 void Entity::SetController(EntityController &c) noexcept {
93 owns_controller = false;
96 void Entity::UnsetController() noexcept {
97 if (ctrl && owns_controller) {
103 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
104 return steering.Force(s);
107 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
112 void Entity::Position(const glm::vec3 &pos) noexcept {
113 state.pos.block = pos;
114 state.AdjustPosition();
117 void Entity::TurnHead(float dp, float dy) noexcept {
118 SetHead(state.pitch + dp, state.yaw + dy);
121 void Entity::SetHead(float p, float y) noexcept {
126 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
127 return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
130 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
131 return Transform(reference) * view_transform;
134 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
135 glm::mat4 transform = ViewTransform(chunk_offset);
136 return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
139 void Entity::Update(World &world, float dt) {
140 if (HasController()) {
141 GetController().Update(*this, dt);
143 steering.Update(world, dt);
144 UpdatePhysics(world, dt);
150 void Entity::UpdatePhysics(World &world, float dt) {
151 EntityState s(state);
153 EntityDerivative a(CalculateStep(world, s, 0.0f, EntityDerivative()));
154 EntityDerivative b(CalculateStep(world, s, dt * 0.5f, a));
155 EntityDerivative c(CalculateStep(world, s, dt * 0.5f, b));
156 EntityDerivative d(CalculateStep(world, s, dt, c));
159 constexpr float sixth = 1.0f / 6.0f;
160 f.position = sixth * (a.position + 2.0f * (b.position + c.position) + d.position);
161 f.velocity = sixth * (a.velocity + 2.0f * (b.velocity + c.velocity) + d.velocity);
163 s.pos.block += f.position * dt;
164 s.velocity += f.velocity * dt;
165 limit(s.velocity, max_vel);
166 world.ResolveWorldCollision(*this, s);
172 EntityDerivative Entity::CalculateStep(
174 const EntityState &cur,
176 const EntityDerivative &delta
178 EntityState next(cur);
179 next.pos.block += delta.position * dt;
180 next.velocity += delta.velocity * dt;
181 limit(next.velocity, max_vel);
182 next.AdjustPosition();
184 EntityDerivative out;
185 out.position = next.velocity;
186 out.velocity = ControlForce(next) + world.GravityAt(next.pos); // by mass = 1kg
191 void Entity::UpdateTransforms() noexcept {
192 // model transform is the one given by current state
193 model_transform = state.Transform(state.pos.chunk);
194 // view transform is either the model's eyes transform or,
195 // should the entity have no model, the pitch (yaw already is
196 // in model transform)
198 view_transform = model.EyesTransform();
200 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
204 void Entity::UpdateHeading() noexcept {
205 speed = length(Velocity());
206 if (speed > std::numeric_limits<float>::epsilon()) {
207 heading = Velocity() / speed;
210 // use -Z (forward axis) of model transform (our "chest")
211 heading = -glm::vec3(model_transform[2]);
215 void Entity::UpdateModel(float dt) noexcept {
216 // first, sanitize the pitch and yaw fields of state (our input)
217 // those indicate the head orientation in the entity's local cosystem
218 state.AdjustHeading();
219 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
224 void Entity::OrientBody(float dt) noexcept {
225 // maximum body rotation per second (due to velocity orientation) (90°)
226 constexpr float max_body_turn_per_second = PI_0p5;
227 const float max_body_turn = max_body_turn_per_second * dt;
228 // minimum speed to apply body correction
229 constexpr float min_speed = 0.0625f;
231 const glm::vec3 up(model_transform[1]);
232 if (speed > min_speed) {
233 // check if our orientation and velocity are aligned
234 const glm::vec3 forward(-model_transform[2]);
235 // facing is local -Z rotated about local Y by yaw and transformed into world space
236 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))));
237 // only adjust if velocity isn't almost parallel to up
238 float vel_dot_up = dot(Velocity(), up);
239 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
240 // get direction of velocity projected onto model plane
241 glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
242 // if velocity points away from our facing (with a little bias), flip it around
243 // (the entity is "walking backwards")
244 if (dot(facing, direction) < -0.1f) {
245 direction = -direction;
247 // calculate the difference between forward and direction
248 const float absolute_difference = std::acos(dot(forward, direction));
249 // if direction is clockwise with respect to up vector, invert the angle
250 const float relative_difference = dot(cross(forward, direction), up) < 0.0f
251 ? -absolute_difference
252 : absolute_difference;
253 // only correct by half the difference max
254 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
256 std::cout << "orientation before: " << state.orient << std::endl;
257 std::cout << "up: " << up << std::endl;
258 std::cout << "forward: " << forward << std::endl;
259 std::cout << "facing: " << facing << std::endl;
260 std::cout << "direction: " << direction << std::endl;
261 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
262 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
263 std::cout << std::endl;
265 // now rotate body by correction and head by -correction
266 state.orient = rotate(state.orient, correction, up);
267 state.yaw -= correction;
272 void Entity::OrientHead(float dt) noexcept {
273 // maximum yaw of head (60°)
274 constexpr float max_head_yaw = PI / 3.0f;
276 const glm::vec3 up(model_transform[1]);
277 // if yaw is bigger than max, rotate the body to accomodate
278 if (std::abs(state.yaw) > max_head_yaw) {
279 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
280 // rotate the entity by deviation about local Y
281 state.orient = rotate(state.orient, deviation, up);
282 // and remove from head yaw
283 state.yaw -= deviation;
284 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
285 state.AdjustHeading();
287 // update model if any
289 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
294 EntityCollision::EntityCollision(Entity *e, float d, const glm::vec3 &n)
303 EntityCollision::~EntityCollision() {
309 EntityCollision::EntityCollision(const EntityCollision &other)
311 , normal(other.normal)
312 , entity(other.entity) {
318 EntityCollision &EntityCollision::operator =(const EntityCollision &other) {
323 normal = other.normal;
324 entity = other.entity;
332 EntityController::~EntityController() {
337 EntityState::EntityState()
340 , orient(1.0f, 0.0f, 0.0f, 0.0f)
346 void EntityState::AdjustPosition() noexcept {
350 void EntityState::AdjustHeading() noexcept {
351 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
360 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
361 const glm::vec3 translation = RelativePosition(reference);
362 glm::mat4 transform(toMat4(orient));
363 transform[3] = glm::vec4(translation, 1.0f);
368 Player::Player(Entity &e, ChunkIndex &c)
379 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
380 if (!spawn_block || spawn_block.GetType().collide_block) {
384 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
385 if (!head_block || head_block.GetType().collide_block) {
392 void Player::Update(int dt) {
393 chunks.Rebase(entity.ChunkCoords());
397 Steering::Steering(const Entity &e)
399 , target_entity(nullptr)
400 , target_velocity(0.0f)
402 , speed(entity.MaxVelocity())
403 , wander_radius(1.0f)
406 , wander_pos(1.0f, 0.0f, 0.0f)
412 Steering::~Steering() {
416 Steering &Steering::SetTargetEntity(Entity &e) noexcept {
423 Steering &Steering::ClearTargetEntity() noexcept {
425 target_entity->UnRef();
426 target_entity = nullptr;
431 void Steering::Update(World &world, float dt) {
432 if (AnyEnabled(WANDER)) {
433 UpdateWander(world, dt);
435 if (AnyEnabled(OBSTACLE_AVOIDANCE)) {
436 UpdateObstacle(world);
440 void Steering::UpdateWander(World &world, float dt) {
441 glm::vec3 displacement(
442 world.Random().SNorm() * wander_disp,
443 world.Random().SNorm() * wander_disp,
444 world.Random().SNorm() * wander_disp
446 if (!iszero(displacement)) {
447 wander_pos = normalize(wander_pos + displacement * dt) * wander_radius;
451 void Steering::UpdateObstacle(World &world) {
452 if (!entity.Moving()) {
453 obstacle_dir = glm::vec3(0.0f);
456 AABB box(entity.Bounds());
457 box.min.z = -entity.Speed();
459 glm::mat4 transform(find_rotation(glm::vec3(0.0f, 0.0f, -1.0f), entity.Heading()));
460 transform[3] = glm::vec4(entity.Position(), 1.0f);
461 // check if that box intersects with any blocks
463 if (!world.Intersection(box, transform, entity.ChunkCoords(), col)) {
464 obstacle_dir = glm::vec3(0.0f);
467 // if so, pick the nearest collision
468 const WorldCollision *nearest = nullptr;
469 glm::vec3 difference(0.0f);
470 float distance = std::numeric_limits<float>::infinity();
471 for (const WorldCollision &c : col) {
472 // diff points from block to state
473 glm::vec3 diff = entity.GetState().RelativePosition(c.ChunkPos()) - c.BlockCoords();
474 float dist = length2(diff);
475 if (dist < distance) {
482 // intersection test lied to us
483 obstacle_dir = glm::vec3(0.0f);
486 // and try to avoid it
487 float to_go = dot(difference, entity.Heading());
488 glm::vec3 point(entity.Position() + entity.Heading() * to_go);
489 obstacle_dir = normalize(point - nearest->BlockCoords()) * (entity.Speed() / std::sqrt(distance));
492 glm::vec3 Steering::Force(const EntityState &state) const noexcept {
493 glm::vec3 force(0.0f);
497 const float max = entity.MaxControlForce();
498 if (AnyEnabled(HALT)) {
499 if (SumForce(force, Halt(state), max)) {
503 if (AnyEnabled(TARGET_VELOCITY)) {
504 if (SumForce(force, TargetVelocity(state, target_velocity), max)) {
508 if (AnyEnabled(OBSTACLE_AVOIDANCE)) {
509 if (SumForce(force, ObstacleAvoidance(state), max)) {
513 if (AnyEnabled(EVADE_TARGET)) {
514 if (HasTargetEntity()) {
515 if (SumForce(force, Evade(state, GetTargetEntity()), max)) {
519 std::cout << "Steering: evade enabled, but target entity not set" << std::endl;
522 if (AnyEnabled(PURSUE_TARGET)) {
523 if (HasTargetEntity()) {
524 if (SumForce(force, Pursuit(state, GetTargetEntity()), max)) {
528 std::cout << "Steering: pursuit enabled, but target entity not set" << std::endl;
531 if (AnyEnabled(WANDER)) {
532 if (SumForce(force, Wander(state), max)) {
539 bool Steering::SumForce(glm::vec3 &out, const glm::vec3 &in, float max) noexcept {
540 if (iszero(in) || any(isnan(in))) {
543 float current = iszero(out) ? 0.0f : length(out);
544 float remain = max - current;
545 if (remain <= 0.0f) {
548 float additional = length(in);
549 if (additional > remain) {
550 out += normalize(in) * remain;
558 glm::vec3 Steering::Halt(const EntityState &state) const noexcept {
559 return state.velocity * -accel;
562 glm::vec3 Steering::TargetVelocity(const EntityState &state, const glm::vec3 &vel) const noexcept {
563 return (vel - state.velocity) * accel;
566 glm::vec3 Steering::Seek(const EntityState &state, const ExactLocation &loc) const noexcept {
567 const glm::vec3 diff(loc.Difference(state.pos).Absolute());
569 return glm::vec3(0.0f);
571 return TargetVelocity(state, normalize(diff) * speed);
575 glm::vec3 Steering::Flee(const EntityState &state, const ExactLocation &loc) const noexcept {
576 const glm::vec3 diff(state.pos.Difference(loc).Absolute());
578 return glm::vec3(0.0f);
580 return TargetVelocity(state, normalize(diff) * speed);
584 glm::vec3 Steering::Arrive(const EntityState &state, const ExactLocation &loc) const noexcept {
585 const glm::vec3 diff(loc.Difference(state.pos).Absolute());
586 const float dist = length(diff);
587 if (dist < std::numeric_limits<float>::epsilon()) {
588 return glm::vec3(0.0f);
590 const float att_speed = std::min(dist * accel, speed);
591 return TargetVelocity(state, diff * att_speed / dist);
595 glm::vec3 Steering::Pursuit(const EntityState &state, const Entity &other) const noexcept {
596 const glm::vec3 diff(state.Diff(other.GetState()));
598 return TargetVelocity(state, other.Velocity());
600 const float time_estimate = length(diff) / speed;
601 ExactLocation prediction(other.ChunkCoords(), other.Position() + (other.Velocity() * time_estimate));
602 return Seek(state, prediction);
606 glm::vec3 Steering::Evade(const EntityState &state, const Entity &other) const noexcept {
607 const glm::vec3 diff(state.Diff(other.GetState()));
609 return TargetVelocity(state, -other.Velocity());
611 const float time_estimate = length(diff) / speed;
612 ExactLocation prediction(other.ChunkCoords(), other.Position() + (other.Velocity() * time_estimate));
613 return Flee(state, prediction);
617 glm::vec3 Steering::Wander(const EntityState &state) const noexcept {
618 return TargetVelocity(state, normalize(entity.Heading() * wander_dist + wander_pos) * speed);
621 glm::vec3 Steering::ObstacleAvoidance(const EntityState &state) const noexcept {
626 World::World(const BlockTypeRegistry &types, const Config &config)
633 #ifdef BLANK_PROFILING
639 , light_direction(config.light_direction)
640 , fog_density(config.fog_density) {
641 for (int i = 0; i < 4; ++i) {
647 for (Entity &e : entities) {
650 std::size_t removed = 0;
653 for (auto e = entities.begin(), end = entities.end(); e != end; ++e) {
654 if (e->CanRemove()) {
656 end = entities.end();
660 } while (removed > 0 && !entities.empty());
664 Player *World::AddPlayer(const std::string &name) {
665 for (Player &p : players) {
666 if (p.Name() == name) {
670 Entity &entity = AddEntity();
672 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
673 entity.WorldCollidable(true);
674 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
675 players.emplace_back(entity, index);
676 return &players.back();
679 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
680 for (Player &p : players) {
681 if (p.Name() == name) {
685 Entity *entity = AddEntity(id);
690 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
691 entity->WorldCollidable(true);
692 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
693 players.emplace_back(*entity, index);
694 return &players.back();
697 Entity &World::AddEntity() {
698 if (entities.empty()) {
699 entities.emplace_back();
700 entities.back().ID(1);
701 return entities.back();
703 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
704 std::uint32_t id = entities.back().ID() + 1;
705 entities.emplace_back();
706 entities.back().ID(id);
707 return entities.back();
709 std::uint32_t id = 1;
710 auto position = entities.begin();
711 auto end = entities.end();
712 while (position != end && position->ID() == id) {
716 auto entity = entities.emplace(position);
721 Entity *World::AddEntity(std::uint32_t id) {
722 if (entities.empty() || entities.back().ID() < id) {
723 entities.emplace_back();
724 entities.back().ID(id);
725 return &entities.back();
728 auto position = entities.begin();
729 auto end = entities.end();
730 while (position != end && position->ID() < id) {
733 if (position != end && position->ID() == id) {
736 auto entity = entities.emplace(position);
741 Entity &World::ForceAddEntity(std::uint32_t id) {
742 if (entities.empty() || entities.back().ID() < id) {
743 entities.emplace_back();
744 entities.back().ID(id);
745 return entities.back();
748 auto position = entities.begin();
749 auto end = entities.end();
750 while (position != end && position->ID() < id) {
753 if (position != end && position->ID() == id) {
756 auto entity = entities.emplace(position);
769 bool CandidateLess(const Candidate &a, const Candidate &b) {
770 return a.dist < b.dist;
773 std::vector<Candidate> candidates;
777 bool World::Intersection(
779 const ExactLocation::Coarse &reference,
784 for (Chunk &cur_chunk : chunks) {
786 if (cur_chunk.Intersection(ray, reference, cur_dist)) {
787 candidates.push_back({ &cur_chunk, cur_dist });
791 if (candidates.empty()) return false;
793 std::sort(candidates.begin(), candidates.end(), CandidateLess);
795 coll.chunk = nullptr;
797 coll.depth = std::numeric_limits<float>::infinity();
799 for (Candidate &cand : candidates) {
800 if (cand.dist > coll.depth) continue;
801 WorldCollision cur_coll;
802 if (cand.chunk->Intersection(ray, reference, cur_coll)) {
803 if (cur_coll.depth < coll.depth) {
812 bool World::Intersection(
814 const Entity &reference,
815 EntityCollision &coll
817 coll = EntityCollision(nullptr, std::numeric_limits<float>::infinity(), glm::vec3(0.0f));
818 for (Entity &cur_entity : entities) {
819 if (&cur_entity == &reference) {
823 glm::vec3 cur_normal;
824 if (blank::Intersection(ray, cur_entity.Bounds(), cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
825 // TODO: fine grained check goes here? maybe?
826 if (cur_dist < coll.depth) {
827 coll = EntityCollision(&cur_entity, cur_dist, cur_normal);
835 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
836 glm::ivec3 reference = s.pos.chunk;
837 glm::mat4 M = s.Transform(reference);
839 ExactLocation::Coarse begin(reference - 1);
840 ExactLocation::Coarse end(reference + 2);
843 for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
844 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
845 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
846 Chunk *chunk = chunks.Get(pos);
847 if (chunk && chunk->Intersection(e, M, chunk->Transform(reference), col)) {
856 bool World::Intersection(
859 const glm::ivec3 &reference,
860 std::vector<WorldCollision> &col
863 for (Chunk &cur_chunk : chunks) {
864 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
865 // chunk is not one of the 3x3x3 surrounding the entity
866 // since there's no entity which can extent over 16 blocks, they can be skipped
867 // TODO: change to indexed (like with entity)
870 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
877 void World::Update(int dt) {
878 float fdt(dt * 0.001f);
879 for (Entity &entity : entities) {
880 entity.Update(*this, fdt);
882 for (Player &player : players) {
885 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
886 if (iter->CanRemove()) {
887 iter = RemoveEntity(iter);
894 void World::ResolveWorldCollision(
895 const Entity &entity,
899 if (!entity.WorldCollidable() || !Intersection(entity, state, col)) {
900 // no collision, no fix
903 glm::vec3 correction = CombinedInterpenetration(state, col);
904 // correction may be zero in which case normalize() returns NaNs
905 if (iszero(correction)) {
908 // if entity is already going in the direction of correction,
909 // let the problem resolve itself
910 if (dot(state.velocity, correction) >= 0.0f) {
913 // apply correction, maybe could use some damping, gotta test
914 state.pos.block += correction;
916 glm::vec3 normal_velocity(proj(state.velocity, correction));
917 state.velocity -= normal_velocity;
920 glm::vec3 World::CombinedInterpenetration(
921 const EntityState &state,
922 const std::vector<WorldCollision> &col
924 // determine displacement for each cardinal axis and move entity accordingly
925 glm::vec3 min_pen(0.0f);
926 glm::vec3 max_pen(0.0f);
927 for (const WorldCollision &c : col) {
928 if (!c.Blocks()) continue;
929 glm::vec3 normal(c.normal);
930 // swap if neccessary (normal may point away from the entity)
931 if (dot(normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) < 0) {
934 // check if block surface is "inside"
935 Block::Face coll_face = Block::NormalFace(normal);
936 BlockLookup neighbor(c.chunk, c.BlockPos(), coll_face);
937 if (neighbor && neighbor.FaceFilled(Block::Opposite(coll_face))) {
938 // yep, so ignore this contact
941 glm::vec3 local_pen(normal * c.depth);
942 min_pen = min(min_pen, local_pen);
943 max_pen = max(max_pen, local_pen);
946 // only apply correction for axes where penetration is only in one direction
947 for (std::size_t i = 0; i < 3; ++i) {
948 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
949 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
959 glm::vec3 World::GravityAt(const ExactLocation &loc) const noexcept {
960 glm::vec3 force(0.0f);
961 ExactLocation::Coarse begin(loc.chunk - 1);
962 ExactLocation::Coarse end(loc.chunk + 2);
964 for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
965 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
966 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
967 const Chunk *chunk = chunks.Get(pos);
969 force += chunk->GravityAt(loc);
978 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
980 for (auto player = players.begin(), end = players.end(); player != end;) {
981 if (&player->GetEntity() == &*eh) {
982 chunks.UnregisterIndex(player->GetChunks());
983 player = players.erase(player);
989 return entities.erase(eh);
993 void World::Render(Viewport &viewport) {
994 DirectionalLighting &entity_prog = viewport.EntityProgram();
995 entity_prog.SetFogDensity(fog_density);
999 glm::vec3 ambient_col;
1000 for (Entity &entity : entities) {
1001 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
1002 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
1003 GetLight(entity, light_dir, light_col, ambient_col);
1004 entity_prog.SetLightDirection(light_dir);
1005 entity_prog.SetLightColor(light_col);
1006 entity_prog.SetAmbientColor(ambient_col);
1007 entity.Render(M, entity_prog);
1012 // this should interpolate based on the fractional part of entity's block position
1013 void World::GetLight(
1019 BlockLookup center(chunks.Get(e.ChunkCoords()), e.Position());
1021 // chunk unavailable, so make it really dark and from
1022 // some arbitrary direction
1023 dir = glm::vec3(1.0f, 2.0f, 3.0f);
1024 col = glm::vec3(0.025f); // ~0.8^15
1027 glm::ivec3 base(center.GetBlockPos());
1028 int base_light = center.GetLight();
1031 glm::ivec3 acc(0, 0, 0);
1032 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
1033 for (offset.y = -1; offset.y < 2; ++offset.y) {
1034 for (offset.x = -1; offset.x < 2; ++offset.x) {
1035 BlockLookup block(¢er.GetChunk(), center.GetBlockPos() + offset);
1037 // missing, just ignore it
1040 // otherwise, accumulate the difference times direction
1041 acc += offset * (base_light - block.GetLight());
1042 max_light = std::max(max_light, block.GetLight());
1043 min_light = std::min(min_light, block.GetLight());
1048 col = glm::vec3(std::pow(0.8f, 15 - max_light));
1049 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
1054 PrimitiveMesh::Buffer debug_buf;
1058 void World::RenderDebug(Viewport &viewport) {
1059 PrimitiveMesh debug_mesh;
1060 PlainColor &prog = viewport.WorldColorProgram();
1061 for (const Entity &entity : entities) {
1062 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
1063 debug_mesh.Update(debug_buf);
1064 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
1065 debug_mesh.DrawLines();