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