]> git.localhorst.tv Git - blank.git/blob - src/world/world.cpp
fix comment handling in TokenStreamReader
[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         state.AdjustPosition();
614
615         entity.SetState(state);
616 }
617
618 EntityDerivative World::CalculateStep(
619         const Entity &entity,
620         const EntityState &cur,
621         float dt,
622         const EntityDerivative &delta
623 ) {
624         EntityState next(cur);
625         next.pos.block += delta.position * dt;
626         next.velocity += delta.velocity * dt;
627         next.AdjustPosition();
628
629         if (dot(next.velocity, next.velocity) > entity.MaxVelocity() * entity.MaxVelocity()) {
630                 next.velocity = normalize(next.velocity) * entity.MaxVelocity();
631         }
632
633         EntityDerivative out;
634         out.position = next.velocity;
635         out.velocity = CalculateForce(entity, next); // by mass = 1kg
636         return out;
637 }
638
639 glm::vec3 World::CalculateForce(
640         const Entity &entity,
641         const EntityState &state
642 ) {
643         glm::vec3 force(ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state));
644         if (dot(force, force) > entity.MaxControlForce() * entity.MaxControlForce()) {
645                 return normalize(force) * entity.MaxControlForce();
646         } else {
647                 return force;
648         }
649 }
650
651 glm::vec3 World::ControlForce(
652         const Entity &entity,
653         const EntityState &state
654 ) {
655         return entity.ControlForce(state);
656 }
657
658 namespace {
659
660 std::vector<WorldCollision> col;
661
662 }
663
664 glm::vec3 World::CollisionForce(
665         const Entity &entity,
666         const EntityState &state
667 ) {
668         col.clear();
669         if (entity.WorldCollidable() && Intersection(entity, state, col)) {
670                 glm::vec3 correction = -CombinedInterpenetration(state, col);
671                 // correction may be zero in which case normalize() returns NaNs
672                 if (iszero(correction)) {
673                         return glm::vec3(0.0f);
674                 }
675                 // if entity is already going in the direction of correction,
676                 // let the problem resolve itself
677                 if (dot(state.velocity, correction) >= 0.0f) {
678                         return glm::vec3(0.0f);
679                 }
680                 glm::vec3 normal_velocity(proj(state.velocity, correction));
681                 // apply force proportional to penetration
682                 // use velocity projected onto correction as damper
683                 constexpr float k = 1000.0f; // spring constant
684                 constexpr float b = 10.0f; // damper constant
685                 const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
686                 const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
687                 return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
688         } else {
689                 return glm::vec3(0.0f);
690         }
691 }
692
693 glm::vec3 World::CombinedInterpenetration(
694         const EntityState &state,
695         const std::vector<WorldCollision> &col
696 ) noexcept {
697         // determine displacement for each cardinal axis and move entity accordingly
698         glm::vec3 min_pen(0.0f);
699         glm::vec3 max_pen(0.0f);
700         for (const WorldCollision &c : col) {
701                 if (!c.Blocks()) continue;
702                 glm::vec3 local_pen(c.normal * c.depth);
703                 // swap if neccessary (normal may point away from the entity)
704                 if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
705                         local_pen *= -1;
706                 }
707                 min_pen = min(min_pen, local_pen);
708                 max_pen = max(max_pen, local_pen);
709         }
710         glm::vec3 pen(0.0f);
711         // only apply correction for axes where penetration is only in one direction
712         for (std::size_t i = 0; i < 3; ++i) {
713                 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
714                         if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
715                                 pen[i] = min_pen[i];
716                         }
717                 } else {
718                         pen[i] = max_pen[i];
719                 }
720         }
721         return pen;
722 }
723
724 glm::vec3 World::Gravity(
725         const Entity &entity,
726         const EntityState &state
727 ) {
728         return glm::vec3(0.0f);
729 }
730
731 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
732         // check for player
733         for (auto player = players.begin(), end = players.end(); player != end;) {
734                 if (&player->GetEntity() == &*eh) {
735                         chunks.UnregisterIndex(player->GetChunks());
736                         player = players.erase(player);
737                         end = players.end();
738                 } else {
739                         ++player;
740                 }
741         }
742         return entities.erase(eh);
743 }
744
745
746 void World::Render(Viewport &viewport) {
747         DirectionalLighting &entity_prog = viewport.EntityProgram();
748         entity_prog.SetFogDensity(fog_density);
749
750         glm::vec3 light_dir;
751         glm::vec3 light_col;
752         glm::vec3 ambient_col;
753         for (Entity &entity : entities) {
754                 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
755                 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
756                         GetLight(entity, light_dir, light_col, ambient_col);
757                         entity_prog.SetLightDirection(light_dir);
758                         entity_prog.SetLightColor(light_col);
759                         entity_prog.SetAmbientColor(ambient_col);
760                         entity.Render(M, entity_prog);
761                 }
762         }
763 }
764
765 // this should interpolate based on the fractional part of entity's block position
766 void World::GetLight(
767         const Entity &e,
768         glm::vec3 &dir,
769         glm::vec3 &col,
770         glm::vec3 &amb
771 ) {
772         Chunk *chunk = chunks.Get(e.ChunkCoords());
773         if (!chunk) {
774                 // chunk unavailable, so make it really dark and from
775                 // some arbitrary direction
776                 dir = glm::vec3(1.0f, 2.0f, 3.0f);
777                 col = glm::vec3(0.025f); // ~0.8^15
778                 return;
779         }
780         glm::ivec3 base(e.Position());
781         int base_light = chunk->GetLight(base);
782         int max_light = 0;
783         int min_light = 15;
784         glm::ivec3 acc(0, 0, 0);
785         for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
786                 for (offset.y = -1; offset.y < 2; ++offset.y) {
787                         for (offset.x = -1; offset.x < 2; ++offset.x) {
788                                 BlockLookup block(chunk, base + offset);
789                                 if (!block) {
790                                         // missing, just ignore it
791                                         continue;
792                                 }
793                                 // otherwise, accumulate the difference times direction
794                                 acc += offset * (base_light - block.GetLight());
795                                 max_light = std::max(max_light, block.GetLight());
796                                 min_light = std::min(min_light, block.GetLight());
797                         }
798                 }
799         }
800         dir = acc;
801         col = glm::vec3(std::pow(0.8f, 15 - max_light));
802         amb = glm::vec3(std::pow(0.8f, 15 - min_light));
803 }
804
805 namespace {
806
807 PrimitiveMesh::Buffer debug_buf;
808
809 }
810
811 void World::RenderDebug(Viewport &viewport) {
812         PrimitiveMesh debug_mesh;
813         PlainColor &prog = viewport.WorldColorProgram();
814         for (const Entity &entity : entities) {
815                 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
816                 debug_mesh.Update(debug_buf);
817                 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
818                 debug_mesh.DrawLines();
819         }
820 }
821
822 }