1 #include "ClientController.hpp"
2 #include "DirectInput.hpp"
4 #include "InteractiveManipulator.hpp"
5 #include "Interface.hpp"
7 #include "PlayerController.hpp"
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 "../net/CongestionControl.hpp"
21 #include "../world/BlockLookup.hpp"
22 #include "../world/World.hpp"
23 #include "../world/WorldManipulator.hpp"
30 #include <glm/gtc/matrix_transform.hpp>
31 #include <glm/gtx/rotate_vector.hpp>
32 #include <glm/gtx/io.hpp>
37 PlayerController::PlayerController(World &world, Player &player)
44 player.GetEntity().SetController(*this);
47 PlayerController::~PlayerController() {
48 if (&player.GetEntity().GetController() == this) {
49 player.GetEntity().UnsetController();
53 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
54 if (dot(m, m) > 1.0f) {
55 move_dir = normalize(m);
62 glm::vec3 PlayerController::ControlForce(const Entity &e, const EntityState &s) const {
63 return TargetVelocity(rotateY(move_dir * e.MaxVelocity(), s.yaw), s, 5.0f);
66 void PlayerController::TurnHead(float dp, float dy) noexcept {
67 player.GetEntity().TurnHead(dp, dy);
70 float PlayerController::GetPitch() const noexcept {
71 return player.GetEntity().Pitch();
74 float PlayerController::GetYaw() const noexcept {
75 return player.GetEntity().Yaw();
78 void PlayerController::SelectInventory(int i) noexcept {
79 player.SetInventorySlot(i);
82 int PlayerController::InventorySlot() const noexcept {
83 return player.GetInventorySlot();
86 void PlayerController::Invalidate() noexcept {
90 void PlayerController::UpdatePlayer() noexcept {
92 Ray aim = player.Aim();
93 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity().ChunkCoords(), aim_world)) {
94 aim_world = WorldCollision();
96 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity(), aim_entity)) {
97 aim_entity = EntityCollision();
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();
104 aim_world = WorldCollision();
112 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
113 : PlayerController(world, player)
116 , remove_timer(0.25f) {
120 void DirectInput::Update(Entity &, float dt) {
121 Invalidate(); // world has changed in the meantime
124 remove_timer.Update(dt);
125 if (remove_timer.Hit()) {
129 place_timer.Update(dt);
130 if (place_timer.Hit()) {
135 void DirectInput::StartPrimaryAction() {
136 if (!remove_timer.Running()) {
138 remove_timer.Start();
142 void DirectInput::StopPrimaryAction() {
146 void DirectInput::StartSecondaryAction() {
147 if (!place_timer.Running()) {
153 void DirectInput::StopSecondaryAction() {
157 void DirectInput::StartTertiaryAction() {
161 void DirectInput::StopTertiaryAction() {
165 void DirectInput::PickBlock() {
167 if (!BlockFocus()) return;
168 SelectInventory(BlockFocus().GetBlock().type - 1);
171 void DirectInput::PlaceBlock() {
173 if (!BlockFocus()) return;
175 BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
179 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
183 void DirectInput::RemoveBlock() {
185 if (!BlockFocus()) return;
186 manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
191 HUD::HUD(Environment &env, Config &config, const Player &player)
197 , outline_transform(1.0f)
198 , outline_visible(false)
202 , block_transform(1.0f)
204 , block_visible(false)
218 , messages(env.assets.small_ui_font)
223 const float ls = env.assets.small_ui_font.LineSkip();
226 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
227 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
228 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
229 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
230 block_label.Position(
231 glm::vec3(50.0f, 85.0f, 0.0f),
235 block_label.Foreground(glm::vec4(1.0f));
236 block_label.Background(glm::vec4(0.5f));
239 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
240 counter_text.Foreground(glm::vec4(1.0f));
241 counter_text.Background(glm::vec4(0.5f));
242 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
243 position_text.Foreground(glm::vec4(1.0f));
244 position_text.Background(glm::vec4(0.5f));
245 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
246 orientation_text.Foreground(glm::vec4(1.0f));
247 orientation_text.Background(glm::vec4(0.5f));
248 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
249 block_text.Foreground(glm::vec4(1.0f));
250 block_text.Background(glm::vec4(0.5f));
251 block_text.Set(env.assets.small_ui_font, "Block: none");
252 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
253 entity_text.Foreground(glm::vec4(1.0f));
254 entity_text.Background(glm::vec4(0.5f));
255 entity_text.Set(env.assets.small_ui_font, "Entity: none");
258 bandwidth_text.Position(glm::vec3(-25.0f, 25.0f + 6 * ls, 0.0f), Gravity::NORTH_EAST);
259 bandwidth_text.Foreground(glm::vec4(1.0f));
260 bandwidth_text.Background(glm::vec4(0.5f));
261 bandwidth_text.Set(env.assets.small_ui_font, "TX: 0.0KB/s RX: 0.0KB/s");
262 rtt_text.Position(glm::vec3(-25.0f, 25.0f + 7 * ls, 0.0f), Gravity::NORTH_EAST);
263 rtt_text.Foreground(glm::vec4(1.0f));
264 rtt_text.Background(glm::vec4(0.5f));
265 rtt_text.Set(env.assets.small_ui_font, "RTT: unavailable");
266 packet_loss_text.Position(glm::vec3(-25.0f, 25.0f + 8 * ls, 0.0f), Gravity::NORTH_EAST);
267 packet_loss_text.Foreground(glm::vec4(1.0f));
268 packet_loss_text.Background(glm::vec4(0.5f));
269 packet_loss_text.Set(env.assets.small_ui_font, "Packet loss: 0.0%");
272 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
273 messages.Foreground(glm::vec4(1.0f));
274 messages.Background(glm::vec4(0.5f));
277 PrimitiveMesh::Buffer buf;
278 buf.vertices = std::vector<glm::vec3>({
279 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
280 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
282 buf.indices = std::vector<PrimitiveMesh::Index>({
285 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
286 crosshair.Update(buf);
291 PrimitiveMesh::Buffer outl_buf;
295 void HUD::FocusBlock(const Chunk &chunk, int index) {
296 const Block &block = chunk.BlockAt(index);
297 const BlockType &type = chunk.Type(index);
299 type.OutlinePrimitiveMesh(outl_buf);
300 outline.Update(outl_buf);
301 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
302 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
303 outline_transform *= glm::scale(glm::vec3(1.005f));
304 outline_visible = true;
309 << ", face: " << block.GetFace()
310 << ", turn: " << block.GetTurn();
311 block_text.Set(env.assets.small_ui_font, s.str());
317 void HUD::FocusEntity(const Entity &entity) {
320 s << "Entity: " << entity.Name();
321 entity_text.Set(env.assets.small_ui_font, s.str());
327 void HUD::FocusNone() {
328 outline_visible = false;
333 void HUD::DisplayNone() {
334 block_visible = false;
337 void HUD::Display(const BlockType &type) {
339 type.FillEntityMesh(block_buf);
340 block.Update(block_buf);
342 block_label.Set(env.assets.small_ui_font, type.label);
344 block_visible = type.visible;
348 void HUD::UpdateDebug() {
354 void HUD::UpdateCounter() {
356 s << std::setprecision(3) <<
357 "avg: " << env.counter.Average().running << "ms, "
358 "peak: " << env.counter.Peak().running << "ms";
359 std::string text = s.str();
360 counter_text.Set(env.assets.small_ui_font, text);
363 void HUD::UpdatePosition() {
365 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
366 position_text.Set(env.assets.small_ui_font, s.str());
369 void HUD::UpdateOrientation() {
371 s << std::setprecision(3) << "pitch: " << rad2deg(player.GetEntity().Pitch())
372 << ", yaw: " << rad2deg(player.GetEntity().Yaw());
373 orientation_text.Set(env.assets.small_ui_font, s.str());
376 void HUD::PostMessage(const char *msg) {
377 messages.PushLine(msg);
380 std::cout << msg << std::endl;
384 void HUD::UpdateNetStats(const CongestionControl &stat) {
385 if (!config.video.debug) return;
388 s << std::fixed << std::setprecision(1)
389 << "TX: " << stat.Upstream()
390 << "KB/s, RX: " << stat.Downstream() << "KB/s";
391 bandwidth_text.Set(env.assets.small_ui_font, s.str());
394 s << "RTT: " << stat.RoundTripTime() << "ms";
395 rtt_text.Set(env.assets.small_ui_font, s.str());
398 s << "Packet loss: " << (stat.PacketLoss() * 100.0f) << "%";
399 packet_loss_text.Set(env.assets.small_ui_font, s.str());
405 void HUD::Update(int dt) {
406 msg_timer.Update(dt);
407 if (msg_timer.HitOnce()) {
411 if (config.video.debug) {
412 if (env.counter.Changed()) {
420 void HUD::Render(Viewport &viewport) noexcept {
422 if (outline_visible && config.video.world) {
423 PlainColor &outline_prog = viewport.WorldColorProgram();
424 outline_prog.SetM(outline_transform);
428 // clear depth buffer so everything renders above the world
429 viewport.ClearDepth();
431 if (config.video.hud) {
434 DirectionalLighting &world_prog = viewport.HUDProgram();
435 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
436 world_prog.SetLightColor({ 1.0f, 1.0f, 1.0f });
437 world_prog.SetAmbientColor({ 0.1f, 0.1f, 0.1f });
438 // disable distance fog
439 world_prog.SetFogDensity(0.0f);
441 viewport.DisableBlending();
442 world_prog.SetM(block_transform);
444 block_label.Render(viewport);
448 if (msg_keep || msg_timer.Running()) {
449 messages.Render(viewport);
453 PlainColor &outline_prog = viewport.HUDColorProgram();
454 viewport.EnableInvertBlending();
455 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
456 outline_prog.SetM(viewport.Cursor());
457 crosshair.DrawLines();
461 if (config.video.debug) {
462 counter_text.Render(viewport);
463 position_text.Render(viewport);
464 orientation_text.Render(viewport);
466 block_text.Render(viewport);
467 } else if (show_entity) {
468 entity_text.Render(viewport);
471 bandwidth_text.Render(viewport);
472 rtt_text.Render(viewport);
473 packet_loss_text.Render(viewport);
479 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
486 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
487 const BlockType &old_type = chunk.Type(index);
488 chunk.SetBlock(index, block);
489 const BlockType &new_type = chunk.Type(index);
490 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
491 if (new_type.id == 0) {
492 if (old_type.remove_sound >= 0) {
493 audio.Play(sounds[old_type.remove_sound], coords);
496 if (new_type.place_sound >= 0) {
497 audio.Play(sounds[new_type.place_sound], coords);
503 Interface::Interface(
505 const Keymap &keymap,
506 PlayerController &pc,
507 ClientController &cc)
520 void Interface::Lock() {
526 void Interface::Unlock() {
530 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
531 if (!config.input.keyboard) return;
533 Keymap::Action action = keymap.Lookup(event);
535 case Keymap::MOVE_FORWARD:
539 case Keymap::MOVE_BACKWARD:
543 case Keymap::MOVE_LEFT:
547 case Keymap::MOVE_RIGHT:
551 case Keymap::MOVE_UP:
555 case Keymap::MOVE_DOWN:
560 case Keymap::PRIMARY:
561 player_ctrl.StartPrimaryAction();
563 case Keymap::SECONDARY:
564 player_ctrl.StartSecondaryAction();
566 case Keymap::TERTIARY:
567 player_ctrl.StartTertiaryAction();
570 case Keymap::INV_NEXT:
573 case Keymap::INV_PREVIOUS:
586 InvAbs(action - Keymap::INV_1);
593 case Keymap::TOGGLE_AUDIO:
594 config.audio.enabled = !config.audio.enabled;
595 client_ctrl.SetAudio(config.audio.enabled);
597 case Keymap::TOGGLE_VIDEO:
598 config.video.world = !config.video.world;
599 client_ctrl.SetVideo(config.video.world);
601 case Keymap::TOGGLE_HUD:
602 config.video.hud = !config.video.hud;
603 client_ctrl.SetHUD(config.video.hud);
605 case Keymap::TOGGLE_DEBUG:
606 config.video.debug = !config.video.debug;
607 client_ctrl.SetDebug(config.video.debug);
615 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
616 if (!config.input.keyboard) return;
618 switch (keymap.Lookup(event)) {
619 case Keymap::MOVE_FORWARD:
623 case Keymap::MOVE_BACKWARD:
627 case Keymap::MOVE_LEFT:
631 case Keymap::MOVE_RIGHT:
635 case Keymap::MOVE_UP:
639 case Keymap::MOVE_DOWN:
644 case Keymap::PRIMARY:
645 player_ctrl.StopPrimaryAction();
647 case Keymap::SECONDARY:
648 player_ctrl.StopSecondaryAction();
650 case Keymap::TERTIARY:
651 player_ctrl.StopTertiaryAction();
659 void Interface::Handle(const SDL_MouseMotionEvent &event) {
660 if (locked || !config.input.mouse) return;
661 player_ctrl.TurnHead(
662 event.yrel * config.input.pitch_sensitivity,
663 event.xrel * config.input.yaw_sensitivity);
666 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
667 if (!config.input.mouse) return;
669 switch (event.button) {
670 case SDL_BUTTON_LEFT:
671 player_ctrl.StartPrimaryAction();
673 case SDL_BUTTON_RIGHT:
674 player_ctrl.StartSecondaryAction();
676 case SDL_BUTTON_MIDDLE:
677 player_ctrl.StartTertiaryAction();
682 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
683 if (!config.input.mouse) return;
685 switch (event.button) {
686 case SDL_BUTTON_LEFT:
687 player_ctrl.StopPrimaryAction();
689 case SDL_BUTTON_RIGHT:
690 player_ctrl.StopSecondaryAction();
692 case SDL_BUTTON_MIDDLE:
693 player_ctrl.StopTertiaryAction();
699 void Interface::Handle(const SDL_MouseWheelEvent &event) {
700 if (!config.input.mouse) return;
704 } else if (event.y > 0) {
709 void Interface::UpdateMovement() {
710 player_ctrl.SetMovement(glm::vec3(fwd - rev));
713 void Interface::InvAbs(int s) {
714 slot = s % num_slots;
718 player_ctrl.SelectInventory(slot);
721 void Interface::InvRel(int delta) {
722 InvAbs(slot + delta);
731 void Keymap::Map(SDL_Scancode scancode, Action action) {
732 if (scancode > MAX_SCANCODE) {
733 throw std::runtime_error("refusing to map scancode: too damn high");
735 codemap[scancode] = action;
738 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
739 if (scancode < NUM_SCANCODES) {
740 return codemap[scancode];
747 void Keymap::LoadDefault() {
748 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
749 Map(SDL_SCANCODE_W, MOVE_FORWARD);
750 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
751 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
752 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
753 Map(SDL_SCANCODE_A, MOVE_LEFT);
754 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
755 Map(SDL_SCANCODE_D, MOVE_RIGHT);
756 Map(SDL_SCANCODE_SPACE, MOVE_UP);
757 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
758 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
759 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
760 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
762 Map(SDL_SCANCODE_TAB, INV_NEXT);
763 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
764 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
765 Map(SDL_SCANCODE_1, INV_1);
766 Map(SDL_SCANCODE_2, INV_2);
767 Map(SDL_SCANCODE_3, INV_3);
768 Map(SDL_SCANCODE_4, INV_4);
769 Map(SDL_SCANCODE_5, INV_5);
770 Map(SDL_SCANCODE_6, INV_6);
771 Map(SDL_SCANCODE_7, INV_7);
772 Map(SDL_SCANCODE_8, INV_8);
773 Map(SDL_SCANCODE_9, INV_9);
774 Map(SDL_SCANCODE_0, INV_10);
776 Map(SDL_SCANCODE_INSERT, SECONDARY);
777 Map(SDL_SCANCODE_RETURN, SECONDARY);
778 Map(SDL_SCANCODE_MENU, TERTIARY);
779 Map(SDL_SCANCODE_DELETE, PRIMARY);
780 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
782 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
783 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
784 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
785 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
787 Map(SDL_SCANCODE_ESCAPE, EXIT);
791 void Keymap::Load(std::istream &is) {
792 TokenStreamReader in(is);
793 std::string key_name;
794 std::string action_name;
797 while (in.HasMore()) {
798 if (in.Peek().type == Token::STRING) {
799 in.ReadString(key_name);
800 key = SDL_GetScancodeFromName(key_name.c_str());
802 key = SDL_Scancode(in.GetInt());
804 in.Skip(Token::EQUALS);
805 in.ReadIdentifier(action_name);
806 action = StringToAction(action_name);
807 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
808 in.Skip(Token::SEMICOLON);
814 void Keymap::Save(std::ostream &out) {
815 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
816 if (codemap[i] == NONE) continue;
818 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
834 out << " = " << ActionToString(codemap[i]) << std::endl;;
841 std::map<std::string, Keymap::Action> action_map = {
842 { "none", Keymap::NONE },
843 { "move_forward", Keymap::MOVE_FORWARD },
844 { "move_backward", Keymap::MOVE_BACKWARD },
845 { "move_left", Keymap::MOVE_LEFT },
846 { "move_right", Keymap::MOVE_RIGHT },
847 { "move_up", Keymap::MOVE_UP },
848 { "move_down", Keymap::MOVE_DOWN },
850 { "primary", Keymap::PRIMARY },
851 { "secondary", Keymap::SECONDARY },
852 { "tertiary", Keymap::TERTIARY },
854 { "inventory_next", Keymap::INV_NEXT },
855 { "inventory_prev", Keymap::INV_PREVIOUS },
856 { "inventory_1", Keymap::INV_1 },
857 { "inventory_2", Keymap::INV_2 },
858 { "inventory_3", Keymap::INV_3 },
859 { "inventory_4", Keymap::INV_4 },
860 { "inventory_5", Keymap::INV_5 },
861 { "inventory_6", Keymap::INV_6 },
862 { "inventory_7", Keymap::INV_7 },
863 { "inventory_8", Keymap::INV_8 },
864 { "inventory_9", Keymap::INV_9 },
865 { "inventory_10", Keymap::INV_10 },
867 { "toggle_audio", Keymap::TOGGLE_AUDIO },
868 { "toggle_video", Keymap::TOGGLE_VIDEO },
869 { "toggle_hud", Keymap::TOGGLE_HUD },
870 { "toggle_debug", Keymap::TOGGLE_DEBUG },
872 { "exit", Keymap::EXIT },
877 const char *Keymap::ActionToString(Action action) {
878 for (const auto &entry : action_map) {
879 if (action == entry.second) {
880 return entry.first.c_str();
886 Keymap::Action Keymap::StringToAction(const std::string &str) {
887 auto entry = action_map.find(str);
888 if (entry != action_map.end()) {
889 return entry->second;
891 std::cerr << "unknown action \"" << str << '"' << std::endl;