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