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