]> git.localhorst.tv Git - blank.git/blob - src/world/world.cpp
direct fix collision response
[blank.git] / src / world / world.cpp
1 #include "Entity.hpp"
2 #include "EntityController.hpp"
3 #include "EntityDerivative.hpp"
4 #include "EntityState.hpp"
5 #include "Player.hpp"
6 #include "World.hpp"
7
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"
16
17 #include <algorithm>
18 #include <cmath>
19 #include <iostream>
20 #include <limits>
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>
27
28
29 namespace blank {
30
31 Entity::Entity() noexcept
32 : ctrl(nullptr)
33 , model()
34 , id(-1)
35 , name("anonymous")
36 , bounds()
37 , radius(0.0f)
38 , state()
39 , heading(0.0f, 0.0f, -1.0f)
40 , max_vel(5.0f)
41 , max_force(25.0f)
42 , ref_count(0)
43 , world_collision(false)
44 , dead(false)
45 , owns_controller(false) {
46
47 }
48
49 Entity::~Entity() noexcept {
50         UnsetController();
51 }
52
53 Entity::Entity(const Entity &other) noexcept
54 : ctrl(other.ctrl)
55 , model(other.model)
56 , id(-1)
57 , name(other.name)
58 , bounds(other.bounds)
59 , state(other.state)
60 , model_transform(1.0f)
61 , view_transform(1.0f)
62 , speed(0.0f)
63 , heading(0.0f, 0.0f, -1.0f)
64 , max_vel(other.max_vel)
65 , max_force(other.max_force)
66 , ref_count(0)
67 , world_collision(other.world_collision)
68 , dead(other.dead)
69 , owns_controller(false) {
70
71 }
72
73 void Entity::SetController(EntityController *c) noexcept {
74         UnsetController();
75         ctrl = c;
76         owns_controller = true;
77 }
78
79 void Entity::SetController(EntityController &c) noexcept {
80         UnsetController();
81         ctrl = &c;
82         owns_controller = false;
83 }
84
85 void Entity::UnsetController() noexcept {
86         if (ctrl && owns_controller) {
87                 delete ctrl;
88         }
89         ctrl = nullptr;
90 }
91
92 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
93         if (HasController()) {
94                 return GetController().ControlForce(*this, s);
95         } else {
96                 return -s.velocity;
97         }
98 }
99
100 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
101         state.pos.chunk = c;
102         state.pos.block = b;
103 }
104
105 void Entity::Position(const glm::vec3 &pos) noexcept {
106         state.pos.block = pos;
107         state.AdjustPosition();
108 }
109
110 void Entity::TurnHead(float dp, float dy) noexcept {
111         SetHead(state.pitch + dp, state.yaw + dy);
112 }
113
114 void Entity::SetHead(float p, float y) noexcept {
115         state.pitch = p;
116         state.yaw = y;
117 }
118
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;
121 }
122
123 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
124         return Transform(reference) * view_transform;
125 }
126
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]) };
130 }
131
132 void Entity::Update(float dt) {
133         UpdateTransforms();
134         UpdateHeading();
135         if (HasController()) {
136                 GetController().Update(*this, dt);
137         }
138         UpdateModel(dt);
139 }
140
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)
147         if (model) {
148                 view_transform = model.EyesTransform();
149         } else {
150                 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
151         }
152 }
153
154 void Entity::UpdateHeading() noexcept {
155         speed = length(Velocity());
156         if (speed > std::numeric_limits<float>::epsilon()) {
157                 heading = Velocity() / speed;
158         } else {
159                 speed = 0.0f;
160                 // use -Z (forward axis) of model transform (our "chest")
161                 heading = -glm::vec3(model_transform[2]);
162         }
163 }
164
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
170         //OrientBody(dt);
171         OrientHead(dt);
172 }
173
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;
180         // use local Y as up
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;
196                         }
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);
205                         if (ID() == 1) {
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;
214                         }
215                         // now rotate body by correction and head by -correction
216                         state.orient = rotate(state.orient, correction, up);
217                         state.yaw -= correction;
218                 }
219         }
220 }
221
222 void Entity::OrientHead(float dt) noexcept {
223         // maximum yaw of head (60°)
224         constexpr float max_head_yaw = PI / 3.0f;
225         // use local Y as up
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();
236         }
237         // update model if any
238         if (model) {
239                 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
240         }
241 }
242
243
244 EntityController::~EntityController() {
245
246 }
247
248 bool EntityController::MaxOutForce(
249         glm::vec3 &out,
250         const glm::vec3 &add,
251         float max
252 ) noexcept {
253         if (iszero(add) || any(isnan(add))) {
254                 return false;
255         }
256         float current = iszero(out) ? 0.0f : length(out);
257         float remain = max - current;
258         if (remain <= 0.0f) {
259                 return true;
260         }
261         float additional = length(add);
262         if (additional > remain) {
263                 out += normalize(add) * remain;
264                 return true;
265         } else {
266                 out += add;
267                 return false;
268         }
269 }
270
271
272 EntityState::EntityState()
273 : pos()
274 , velocity(0.0f)
275 , orient(1.0f, 0.0f, 0.0f, 0.0f)
276 , pitch(0.0f)
277 , yaw(0.0f) {
278
279 }
280
281 void EntityState::AdjustPosition() noexcept {
282         pos.Correct();
283 }
284
285 void EntityState::AdjustHeading() noexcept {
286         pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
287         while (yaw > PI) {
288                 yaw -= PI_2p0;
289         }
290         while (yaw < -PI) {
291                 yaw += PI_2p0;
292         }
293 }
294
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);
299         return transform;
300 }
301
302
303 Player::Player(Entity &e, ChunkIndex &c)
304 : entity(e)
305 , chunks(c)
306 , inv_slot(0) {
307
308 }
309
310 Player::~Player() {
311
312 }
313
314 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
315         if (!spawn_block || spawn_block.GetType().collide_block) {
316                 return false;
317         }
318
319         BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
320         if (!head_block || head_block.GetType().collide_block) {
321                 return false;
322         }
323
324         return true;
325 }
326
327 void Player::Update(int dt) {
328         chunks.Rebase(entity.ChunkCoords());
329 }
330
331
332 World::World(const BlockTypeRegistry &types, const Config &config)
333 : config(config)
334 , block_type(types)
335 , chunks(types)
336 , players()
337 , entities()
338 , light_direction(config.light_direction)
339 , fog_density(config.fog_density) {
340
341 }
342
343 World::~World() {
344         for (Entity &e : entities) {
345                 e.Kill();
346         }
347         std::size_t removed = 0;
348         do {
349                 removed = 0;
350                 for (auto e = entities.begin(), end = entities.end(); e != end; ++e) {
351                         if (e->CanRemove()) {
352                                 e = RemoveEntity(e);
353                                 end = entities.end();
354                                 ++removed;
355                         }
356                 }
357         } while (removed > 0 && !entities.empty());
358 }
359
360
361 Player *World::AddPlayer(const std::string &name) {
362         for (Player &p : players) {
363                 if (p.Name() == name) {
364                         return nullptr;
365                 }
366         }
367         Entity &entity = AddEntity();
368         entity.Name(name);
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();
374 }
375
376 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
377         for (Player &p : players) {
378                 if (p.Name() == name) {
379                         return nullptr;
380                 }
381         }
382         Entity *entity = AddEntity(id);
383         if (!entity) {
384                 return nullptr;
385         }
386         entity->Name(name);
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();
392 }
393
394 Entity &World::AddEntity() {
395         if (entities.empty()) {
396                 entities.emplace_back();
397                 entities.back().ID(1);
398                 return entities.back();
399         }
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();
405         }
406         std::uint32_t id = 1;
407         auto position = entities.begin();
408         auto end = entities.end();
409         while (position != end && position->ID() == id) {
410                 ++id;
411                 ++position;
412         }
413         auto entity = entities.emplace(position);
414         entity->ID(id);
415         return *entity;
416 }
417
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();
423         }
424
425         auto position = entities.begin();
426         auto end = entities.end();
427         while (position != end && position->ID() < id) {
428                 ++position;
429         }
430         if (position != end && position->ID() == id) {
431                 return nullptr;
432         }
433         auto entity = entities.emplace(position);
434         entity->ID(id);
435         return &*entity;
436 }
437
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();
443         }
444
445         auto position = entities.begin();
446         auto end = entities.end();
447         while (position != end && position->ID() < id) {
448                 ++position;
449         }
450         if (position != end && position->ID() == id) {
451                 return *position;
452         }
453         auto entity = entities.emplace(position);
454         entity->ID(id);
455         return *entity;
456 }
457
458
459 namespace {
460
461 struct Candidate {
462         Chunk *chunk;
463         float dist;
464 };
465
466 bool CandidateLess(const Candidate &a, const Candidate &b) {
467         return a.dist < b.dist;
468 }
469
470 std::vector<Candidate> candidates;
471
472 }
473
474 bool World::Intersection(
475         const Ray &ray,
476         const ExactLocation::Coarse &reference,
477         WorldCollision &coll
478 ) {
479         candidates.clear();
480
481         for (Chunk &cur_chunk : chunks) {
482                 float cur_dist;
483                 if (cur_chunk.Intersection(ray, reference, cur_dist)) {
484                         candidates.push_back({ &cur_chunk, cur_dist });
485                 }
486         }
487
488         if (candidates.empty()) return false;
489
490         std::sort(candidates.begin(), candidates.end(), CandidateLess);
491
492         coll.chunk = nullptr;
493         coll.block = -1;
494         coll.depth = std::numeric_limits<float>::infinity();
495
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) {
501                                 coll = cur_coll;
502                         }
503                 }
504         }
505
506         return coll.chunk;
507 }
508
509 bool World::Intersection(
510         const Ray &ray,
511         const Entity &reference,
512         EntityCollision &coll
513 ) {
514         coll.entity = nullptr;
515         coll.depth = std::numeric_limits<float>::infinity();
516         for (Entity &cur_entity : entities) {
517                 if (&cur_entity == &reference) {
518                         continue;
519                 }
520                 float cur_dist;
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;
528                         }
529                 }
530         }
531
532         return coll.entity;
533 }
534
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);
540
541         ExactLocation::Coarse begin(reference - 1);
542         ExactLocation::Coarse end(reference + 2);
543
544         bool any = false;
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)) {
550                                         any = true;
551                                 }
552                         }
553                 }
554         }
555         return any;
556 }
557
558 bool World::Intersection(
559         const AABB &box,
560         const glm::mat4 &M,
561         const glm::ivec3 &reference,
562         std::vector<WorldCollision> &col
563 ) {
564         bool any = false;
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
569                         continue;
570                 }
571                 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
572                         any = true;
573                 }
574         }
575         return any;
576 }
577
578 void World::Update(int dt) {
579         float fdt(dt * 0.001f);
580         for (Entity &entity : entities) {
581                 Update(entity, fdt);
582         }
583         for (Entity &entity : entities) {
584                 entity.Update(fdt);
585         }
586         for (Player &player : players) {
587                 player.Update(dt);
588         }
589         for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
590                 if (iter->CanRemove()) {
591                         iter = RemoveEntity(iter);
592                 } else {
593                         ++iter;
594                 }
595         }
596 }
597
598 void World::Update(Entity &entity, float dt) {
599         EntityState state(entity.GetState());
600
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));
605
606         EntityDerivative f;
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);
610
611         state.pos.block += f.position * dt;
612         state.velocity += f.velocity * dt;
613         CollisionFix(entity, state);
614         state.AdjustPosition();
615
616         entity.SetState(state);
617 }
618
619 EntityDerivative World::CalculateStep(
620         const Entity &entity,
621         const EntityState &cur,
622         float dt,
623         const EntityDerivative &delta
624 ) {
625         EntityState next(cur);
626         next.pos.block += delta.position * dt;
627         next.velocity += delta.velocity * dt;
628         CollisionFix(entity, next);
629         next.AdjustPosition();
630
631         if (dot(next.velocity, next.velocity) > entity.MaxVelocity() * entity.MaxVelocity()) {
632                 next.velocity = normalize(next.velocity) * entity.MaxVelocity();
633         }
634
635         EntityDerivative out;
636         out.position = next.velocity;
637         out.velocity = CalculateForce(entity, next); // by mass = 1kg
638         return out;
639 }
640
641 glm::vec3 World::CalculateForce(
642         const Entity &entity,
643         const EntityState &state
644 ) {
645         glm::vec3 force(ControlForce(entity, state));
646         if (dot(force, force) > entity.MaxControlForce() * entity.MaxControlForce()) {
647                 force = normalize(force) * entity.MaxControlForce();
648         }
649         return force + Gravity(entity, state);
650 }
651
652 glm::vec3 World::ControlForce(
653         const Entity &entity,
654         const EntityState &state
655 ) {
656         return entity.ControlForce(state);
657 }
658
659 namespace {
660
661 std::vector<WorldCollision> col;
662
663 }
664
665 void World::CollisionFix(
666         const Entity &entity,
667         EntityState &state
668 ) {
669         col.clear();
670         if (!entity.WorldCollidable() || !Intersection(entity, state, col)) {
671                 // no collision, no fix
672                 return;
673         }
674         glm::vec3 correction = CombinedInterpenetration(state, col);
675         // correction may be zero in which case normalize() returns NaNs
676         if (iszero(correction)) {
677                 return;
678         }
679         // if entity is already going in the direction of correction,
680         // let the problem resolve itself
681         if (dot(state.velocity, correction) >= 0.0f) {
682                 return;
683         }
684         // apply correction, maybe could use some damping, gotta test
685         state.pos.block += correction;
686         // kill velocity?
687         glm::vec3 normal_velocity(proj(state.velocity, correction));
688         state.velocity -= normal_velocity;
689         // apply force proportional to penetration
690         // use velocity projected onto correction as damper
691         //constexpr float k = 1000.0f; // spring constant
692         //constexpr float b = 10.0f; // damper constant
693         //const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
694         //const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
695         //return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
696 }
697
698 glm::vec3 World::CombinedInterpenetration(
699         const EntityState &state,
700         const std::vector<WorldCollision> &col
701 ) noexcept {
702         // determine displacement for each cardinal axis and move entity accordingly
703         glm::vec3 min_pen(0.0f);
704         glm::vec3 max_pen(0.0f);
705         for (const WorldCollision &c : col) {
706                 if (!c.Blocks()) continue;
707                 glm::vec3 normal(c.normal);
708                 // swap if neccessary (normal may point away from the entity)
709                 if (dot(normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) < 0) {
710                         normal = -normal;
711                 }
712                 // check if block surface is "inside"
713                 Block::Face coll_face = Block::NormalFace(normal);
714                 BlockLookup neighbor(c.chunk, c.BlockPos(), coll_face);
715                 if (neighbor && neighbor.FaceFilled(Block::Opposite(coll_face))) {
716                         // yep, so ignore this contact
717                         continue;
718                 }
719                 glm::vec3 local_pen(normal * c.depth);
720                 min_pen = min(min_pen, local_pen);
721                 max_pen = max(max_pen, local_pen);
722         }
723         glm::vec3 pen(0.0f);
724         // only apply correction for axes where penetration is only in one direction
725         for (std::size_t i = 0; i < 3; ++i) {
726                 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
727                         if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
728                                 pen[i] = min_pen[i];
729                         }
730                 } else {
731                         pen[i] = max_pen[i];
732                 }
733         }
734         return pen;
735 }
736
737 glm::vec3 World::Gravity(
738         const Entity &entity,
739         const EntityState &state
740 ) {
741         glm::vec3 force(0.0f);
742         ExactLocation::Coarse begin(state.pos.chunk - 1);
743         ExactLocation::Coarse end(state.pos.chunk + 2);
744
745         for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
746                 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
747                         for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
748                                 Chunk *chunk = chunks.Get(pos);
749                                 if (chunk) {
750                                         force += chunk->GravityAt(state.pos);
751                                 }
752                         }
753                 }
754         }
755
756         return force;
757 }
758
759 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
760         // check for player
761         for (auto player = players.begin(), end = players.end(); player != end;) {
762                 if (&player->GetEntity() == &*eh) {
763                         chunks.UnregisterIndex(player->GetChunks());
764                         player = players.erase(player);
765                         end = players.end();
766                 } else {
767                         ++player;
768                 }
769         }
770         return entities.erase(eh);
771 }
772
773
774 void World::Render(Viewport &viewport) {
775         DirectionalLighting &entity_prog = viewport.EntityProgram();
776         entity_prog.SetFogDensity(fog_density);
777
778         glm::vec3 light_dir;
779         glm::vec3 light_col;
780         glm::vec3 ambient_col;
781         for (Entity &entity : entities) {
782                 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
783                 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
784                         GetLight(entity, light_dir, light_col, ambient_col);
785                         entity_prog.SetLightDirection(light_dir);
786                         entity_prog.SetLightColor(light_col);
787                         entity_prog.SetAmbientColor(ambient_col);
788                         entity.Render(M, entity_prog);
789                 }
790         }
791 }
792
793 // this should interpolate based on the fractional part of entity's block position
794 void World::GetLight(
795         const Entity &e,
796         glm::vec3 &dir,
797         glm::vec3 &col,
798         glm::vec3 &amb
799 ) {
800         Chunk *chunk = chunks.Get(e.ChunkCoords());
801         if (!chunk) {
802                 // chunk unavailable, so make it really dark and from
803                 // some arbitrary direction
804                 dir = glm::vec3(1.0f, 2.0f, 3.0f);
805                 col = glm::vec3(0.025f); // ~0.8^15
806                 return;
807         }
808         glm::ivec3 base(e.Position());
809         int base_light = chunk->GetLight(base);
810         int max_light = 0;
811         int min_light = 15;
812         glm::ivec3 acc(0, 0, 0);
813         for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
814                 for (offset.y = -1; offset.y < 2; ++offset.y) {
815                         for (offset.x = -1; offset.x < 2; ++offset.x) {
816                                 BlockLookup block(chunk, base + offset);
817                                 if (!block) {
818                                         // missing, just ignore it
819                                         continue;
820                                 }
821                                 // otherwise, accumulate the difference times direction
822                                 acc += offset * (base_light - block.GetLight());
823                                 max_light = std::max(max_light, block.GetLight());
824                                 min_light = std::min(min_light, block.GetLight());
825                         }
826                 }
827         }
828         dir = acc;
829         col = glm::vec3(std::pow(0.8f, 15 - max_light));
830         amb = glm::vec3(std::pow(0.8f, 15 - min_light));
831 }
832
833 namespace {
834
835 PrimitiveMesh::Buffer debug_buf;
836
837 }
838
839 void World::RenderDebug(Viewport &viewport) {
840         PrimitiveMesh debug_mesh;
841         PlainColor &prog = viewport.WorldColorProgram();
842         for (const Entity &entity : entities) {
843                 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
844                 debug_mesh.Update(debug_buf);
845                 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
846                 debug_mesh.DrawLines();
847         }
848 }
849
850 }