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