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