]> git.localhorst.tv Git - blank.git/blob - ui/ui.cpp
new gcc version
[blank.git] / ui / ui.cpp
1 #include "ClientController.hpp"
2 #include "DirectInput.hpp"
3 #include "HUD.hpp"
4 #include "InteractiveManipulator.hpp"
5 #include "Interface.hpp"
6 #include "Keymap.hpp"
7 #include "PlayerController.hpp"
8
9 #include "../app/Assets.hpp"
10 #include "../app/Config.hpp"
11 #include "../app/Environment.hpp"
12 #include "../app/FrameCounter.hpp"
13 #include "../audio/Audio.hpp"
14 #include "../audio/SoundBank.hpp"
15 #include "../geometry/distance.hpp"
16 #include "../graphics/Font.hpp"
17 #include "../graphics/Viewport.hpp"
18 #include "../io/TokenStreamReader.hpp"
19 #include "../model/bounds.hpp"
20 #include "../net/CongestionControl.hpp"
21 #include "../world/BlockLookup.hpp"
22 #include "../world/World.hpp"
23 #include "../world/WorldManipulator.hpp"
24
25 #include <algorithm>
26 #include <cmath>
27 #include <iostream>
28 #include <map>
29 #include <sstream>
30 #include <glm/gtc/matrix_transform.hpp>
31 #include <glm/gtx/projection.hpp>
32 #include <glm/gtx/rotate_vector.hpp>
33 #include <glm/gtx/io.hpp>
34
35
36 namespace blank {
37
38 PlayerController::PlayerController(World &world, Player &player)
39 : world(world)
40 , player(player)
41 , move_dir(0.0f)
42 , dirty(true)
43 , aim_world()
44 , aim_entity() {
45         player.GetEntity().SetController(*this);
46         player.GetEntity().GetSteering().SetAcceleration(5.0f);
47 }
48
49 PlayerController::~PlayerController() {
50         if (&player.GetEntity().GetController() == this) {
51                 player.GetEntity().UnsetController();
52         }
53 }
54
55 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
56         if (glm::dot(m, m) > 1.0f) {
57                 move_dir = glm::normalize(m);
58         } else {
59                 move_dir = m;
60         }
61         Invalidate();
62 }
63
64 void PlayerController::TurnHead(float dp, float dy) noexcept {
65         player.GetEntity().TurnHead(dp, dy);
66 }
67
68 float PlayerController::GetPitch() const noexcept {
69         return player.GetEntity().Pitch();
70 }
71
72 float PlayerController::GetYaw() const noexcept {
73         return player.GetEntity().Yaw();
74 }
75
76 void PlayerController::SelectInventory(int i) noexcept {
77         player.SetInventorySlot(i);
78 }
79
80 int PlayerController::InventorySlot() const noexcept {
81         return player.GetInventorySlot();
82 }
83
84 void PlayerController::Invalidate() noexcept {
85         dirty = true;
86 }
87
88 void PlayerController::UpdatePlayer() noexcept {
89         if (dirty) {
90                 Ray aim = player.Aim();
91                 Entity &entity = player.GetEntity();
92                 if (!world.Intersection(aim, entity.ChunkCoords(), aim_world)) {
93                         aim_world = WorldCollision();
94                 }
95                 if (!world.Intersection(aim, entity, aim_entity)) {
96                         aim_entity = EntityCollision();
97                 }
98                 if (aim_world && aim_entity) {
99                         // got both, pick the closest one
100                         if (aim_world.depth < aim_entity.depth) {
101                                 aim_entity = EntityCollision();
102                         } else {
103                                 aim_world = WorldCollision();
104                         }
105                 }
106                 Steering &steering = entity.GetSteering();
107                 if (!iszero(move_dir)) {
108                         // scale input by max velocity, apply yaw, and transform to world space
109                         steering.SetTargetVelocity(glm::vec3(
110                                 glm::vec4(glm::rotateY(move_dir * entity.MaxVelocity(), entity.Yaw()), 0.0f)
111                                 * glm::transpose(entity.Transform())
112                         ));
113                         steering.Enable(Steering::TARGET_VELOCITY);
114                         steering.Disable(Steering::HALT);
115                 } else {
116                         // target velocity of 0 is the same as halt
117                         steering.Enable(Steering::HALT);
118                         steering.Disable(Steering::TARGET_VELOCITY);
119                 }
120                 dirty = false;
121         }
122 }
123
124
125 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
126 : PlayerController(world, player)
127 , manip(manip)
128 , place_timer(0.25f)
129 , remove_timer(0.25f) {
130
131 }
132
133 void DirectInput::Update(Entity &, float dt) {
134         Invalidate(); // world has changed in the meantime
135         UpdatePlayer();
136
137         remove_timer.Update(dt);
138         if (remove_timer.Hit()) {
139                 RemoveBlock();
140         }
141
142         place_timer.Update(dt);
143         if (place_timer.Hit()) {
144                 PlaceBlock();
145         }
146 }
147
148 void DirectInput::StartPrimaryAction() {
149         if (!remove_timer.Running()) {
150                 RemoveBlock();
151                 remove_timer.Start();
152         }
153 }
154
155 void DirectInput::StopPrimaryAction() {
156         remove_timer.Stop();
157 }
158
159 void DirectInput::StartSecondaryAction() {
160         if (!place_timer.Running()) {
161                 PlaceBlock();
162                 place_timer.Start();
163         }
164 }
165
166 void DirectInput::StopSecondaryAction() {
167         place_timer.Stop();
168 }
169
170 void DirectInput::StartTertiaryAction() {
171         PickBlock();
172 }
173
174 void DirectInput::StopTertiaryAction() {
175         // nothing
176 }
177
178 void DirectInput::PickBlock() {
179         UpdatePlayer();
180         if (!BlockFocus()) return;
181         SelectInventory(BlockFocus().GetBlock().type - 1);
182 }
183
184 void DirectInput::PlaceBlock() {
185         // update block focus
186         UpdatePlayer();
187         // do nothing if not looking at any block
188         if (!BlockFocus()) return;
189
190         // determine block adjacent to the face the player is looking at
191         BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
192         // abort if it's unavailable
193         if (!next_block) {
194                 return;
195         }
196
197         // "can replace" check
198         // this prevents players from replacing solid blocks e.g. by looking through slabs
199         // simple for now, should be expanded to include things like
200         // entities in the way or replacable blocks like water and stuff
201         if (next_block.GetBlock().type != 0) {
202                 return;
203         }
204
205         Block new_block(InventorySlot() + 1);
206
207         // block's up vector
208         // align with player's up
209         const glm::vec3 player_up(GetPlayer().GetEntity().Up());
210         new_block.SetFace(Block::NormalFace(player_up));
211         // to align with player's local up/down look (like stairs in minecraft), just invert
212         // it if pitch is positive
213         // or, align with focus normal (like logs in minecraft)
214
215         // determine block's turn (local rotation about up axis)
216         // when aligned with player's up (first mode, and currently the only one implemented)
217         // project the player's view forward onto his entity's XZ plane and
218         // use the closest cardinal direction it's pointing in
219         const glm::vec3 view_forward(-GetPlayer().GetEntity().ViewTransform(GetPlayer().GetEntity().ChunkCoords())[2]);
220         // if view is straight up or down, this will be a null vector (NaN after normalization)
221         // in that case maybe the model forward should be used?
222         // the current implementation implicitly falls back to TURN_NONE which is -Z
223         const glm::vec3 local_forward(glm::normalize(view_forward - glm::proj(view_forward, player_up)));
224         // FIXME: I suspect this only works when player_up is positive Y
225         if (local_forward.x > 0.707f) {
226                 new_block.SetTurn(Block::TURN_RIGHT);
227         } else if (local_forward.z > 0.707f) {
228                 new_block.SetTurn(Block::TURN_AROUND);
229         } else if (local_forward.x < -0.707f) {
230                 new_block.SetTurn(Block::TURN_LEFT);
231         }
232         // for mode two ("minecraft stairs") it should work the same, but I haven't properly
233         // thought that through (well, that's also true about the whole face/turn thing, but oh well)
234         // mode three I have absoloutely no clue. that placement would be appropriate for pipe-like
235         // blocks, where turn shouldn't make a difference, but what if it does?
236
237         manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), new_block);
238         Invalidate();
239 }
240
241 void DirectInput::RemoveBlock() {
242         UpdatePlayer();
243         if (!BlockFocus()) return;
244         manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
245         Invalidate();
246 }
247
248
249 HUD::HUD(Environment &env, Config &config, const Player &player)
250 : env(env)
251 , config(config)
252 , player(player)
253 // block focus
254 , outline()
255 , outline_transform(1.0f)
256 , outline_visible(false)
257 // "inventory"
258 , block()
259 , block_buf()
260 , block_transform(1.0f)
261 , block_label()
262 , block_visible(false)
263 // debug overlay
264 , counter_text()
265 , position_text()
266 , orientation_text()
267 , block_text()
268 , show_block(false)
269 , show_entity(false)
270 // net stats
271 , bandwidth_text()
272 , rtt_text()
273 , packet_loss_text()
274 , show_net(false)
275 // message box
276 , messages(env.assets.small_ui_font)
277 , msg_timer(5000)
278 , msg_keep(false)
279 // crosshair
280 , crosshair() {
281         const float ls = env.assets.small_ui_font.LineSkip();
282
283         // "inventory"
284         block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
285         block_transform = glm::scale(block_transform, glm::vec3(50.0f));
286         block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
287         block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
288         block_label.Position(
289                 glm::vec3(50.0f, 85.0f, 0.0f),
290                 Gravity::NORTH_WEST,
291                 Gravity::NORTH
292         );
293         block_label.Foreground(glm::vec4(1.0f));
294         block_label.Background(glm::vec4(0.5f));
295
296         // debug overlay
297         counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
298         counter_text.Foreground(glm::vec4(1.0f));
299         counter_text.Background(glm::vec4(0.5f));
300         position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
301         position_text.Foreground(glm::vec4(1.0f));
302         position_text.Background(glm::vec4(0.5f));
303         orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
304         orientation_text.Foreground(glm::vec4(1.0f));
305         orientation_text.Background(glm::vec4(0.5f));
306         block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
307         block_text.Foreground(glm::vec4(1.0f));
308         block_text.Background(glm::vec4(0.5f));
309         block_text.Set(env.assets.small_ui_font, "Block: none");
310         entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
311         entity_text.Foreground(glm::vec4(1.0f));
312         entity_text.Background(glm::vec4(0.5f));
313         entity_text.Set(env.assets.small_ui_font, "Entity: none");
314
315         // net stats
316         bandwidth_text.Position(glm::vec3(-25.0f, 25.0f + 6 * ls, 0.0f), Gravity::NORTH_EAST);
317         bandwidth_text.Foreground(glm::vec4(1.0f));
318         bandwidth_text.Background(glm::vec4(0.5f));
319         bandwidth_text.Set(env.assets.small_ui_font, "TX: 0.0KB/s RX: 0.0KB/s");
320         rtt_text.Position(glm::vec3(-25.0f, 25.0f + 7 * ls, 0.0f), Gravity::NORTH_EAST);
321         rtt_text.Foreground(glm::vec4(1.0f));
322         rtt_text.Background(glm::vec4(0.5f));
323         rtt_text.Set(env.assets.small_ui_font, "RTT: unavailable");
324         packet_loss_text.Position(glm::vec3(-25.0f, 25.0f + 8 * ls, 0.0f), Gravity::NORTH_EAST);
325         packet_loss_text.Foreground(glm::vec4(1.0f));
326         packet_loss_text.Background(glm::vec4(0.5f));
327         packet_loss_text.Set(env.assets.small_ui_font, "Packet loss: 0.0%");
328
329         // message box
330         messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
331         messages.Foreground(glm::vec4(1.0f));
332         messages.Background(glm::vec4(0.5f));
333
334         // crosshair
335         PrimitiveMesh::Buffer buf;
336         buf.vertices = std::vector<glm::vec3>({
337                 { -10.0f,   0.0f, 0.0f }, { 10.0f,  0.0f, 0.0f },
338                 {   0.0f, -10.0f, 0.0f }, {  0.0f, 10.0f, 0.0f },
339         });
340         buf.indices = std::vector<PrimitiveMesh::Index>({
341                 0, 1, 2, 3
342         });
343         buf.colors.resize(4, { 255, 255, 255, 255 });
344         crosshair.Update(buf);
345 }
346
347 namespace {
348
349 PrimitiveMesh::Buffer outl_buf;
350
351 }
352
353 void HUD::FocusBlock(const Chunk &chunk, int index) {
354         const Block &block = chunk.BlockAt(index);
355         const BlockType &type = chunk.Type(index);
356         outl_buf.Clear();
357         type.OutlinePrimitiveMesh(outl_buf);
358         outline.Update(outl_buf);
359         outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
360         outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
361         outline_transform *= glm::scale(glm::vec3(1.005f));
362         outline_visible = true;
363         {
364                 std::stringstream s;
365                 s << "Block: "
366                         << type.label
367                         << ", face: " << block.GetFace()
368                         << ", turn: " << block.GetTurn();
369                 block_text.Set(env.assets.small_ui_font, s.str());
370         }
371         show_block = true;
372         show_entity = false;
373 }
374
375 void HUD::FocusEntity(const Entity &entity) {
376         {
377                 std::stringstream s;
378                 s << "Entity: " << entity.Name();
379                 entity_text.Set(env.assets.small_ui_font, s.str());
380         }
381         show_block = false;
382         show_entity = true;
383 }
384
385 void HUD::FocusNone() {
386         outline_visible = false;
387         show_block = false;
388         show_entity = false;
389 }
390
391 void HUD::DisplayNone() {
392         block_visible = false;
393 }
394
395 void HUD::Display(const BlockType &type) {
396         block_buf.Clear();
397         type.FillEntityMesh(block_buf);
398         block.Update(block_buf);
399
400         block_label.Set(env.assets.small_ui_font, type.label);
401
402         block_visible = type.visible;
403 }
404
405
406 void HUD::UpdateDebug() {
407         UpdateCounter();
408         UpdatePosition();
409         UpdateOrientation();
410 }
411
412 void HUD::UpdateCounter() {
413         std::stringstream s;
414         s << std::setprecision(3) <<
415                 "avg: " << env.counter.Average().running << "ms, "
416                 "peak: " << env.counter.Peak().running << "ms";
417         std::string text = s.str();
418         counter_text.Set(env.assets.small_ui_font, text);
419 }
420
421 void HUD::UpdatePosition() {
422         std::stringstream s;
423         s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
424         position_text.Set(env.assets.small_ui_font, s.str());
425 }
426
427 void HUD::UpdateOrientation() {
428         std::stringstream s;
429         s << std::setprecision(3) << "pitch: " << glm::degrees(player.GetEntity().Pitch())
430                 << ", yaw: " << glm::degrees(player.GetEntity().Yaw());
431         orientation_text.Set(env.assets.small_ui_font, s.str());
432 }
433
434 void HUD::PostMessage(const char *msg) {
435         messages.PushLine(msg);
436         msg_timer.Reset();
437         msg_timer.Start();
438         std::cout << msg << std::endl;
439 }
440
441
442 void HUD::UpdateNetStats(const CongestionControl &stat) {
443         if (!config.video.debug) return;
444
445         std::stringstream s;
446         s << std::fixed << std::setprecision(1)
447                 << "TX: " << stat.Upstream()
448                 << "KB/s, RX: " << stat.Downstream() << "KB/s";
449         bandwidth_text.Set(env.assets.small_ui_font, s.str());
450
451         s.str("");
452         s << "RTT: " << stat.RoundTripTime() << "ms";
453         rtt_text.Set(env.assets.small_ui_font, s.str());
454
455         s.str("");
456         s << "Packet loss: " << (stat.PacketLoss() * 100.0f) << "%";
457         packet_loss_text.Set(env.assets.small_ui_font, s.str());
458
459         show_net = true;
460 }
461
462
463 void HUD::Update(int dt) {
464         msg_timer.Update(dt);
465         if (msg_timer.HitOnce()) {
466                 msg_timer.Stop();
467         }
468
469         if (config.video.debug) {
470                 if (env.counter.Changed()) {
471                         UpdateCounter();
472                 }
473                 UpdatePosition();
474                 UpdateOrientation();
475         }
476 }
477
478 void HUD::Render(Viewport &viewport) noexcept {
479         // block focus
480         if (outline_visible && config.video.world) {
481                 PlainColor &outline_prog = viewport.WorldColorProgram();
482                 outline_prog.SetM(outline_transform);
483                 outline.DrawLines();
484         }
485
486         // clear depth buffer so everything renders above the world
487         viewport.ClearDepth();
488
489         if (config.video.hud) {
490                 // "inventory"
491                 if (block_visible) {
492                         DirectionalLighting &world_prog = viewport.HUDProgram();
493                         world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
494                         world_prog.SetLightColor({ 1.0f, 1.0f, 1.0f });
495                         world_prog.SetAmbientColor({ 0.1f, 0.1f, 0.1f });
496                         // disable distance fog
497                         world_prog.SetFogDensity(0.0f);
498
499                         viewport.DisableBlending();
500                         world_prog.SetM(block_transform);
501                         block.Draw();
502                         block_label.Render(viewport);
503                 }
504
505                 // message box
506                 if (msg_keep || msg_timer.Running()) {
507                         messages.Render(viewport);
508                 }
509
510                 // crosshair
511                 PlainColor &outline_prog = viewport.HUDColorProgram();
512                 viewport.EnableInvertBlending();
513                 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
514                 outline_prog.SetM(viewport.Cursor());
515                 crosshair.DrawLines();
516         }
517
518         // debug overlay
519         if (config.video.debug) {
520                 counter_text.Render(viewport);
521                 position_text.Render(viewport);
522                 orientation_text.Render(viewport);
523                 if (show_block) {
524                         block_text.Render(viewport);
525                 } else if (show_entity) {
526                         entity_text.Render(viewport);
527                 }
528                 if (show_net) {
529                         bandwidth_text.Render(viewport);
530                         rtt_text.Render(viewport);
531                         packet_loss_text.Render(viewport);
532                 }
533         }
534 }
535
536
537 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
538 : player(player)
539 , audio(audio)
540 , sounds(sounds) {
541
542 }
543
544 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
545         const BlockType &old_type = chunk.Type(index);
546         chunk.SetBlock(index, block);
547         const BlockType &new_type = chunk.Type(index);
548         glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
549         if (new_type.id == 0) {
550                 if (old_type.remove_sound >= 0) {
551                         audio.Play(sounds[old_type.remove_sound], coords);
552                 }
553         } else {
554                 if (new_type.place_sound >= 0) {
555                         audio.Play(sounds[new_type.place_sound], coords);
556                 }
557         }
558 }
559
560
561 Interface::Interface(
562         Config &config,
563         const Keymap &keymap,
564         PlayerController &pc,
565         ClientController &cc)
566 : config(config)
567 , keymap(keymap)
568 , player_ctrl(pc)
569 , client_ctrl(cc)
570 , fwd(0)
571 , rev(0)
572 , num_slots(10)
573 , locked(false) {
574
575 }
576
577 void Interface::Lock() {
578         fwd = glm::ivec3(0);
579         rev = glm::ivec3(0);
580         locked = true;
581 }
582
583 void Interface::Unlock() {
584         locked = false;
585 }
586
587 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
588         if (!config.input.keyboard) return;
589
590         Keymap::Action action = keymap.Lookup(event);
591         switch (action) {
592                 case Keymap::MOVE_FORWARD:
593                         rev.z = 1;
594                         UpdateMovement();
595                         break;
596                 case Keymap::MOVE_BACKWARD:
597                         fwd.z = 1;
598                         UpdateMovement();
599                         break;
600                 case Keymap::MOVE_LEFT:
601                         rev.x = 1;
602                         UpdateMovement();
603                         break;
604                 case Keymap::MOVE_RIGHT:
605                         fwd.x = 1;
606                         UpdateMovement();
607                         break;
608                 case Keymap::MOVE_UP:
609                         fwd.y = 1;
610                         UpdateMovement();
611                         break;
612                 case Keymap::MOVE_DOWN:
613                         rev.y = 1;
614                         UpdateMovement();
615                         break;
616
617                 case Keymap::PRIMARY:
618                         player_ctrl.StartPrimaryAction();
619                         break;
620                 case Keymap::SECONDARY:
621                         player_ctrl.StartSecondaryAction();
622                         break;
623                 case Keymap::TERTIARY:
624                         player_ctrl.StartTertiaryAction();
625                         break;
626
627                 case Keymap::INV_NEXT:
628                         InvRel(1);
629                         break;
630                 case Keymap::INV_PREVIOUS:
631                         InvRel(-1);
632                         break;
633                 case Keymap::INV_1:
634                 case Keymap::INV_2:
635                 case Keymap::INV_3:
636                 case Keymap::INV_4:
637                 case Keymap::INV_5:
638                 case Keymap::INV_6:
639                 case Keymap::INV_7:
640                 case Keymap::INV_8:
641                 case Keymap::INV_9:
642                 case Keymap::INV_10:
643                         InvAbs(action - Keymap::INV_1);
644                         break;
645
646                 case Keymap::EXIT:
647                         client_ctrl.Exit();
648                         break;
649
650                 case Keymap::TOGGLE_AUDIO:
651                         client_ctrl.SetAudio(!config.audio.enabled);
652                         break;
653                 case Keymap::TOGGLE_VIDEO:
654                         client_ctrl.SetVideo(!config.video.world);
655                         break;
656                 case Keymap::TOGGLE_HUD:
657                         client_ctrl.SetHUD(!config.video.hud);
658                         break;
659                 case Keymap::TOGGLE_DEBUG:
660                         client_ctrl.SetDebug(!config.video.debug);
661                         break;
662                 case Keymap::CAMERA_NEXT:
663                         client_ctrl.NextCamera();
664                         break;
665
666                 default:
667                         break;
668         }
669 }
670
671 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
672         if (!config.input.keyboard) return;
673
674         switch (keymap.Lookup(event)) {
675                 case Keymap::MOVE_FORWARD:
676                         rev.z = 0;
677                         UpdateMovement();
678                         break;
679                 case Keymap::MOVE_BACKWARD:
680                         fwd.z = 0;
681                         UpdateMovement();
682                         break;
683                 case Keymap::MOVE_LEFT:
684                         rev.x = 0;
685                         UpdateMovement();
686                         break;
687                 case Keymap::MOVE_RIGHT:
688                         fwd.x = 0;
689                         UpdateMovement();
690                         break;
691                 case Keymap::MOVE_UP:
692                         fwd.y = 0;
693                         UpdateMovement();
694                         break;
695                 case Keymap::MOVE_DOWN:
696                         rev.y = 0;
697                         UpdateMovement();
698                         break;
699
700                 case Keymap::PRIMARY:
701                         player_ctrl.StopPrimaryAction();
702                         break;
703                 case Keymap::SECONDARY:
704                         player_ctrl.StopSecondaryAction();
705                         break;
706                 case Keymap::TERTIARY:
707                         player_ctrl.StopTertiaryAction();
708                         break;
709
710                 default:
711                         break;
712         }
713 }
714
715 void Interface::Handle(const SDL_MouseMotionEvent &event) {
716         if (locked || !config.input.mouse) return;
717         player_ctrl.TurnHead(
718                 event.yrel * config.input.pitch_sensitivity,
719                 event.xrel * config.input.yaw_sensitivity);
720 }
721
722 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
723         if (!config.input.mouse) return;
724
725         switch (event.button) {
726                 case SDL_BUTTON_LEFT:
727                         player_ctrl.StartPrimaryAction();
728                         break;
729                 case SDL_BUTTON_RIGHT:
730                         player_ctrl.StartSecondaryAction();
731                         break;
732                 case SDL_BUTTON_MIDDLE:
733                         player_ctrl.StartTertiaryAction();
734                         break;
735         }
736 }
737
738 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
739         if (!config.input.mouse) return;
740
741         switch (event.button) {
742                 case SDL_BUTTON_LEFT:
743                         player_ctrl.StopPrimaryAction();
744                         break;
745                 case SDL_BUTTON_RIGHT:
746                         player_ctrl.StopSecondaryAction();
747                         break;
748                 case SDL_BUTTON_MIDDLE:
749                         player_ctrl.StopTertiaryAction();
750                         break;
751         }
752 }
753
754
755 void Interface::Handle(const SDL_MouseWheelEvent &event) {
756         if (!config.input.mouse) return;
757
758         if (event.y < 0) {
759                 InvRel(1);
760         } else if (event.y > 0) {
761                 InvRel(-1);
762         }
763 }
764
765 void Interface::UpdateMovement() {
766         player_ctrl.SetMovement(glm::vec3(fwd - rev));
767 }
768
769 void Interface::InvAbs(int s) {
770         int slot = s % num_slots;
771         while (slot < 0) {
772                 slot += num_slots;
773         }
774         player_ctrl.SelectInventory(slot);
775 }
776
777 void Interface::InvRel(int delta) {
778         InvAbs(player_ctrl.GetPlayer().GetInventorySlot() + delta);
779 }
780
781
782 Keymap::Keymap()
783 : codemap{ NONE } {
784
785 }
786
787 void Keymap::Map(SDL_Scancode scancode, Action action) {
788         if (scancode > MAX_SCANCODE) {
789                 throw std::runtime_error("refusing to map scancode: too damn high");
790         }
791         codemap[scancode] = action;
792 }
793
794 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
795         if (scancode < NUM_SCANCODES) {
796                 return codemap[scancode];
797         } else {
798                 return NONE;
799         }
800 }
801
802
803 void Keymap::LoadDefault() {
804         Map(SDL_SCANCODE_UP, MOVE_FORWARD);
805         Map(SDL_SCANCODE_W, MOVE_FORWARD);
806         Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
807         Map(SDL_SCANCODE_S, MOVE_BACKWARD);
808         Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
809         Map(SDL_SCANCODE_A, MOVE_LEFT);
810         Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
811         Map(SDL_SCANCODE_D, MOVE_RIGHT);
812         Map(SDL_SCANCODE_SPACE, MOVE_UP);
813         Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
814         Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
815         Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
816         Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
817
818         Map(SDL_SCANCODE_TAB, INV_NEXT);
819         Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
820         Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
821         Map(SDL_SCANCODE_1, INV_1);
822         Map(SDL_SCANCODE_2, INV_2);
823         Map(SDL_SCANCODE_3, INV_3);
824         Map(SDL_SCANCODE_4, INV_4);
825         Map(SDL_SCANCODE_5, INV_5);
826         Map(SDL_SCANCODE_6, INV_6);
827         Map(SDL_SCANCODE_7, INV_7);
828         Map(SDL_SCANCODE_8, INV_8);
829         Map(SDL_SCANCODE_9, INV_9);
830         Map(SDL_SCANCODE_0, INV_10);
831
832         Map(SDL_SCANCODE_INSERT, SECONDARY);
833         Map(SDL_SCANCODE_MENU, TERTIARY);
834         Map(SDL_SCANCODE_DELETE, PRIMARY);
835         Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
836
837         Map(SDL_SCANCODE_F1, TOGGLE_HUD);
838         Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
839         Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
840         Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
841         Map(SDL_SCANCODE_F5, CAMERA_NEXT);
842
843         Map(SDL_SCANCODE_ESCAPE, EXIT);
844 }
845
846
847 void Keymap::Load(std::istream &is) {
848         TokenStreamReader in(is);
849         std::string key_name;
850         std::string action_name;
851         SDL_Scancode key;
852         Action action;
853         while (in.HasMore()) {
854                 if (in.Peek().type == Token::STRING) {
855                         in.ReadString(key_name);
856                         key = SDL_GetScancodeFromName(key_name.c_str());
857                 } else {
858                         key = SDL_Scancode(in.GetInt());
859                 }
860                 in.Skip(Token::EQUALS);
861                 in.ReadIdentifier(action_name);
862                 action = StringToAction(action_name);
863                 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
864                         in.Skip(Token::SEMICOLON);
865                 }
866                 Map(key, action);
867         }
868 }
869
870 void Keymap::Save(std::ostream &out) {
871         for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
872                 if (codemap[i] == NONE) continue;
873
874                 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
875                 if (str && *str) {
876                         out << '"';
877                         while (*str) {
878                                 if (*str == '"') {
879                                         out << "\\\"";
880                                 } else {
881                                         out << *str;
882                                 }
883                                 ++str;
884                         }
885                         out << '"';
886                 } else {
887                         out << i;
888                 }
889
890                 out << " = " << ActionToString(codemap[i]) << std::endl;;
891         }
892 }
893
894
895 namespace {
896
897 std::map<std::string, Keymap::Action> action_map = {
898         { "none", Keymap::NONE },
899         { "move_forward", Keymap::MOVE_FORWARD },
900         { "move_backward", Keymap::MOVE_BACKWARD },
901         { "move_left", Keymap::MOVE_LEFT },
902         { "move_right", Keymap::MOVE_RIGHT },
903         { "move_up", Keymap::MOVE_UP },
904         { "move_down", Keymap::MOVE_DOWN },
905
906         { "primary", Keymap::PRIMARY },
907         { "secondary", Keymap::SECONDARY },
908         { "tertiary", Keymap::TERTIARY },
909
910         { "inventory_next", Keymap::INV_NEXT },
911         { "inventory_prev", Keymap::INV_PREVIOUS },
912         { "inventory_1", Keymap::INV_1 },
913         { "inventory_2", Keymap::INV_2 },
914         { "inventory_3", Keymap::INV_3 },
915         { "inventory_4", Keymap::INV_4 },
916         { "inventory_5", Keymap::INV_5 },
917         { "inventory_6", Keymap::INV_6 },
918         { "inventory_7", Keymap::INV_7 },
919         { "inventory_8", Keymap::INV_8 },
920         { "inventory_9", Keymap::INV_9 },
921         { "inventory_10", Keymap::INV_10 },
922
923         { "toggle_audio", Keymap::TOGGLE_AUDIO },
924         { "toggle_video", Keymap::TOGGLE_VIDEO },
925         { "toggle_hud", Keymap::TOGGLE_HUD },
926         { "toggle_debug", Keymap::TOGGLE_DEBUG },
927         { "camera_next", Keymap::CAMERA_NEXT },
928
929         { "exit", Keymap::EXIT },
930 };
931
932 }
933
934 const char *Keymap::ActionToString(Action action) {
935         for (const auto &entry : action_map) {
936                 if (action == entry.second) {
937                         return entry.first.c_str();
938                 }
939         }
940         return "none";
941 }
942
943 Keymap::Action Keymap::StringToAction(const std::string &str) {
944         auto entry = action_map.find(str);
945         if (entry != action_map.end()) {
946                 return entry->second;
947         } else {
948                 std::cerr << "unknown action \"" << str << '"' << std::endl;
949                 return NONE;
950         }
951 }
952
953 }