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