]> git.localhorst.tv Git - blank.git/blob - src/world/world.cpp
safer method for lighting entities
[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         glm::vec3 force;
94         if (HasController()) {
95                 force = GetController().ControlForce(*this, s);
96         } else {
97                 force = -s.velocity;
98         }
99         limit(force, max_force);
100         return force;
101 }
102
103 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
104         state.pos.chunk = c;
105         state.pos.block = b;
106 }
107
108 void Entity::Position(const glm::vec3 &pos) noexcept {
109         state.pos.block = pos;
110         state.AdjustPosition();
111 }
112
113 void Entity::TurnHead(float dp, float dy) noexcept {
114         SetHead(state.pitch + dp, state.yaw + dy);
115 }
116
117 void Entity::SetHead(float p, float y) noexcept {
118         state.pitch = p;
119         state.yaw = y;
120 }
121
122 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
123         return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
124 }
125
126 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
127         return Transform(reference) * view_transform;
128 }
129
130 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
131         glm::mat4 transform = ViewTransform(chunk_offset);
132         return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
133 }
134
135 void Entity::Update(World &world, float dt) {
136         if (HasController()) {
137                 GetController().Update(*this, dt);
138         }
139         UpdatePhysics(world, dt);
140         UpdateTransforms();
141         UpdateHeading();
142         UpdateModel(dt);
143 }
144
145 void Entity::UpdatePhysics(World &world, float dt) {
146         EntityState s(state);
147
148         EntityDerivative a(CalculateStep(world, s, 0.0f, EntityDerivative()));
149         EntityDerivative b(CalculateStep(world, s, dt * 0.5f, a));
150         EntityDerivative c(CalculateStep(world, s, dt * 0.5f, b));
151         EntityDerivative d(CalculateStep(world, s, dt, c));
152
153         EntityDerivative f;
154         constexpr float sixth = 1.0f / 6.0f;
155         f.position = sixth * (a.position + 2.0f * (b.position + c.position) + d.position);
156         f.velocity = sixth * (a.velocity + 2.0f * (b.velocity + c.velocity) + d.velocity);
157
158         s.pos.block += f.position * dt;
159         s.velocity += f.velocity * dt;
160         limit(s.velocity, max_vel);
161         world.ResolveWorldCollision(*this, s);
162         s.AdjustPosition();
163
164         SetState(s);
165 }
166
167 EntityDerivative Entity::CalculateStep(
168         World &world,
169         const EntityState &cur,
170         float dt,
171         const EntityDerivative &delta
172 ) const {
173         EntityState next(cur);
174         next.pos.block += delta.position * dt;
175         next.velocity += delta.velocity * dt;
176         limit(next.velocity, max_vel);
177         world.ResolveWorldCollision(*this, next);
178         next.AdjustPosition();
179
180         EntityDerivative out;
181         out.position = next.velocity;
182         out.velocity = ControlForce(next) + world.GravityAt(next.pos); // by mass = 1kg
183         return out;
184 }
185
186
187 void Entity::UpdateTransforms() noexcept {
188         // model transform is the one given by current state
189         model_transform = state.Transform(state.pos.chunk);
190         // view transform is either the model's eyes transform or,
191         // should the entity have no model, the pitch (yaw already is
192         // in model transform)
193         if (model) {
194                 view_transform = model.EyesTransform();
195         } else {
196                 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
197         }
198 }
199
200 void Entity::UpdateHeading() noexcept {
201         speed = length(Velocity());
202         if (speed > std::numeric_limits<float>::epsilon()) {
203                 heading = Velocity() / speed;
204         } else {
205                 speed = 0.0f;
206                 // use -Z (forward axis) of model transform (our "chest")
207                 heading = -glm::vec3(model_transform[2]);
208         }
209 }
210
211 void Entity::UpdateModel(float dt) noexcept {
212         // first, sanitize the pitch and yaw fields of state (our input)
213         // those indicate the head orientation in the entity's local cosystem
214         state.AdjustHeading();
215         // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
216         //OrientBody(dt);
217         OrientHead(dt);
218 }
219
220 void Entity::OrientBody(float dt) noexcept {
221         // maximum body rotation per second (due to velocity orientation) (90°)
222         constexpr float max_body_turn_per_second = PI_0p5;
223         const float max_body_turn = max_body_turn_per_second * dt;
224         // minimum speed to apply body correction
225         constexpr float min_speed = 0.0625f;
226         // use local Y as up
227         const glm::vec3 up(model_transform[1]);
228         if (speed > min_speed) {
229                 // check if our orientation and velocity are aligned
230                 const glm::vec3 forward(-model_transform[2]);
231                 // facing is local -Z rotated about local Y by yaw and transformed into world space
232                 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))));
233                 // only adjust if velocity isn't almost parallel to up
234                 float vel_dot_up = dot(Velocity(), up);
235                 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
236                         // get direction of velocity projected onto model plane
237                         glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
238                         // if velocity points away from our facing (with a little bias), flip it around
239                         // (the entity is "walking backwards")
240                         if (dot(facing, direction) < -0.1f) {
241                                 direction = -direction;
242                         }
243                         // calculate the difference between forward and direction
244                         const float absolute_difference = std::acos(dot(forward, direction));
245                         // if direction is clockwise with respect to up vector, invert the angle
246                         const float relative_difference = dot(cross(forward, direction), up) < 0.0f
247                                 ? -absolute_difference
248                                 : absolute_difference;
249                         // only correct by half the difference max
250                         const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
251                         if (ID() == 1) {
252                                 std::cout << "orientation before: " << state.orient << std::endl;
253                                 std::cout << "up:        " << up << std::endl;
254                                 std::cout << "forward:   " << forward << std::endl;
255                                 std::cout << "facing:    " << facing << std::endl;
256                                 std::cout << "direction: " << direction << std::endl;
257                                 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
258                                 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
259                                 std::cout << std::endl;
260                         }
261                         // now rotate body by correction and head by -correction
262                         state.orient = rotate(state.orient, correction, up);
263                         state.yaw -= correction;
264                 }
265         }
266 }
267
268 void Entity::OrientHead(float dt) noexcept {
269         // maximum yaw of head (60°)
270         constexpr float max_head_yaw = PI / 3.0f;
271         // use local Y as up
272         const glm::vec3 up(model_transform[1]);
273         // if yaw is bigger than max, rotate the body to accomodate
274         if (std::abs(state.yaw) > max_head_yaw) {
275                 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
276                 // rotate the entity by deviation about local Y
277                 state.orient = rotate(state.orient, deviation, up);
278                 // and remove from head yaw
279                 state.yaw -= deviation;
280                 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
281                 state.AdjustHeading();
282         }
283         // update model if any
284         if (model) {
285                 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
286         }
287 }
288
289
290 EntityController::~EntityController() {
291
292 }
293
294 bool EntityController::MaxOutForce(
295         glm::vec3 &out,
296         const glm::vec3 &add,
297         float max
298 ) noexcept {
299         if (iszero(add) || any(isnan(add))) {
300                 return false;
301         }
302         float current = iszero(out) ? 0.0f : length(out);
303         float remain = max - current;
304         if (remain <= 0.0f) {
305                 return true;
306         }
307         float additional = length(add);
308         if (additional > remain) {
309                 out += normalize(add) * remain;
310                 return true;
311         } else {
312                 out += add;
313                 return false;
314         }
315 }
316
317
318 EntityState::EntityState()
319 : pos()
320 , velocity(0.0f)
321 , orient(1.0f, 0.0f, 0.0f, 0.0f)
322 , pitch(0.0f)
323 , yaw(0.0f) {
324
325 }
326
327 void EntityState::AdjustPosition() noexcept {
328         pos.Correct();
329 }
330
331 void EntityState::AdjustHeading() noexcept {
332         pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
333         while (yaw > PI) {
334                 yaw -= PI_2p0;
335         }
336         while (yaw < -PI) {
337                 yaw += PI_2p0;
338         }
339 }
340
341 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
342         const glm::vec3 translation = RelativePosition(reference);
343         glm::mat4 transform(toMat4(orient));
344         transform[3] = glm::vec4(translation, 1.0f);
345         return transform;
346 }
347
348
349 Player::Player(Entity &e, ChunkIndex &c)
350 : entity(e)
351 , chunks(c)
352 , inv_slot(0) {
353
354 }
355
356 Player::~Player() {
357
358 }
359
360 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
361         if (!spawn_block || spawn_block.GetType().collide_block) {
362                 return false;
363         }
364
365         BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
366         if (!head_block || head_block.GetType().collide_block) {
367                 return false;
368         }
369
370         return true;
371 }
372
373 void Player::Update(int dt) {
374         chunks.Rebase(entity.ChunkCoords());
375 }
376
377
378 World::World(const BlockTypeRegistry &types, const Config &config)
379 : config(config)
380 , block_type(types)
381 , chunks(types)
382 , players()
383 , entities()
384 , light_direction(config.light_direction)
385 , fog_density(config.fog_density) {
386
387 }
388
389 World::~World() {
390         for (Entity &e : entities) {
391                 e.Kill();
392         }
393         std::size_t removed = 0;
394         do {
395                 removed = 0;
396                 for (auto e = entities.begin(), end = entities.end(); e != end; ++e) {
397                         if (e->CanRemove()) {
398                                 e = RemoveEntity(e);
399                                 end = entities.end();
400                                 ++removed;
401                         }
402                 }
403         } while (removed > 0 && !entities.empty());
404 }
405
406
407 Player *World::AddPlayer(const std::string &name) {
408         for (Player &p : players) {
409                 if (p.Name() == name) {
410                         return nullptr;
411                 }
412         }
413         Entity &entity = AddEntity();
414         entity.Name(name);
415         entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
416         entity.WorldCollidable(true);
417         ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
418         players.emplace_back(entity, index);
419         return &players.back();
420 }
421
422 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
423         for (Player &p : players) {
424                 if (p.Name() == name) {
425                         return nullptr;
426                 }
427         }
428         Entity *entity = AddEntity(id);
429         if (!entity) {
430                 return nullptr;
431         }
432         entity->Name(name);
433         entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
434         entity->WorldCollidable(true);
435         ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
436         players.emplace_back(*entity, index);
437         return &players.back();
438 }
439
440 Entity &World::AddEntity() {
441         if (entities.empty()) {
442                 entities.emplace_back();
443                 entities.back().ID(1);
444                 return entities.back();
445         }
446         if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
447                 std::uint32_t id = entities.back().ID() + 1;
448                 entities.emplace_back();
449                 entities.back().ID(id);
450                 return entities.back();
451         }
452         std::uint32_t id = 1;
453         auto position = entities.begin();
454         auto end = entities.end();
455         while (position != end && position->ID() == id) {
456                 ++id;
457                 ++position;
458         }
459         auto entity = entities.emplace(position);
460         entity->ID(id);
461         return *entity;
462 }
463
464 Entity *World::AddEntity(std::uint32_t id) {
465         if (entities.empty() || entities.back().ID() < id) {
466                 entities.emplace_back();
467                 entities.back().ID(id);
468                 return &entities.back();
469         }
470
471         auto position = entities.begin();
472         auto end = entities.end();
473         while (position != end && position->ID() < id) {
474                 ++position;
475         }
476         if (position != end && position->ID() == id) {
477                 return nullptr;
478         }
479         auto entity = entities.emplace(position);
480         entity->ID(id);
481         return &*entity;
482 }
483
484 Entity &World::ForceAddEntity(std::uint32_t id) {
485         if (entities.empty() || entities.back().ID() < id) {
486                 entities.emplace_back();
487                 entities.back().ID(id);
488                 return entities.back();
489         }
490
491         auto position = entities.begin();
492         auto end = entities.end();
493         while (position != end && position->ID() < id) {
494                 ++position;
495         }
496         if (position != end && position->ID() == id) {
497                 return *position;
498         }
499         auto entity = entities.emplace(position);
500         entity->ID(id);
501         return *entity;
502 }
503
504
505 namespace {
506
507 struct Candidate {
508         Chunk *chunk;
509         float dist;
510 };
511
512 bool CandidateLess(const Candidate &a, const Candidate &b) {
513         return a.dist < b.dist;
514 }
515
516 std::vector<Candidate> candidates;
517
518 }
519
520 bool World::Intersection(
521         const Ray &ray,
522         const ExactLocation::Coarse &reference,
523         WorldCollision &coll
524 ) {
525         candidates.clear();
526
527         for (Chunk &cur_chunk : chunks) {
528                 float cur_dist;
529                 if (cur_chunk.Intersection(ray, reference, cur_dist)) {
530                         candidates.push_back({ &cur_chunk, cur_dist });
531                 }
532         }
533
534         if (candidates.empty()) return false;
535
536         std::sort(candidates.begin(), candidates.end(), CandidateLess);
537
538         coll.chunk = nullptr;
539         coll.block = -1;
540         coll.depth = std::numeric_limits<float>::infinity();
541
542         for (Candidate &cand : candidates) {
543                 if (cand.dist > coll.depth) continue;
544                 WorldCollision cur_coll;
545                 if (cand.chunk->Intersection(ray, reference, cur_coll)) {
546                         if (cur_coll.depth < coll.depth) {
547                                 coll = cur_coll;
548                         }
549                 }
550         }
551
552         return coll.chunk;
553 }
554
555 bool World::Intersection(
556         const Ray &ray,
557         const Entity &reference,
558         EntityCollision &coll
559 ) {
560         coll.entity = nullptr;
561         coll.depth = std::numeric_limits<float>::infinity();
562         for (Entity &cur_entity : entities) {
563                 if (&cur_entity == &reference) {
564                         continue;
565                 }
566                 float cur_dist;
567                 glm::vec3 cur_normal;
568                 if (blank::Intersection(ray, cur_entity.Bounds(), cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
569                         // TODO: fine grained check goes here? maybe?
570                         if (cur_dist < coll.depth) {
571                                 coll.entity = &cur_entity;
572                                 coll.depth = cur_dist;
573                                 coll.normal = cur_normal;
574                         }
575                 }
576         }
577
578         return coll.entity;
579 }
580
581 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
582         glm::ivec3 reference = s.pos.chunk;
583         glm::mat4 M = s.Transform(reference);
584
585         ExactLocation::Coarse begin(reference - 1);
586         ExactLocation::Coarse end(reference + 2);
587
588         bool any = false;
589         for (ExactLocation::Coarse pos(begin); pos.z < end.y; ++pos.z) {
590                 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
591                         for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
592                                 Chunk *chunk = chunks.Get(pos);
593                                 if (chunk && chunk->Intersection(e, M, chunk->Transform(reference), col)) {
594                                         any = true;
595                                 }
596                         }
597                 }
598         }
599         return any;
600 }
601
602 bool World::Intersection(
603         const AABB &box,
604         const glm::mat4 &M,
605         const glm::ivec3 &reference,
606         std::vector<WorldCollision> &col
607 ) {
608         bool any = false;
609         for (Chunk &cur_chunk : chunks) {
610                 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
611                         // chunk is not one of the 3x3x3 surrounding the entity
612                         // since there's no entity which can extent over 16 blocks, they can be skipped
613                         // TODO: change to indexed (like with entity)
614                         continue;
615                 }
616                 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
617                         any = true;
618                 }
619         }
620         return any;
621 }
622
623 void World::Update(int dt) {
624         float fdt(dt * 0.001f);
625         for (Entity &entity : entities) {
626                 entity.Update(*this, fdt);
627         }
628         for (Player &player : players) {
629                 player.Update(dt);
630         }
631         for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
632                 if (iter->CanRemove()) {
633                         iter = RemoveEntity(iter);
634                 } else {
635                         ++iter;
636                 }
637         }
638 }
639
640 namespace {
641
642 std::vector<WorldCollision> col;
643
644 }
645
646 void World::ResolveWorldCollision(
647         const Entity &entity,
648         EntityState &state
649 ) {
650         col.clear();
651         if (!entity.WorldCollidable() || !Intersection(entity, state, col)) {
652                 // no collision, no fix
653                 return;
654         }
655         glm::vec3 correction = CombinedInterpenetration(state, col);
656         // correction may be zero in which case normalize() returns NaNs
657         if (iszero(correction)) {
658                 return;
659         }
660         // if entity is already going in the direction of correction,
661         // let the problem resolve itself
662         if (dot(state.velocity, correction) >= 0.0f) {
663                 return;
664         }
665         // apply correction, maybe could use some damping, gotta test
666         state.pos.block += correction;
667         // kill velocity?
668         glm::vec3 normal_velocity(proj(state.velocity, correction));
669         state.velocity -= normal_velocity;
670 }
671
672 glm::vec3 World::CombinedInterpenetration(
673         const EntityState &state,
674         const std::vector<WorldCollision> &col
675 ) noexcept {
676         // determine displacement for each cardinal axis and move entity accordingly
677         glm::vec3 min_pen(0.0f);
678         glm::vec3 max_pen(0.0f);
679         for (const WorldCollision &c : col) {
680                 if (!c.Blocks()) continue;
681                 glm::vec3 normal(c.normal);
682                 // swap if neccessary (normal may point away from the entity)
683                 if (dot(normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) < 0) {
684                         normal = -normal;
685                 }
686                 // check if block surface is "inside"
687                 Block::Face coll_face = Block::NormalFace(normal);
688                 BlockLookup neighbor(c.chunk, c.BlockPos(), coll_face);
689                 if (neighbor && neighbor.FaceFilled(Block::Opposite(coll_face))) {
690                         // yep, so ignore this contact
691                         continue;
692                 }
693                 glm::vec3 local_pen(normal * c.depth);
694                 min_pen = min(min_pen, local_pen);
695                 max_pen = max(max_pen, local_pen);
696         }
697         glm::vec3 pen(0.0f);
698         // only apply correction for axes where penetration is only in one direction
699         for (std::size_t i = 0; i < 3; ++i) {
700                 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
701                         if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
702                                 pen[i] = min_pen[i];
703                         }
704                 } else {
705                         pen[i] = max_pen[i];
706                 }
707         }
708         return pen;
709 }
710
711 glm::vec3 World::GravityAt(const ExactLocation &loc) const noexcept {
712         glm::vec3 force(0.0f);
713         ExactLocation::Coarse begin(loc.chunk - 1);
714         ExactLocation::Coarse end(loc.chunk + 2);
715
716         for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
717                 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
718                         for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
719                                 const Chunk *chunk = chunks.Get(pos);
720                                 if (chunk) {
721                                         force += chunk->GravityAt(loc);
722                                 }
723                         }
724                 }
725         }
726
727         return force;
728 }
729
730 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
731         // check for player
732         for (auto player = players.begin(), end = players.end(); player != end;) {
733                 if (&player->GetEntity() == &*eh) {
734                         chunks.UnregisterIndex(player->GetChunks());
735                         player = players.erase(player);
736                         end = players.end();
737                 } else {
738                         ++player;
739                 }
740         }
741         return entities.erase(eh);
742 }
743
744
745 void World::Render(Viewport &viewport) {
746         DirectionalLighting &entity_prog = viewport.EntityProgram();
747         entity_prog.SetFogDensity(fog_density);
748
749         glm::vec3 light_dir;
750         glm::vec3 light_col;
751         glm::vec3 ambient_col;
752         for (Entity &entity : entities) {
753                 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
754                 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
755                         GetLight(entity, light_dir, light_col, ambient_col);
756                         entity_prog.SetLightDirection(light_dir);
757                         entity_prog.SetLightColor(light_col);
758                         entity_prog.SetAmbientColor(ambient_col);
759                         entity.Render(M, entity_prog);
760                 }
761         }
762 }
763
764 // this should interpolate based on the fractional part of entity's block position
765 void World::GetLight(
766         const Entity &e,
767         glm::vec3 &dir,
768         glm::vec3 &col,
769         glm::vec3 &amb
770 ) {
771         BlockLookup center(chunks.Get(e.ChunkCoords()), e.Position());
772         if (!center) {
773                 // chunk unavailable, so make it really dark and from
774                 // some arbitrary direction
775                 dir = glm::vec3(1.0f, 2.0f, 3.0f);
776                 col = glm::vec3(0.025f); // ~0.8^15
777                 return;
778         }
779         glm::ivec3 base(center.GetBlockPos());
780         int base_light = center.GetLight();
781         int max_light = 0;
782         int min_light = 15;
783         glm::ivec3 acc(0, 0, 0);
784         for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
785                 for (offset.y = -1; offset.y < 2; ++offset.y) {
786                         for (offset.x = -1; offset.x < 2; ++offset.x) {
787                                 BlockLookup block(&center.GetChunk(), center.GetBlockPos() + offset);
788                                 if (!block) {
789                                         // missing, just ignore it
790                                         continue;
791                                 }
792                                 // otherwise, accumulate the difference times direction
793                                 acc += offset * (base_light - block.GetLight());
794                                 max_light = std::max(max_light, block.GetLight());
795                                 min_light = std::min(min_light, block.GetLight());
796                         }
797                 }
798         }
799         dir = acc;
800         col = glm::vec3(std::pow(0.8f, 15 - max_light));
801         amb = glm::vec3(std::pow(0.8f, 15 - min_light));
802 }
803
804 namespace {
805
806 PrimitiveMesh::Buffer debug_buf;
807
808 }
809
810 void World::RenderDebug(Viewport &viewport) {
811         PrimitiveMesh debug_mesh;
812         PlainColor &prog = viewport.WorldColorProgram();
813         for (const Entity &entity : entities) {
814                 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
815                 debug_mesh.Update(debug_buf);
816                 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
817                 debug_mesh.DrawLines();
818         }
819 }
820
821 }