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 "../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"
31 #include <glm/gtc/matrix_transform.hpp>
32 #include <glm/gtx/rotate_vector.hpp>
33 #include <glm/gtx/io.hpp>
38 PlayerController::PlayerController(World &world, Player &player)
45 player.GetEntity().SetController(*this);
46 player.GetEntity().GetSteering().SetAcceleration(5.0f);
49 PlayerController::~PlayerController() {
50 if (&player.GetEntity().GetController() == this) {
51 player.GetEntity().UnsetController();
55 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
56 if (dot(m, m) > 1.0f) {
57 move_dir = normalize(m);
64 void PlayerController::TurnHead(float dp, float dy) noexcept {
65 player.GetEntity().TurnHead(dp, dy);
68 float PlayerController::GetPitch() const noexcept {
69 return player.GetEntity().Pitch();
72 float PlayerController::GetYaw() const noexcept {
73 return player.GetEntity().Yaw();
76 void PlayerController::SelectInventory(int i) noexcept {
77 player.SetInventorySlot(i);
80 int PlayerController::InventorySlot() const noexcept {
81 return player.GetInventorySlot();
84 void PlayerController::Invalidate() noexcept {
88 void PlayerController::UpdatePlayer() noexcept {
90 Ray aim = player.Aim();
91 Entity &entity = player.GetEntity();
92 if (!world.Intersection(aim, entity.ChunkCoords(), aim_world)) {
93 aim_world = WorldCollision();
95 if (!world.Intersection(aim, entity, aim_entity)) {
96 aim_entity = EntityCollision();
98 if (aim_world && aim_entity) {
99 // got both, pick the closest one
100 if (aim_world.depth < aim_entity.depth) {
101 // FIXME: somehow this can get stuck on an entity?
102 aim_entity = EntityCollision();
104 aim_world = WorldCollision();
107 Steering &steering = entity.GetSteering();
108 if (!iszero(move_dir)) {
109 // scale input by max velocity, apply yaw, and transform to world space
110 steering.SetTargetVelocity(glm::vec3(
111 glm::vec4(rotateY(move_dir * entity.MaxVelocity(), entity.Yaw()), 0.0f)
112 * transpose(entity.Transform())
114 steering.Enable(Steering::TARGET_VELOCITY);
115 steering.Disable(Steering::HALT);
117 // target velocity of 0 is the same as halt
118 steering.Enable(Steering::HALT);
119 steering.Disable(Steering::TARGET_VELOCITY);
126 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
127 : PlayerController(world, player)
130 , remove_timer(0.25f) {
134 void DirectInput::Update(Entity &, float dt) {
135 Invalidate(); // world has changed in the meantime
138 remove_timer.Update(dt);
139 if (remove_timer.Hit()) {
143 place_timer.Update(dt);
144 if (place_timer.Hit()) {
149 void DirectInput::StartPrimaryAction() {
150 if (!remove_timer.Running()) {
152 remove_timer.Start();
156 void DirectInput::StopPrimaryAction() {
160 void DirectInput::StartSecondaryAction() {
161 if (!place_timer.Running()) {
167 void DirectInput::StopSecondaryAction() {
171 void DirectInput::StartTertiaryAction() {
175 void DirectInput::StopTertiaryAction() {
179 void DirectInput::PickBlock() {
181 if (!BlockFocus()) return;
182 SelectInventory(BlockFocus().GetBlock().type - 1);
185 void DirectInput::PlaceBlock() {
187 if (!BlockFocus()) return;
189 BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
193 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
197 void DirectInput::RemoveBlock() {
199 if (!BlockFocus()) return;
200 manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
205 HUD::HUD(Environment &env, Config &config, const Player &player)
211 , outline_transform(1.0f)
212 , outline_visible(false)
216 , block_transform(1.0f)
218 , block_visible(false)
232 , messages(env.assets.small_ui_font)
237 const float ls = env.assets.small_ui_font.LineSkip();
240 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
241 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
242 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
243 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
244 block_label.Position(
245 glm::vec3(50.0f, 85.0f, 0.0f),
249 block_label.Foreground(glm::vec4(1.0f));
250 block_label.Background(glm::vec4(0.5f));
253 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
254 counter_text.Foreground(glm::vec4(1.0f));
255 counter_text.Background(glm::vec4(0.5f));
256 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
257 position_text.Foreground(glm::vec4(1.0f));
258 position_text.Background(glm::vec4(0.5f));
259 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
260 orientation_text.Foreground(glm::vec4(1.0f));
261 orientation_text.Background(glm::vec4(0.5f));
262 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
263 block_text.Foreground(glm::vec4(1.0f));
264 block_text.Background(glm::vec4(0.5f));
265 block_text.Set(env.assets.small_ui_font, "Block: none");
266 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
267 entity_text.Foreground(glm::vec4(1.0f));
268 entity_text.Background(glm::vec4(0.5f));
269 entity_text.Set(env.assets.small_ui_font, "Entity: none");
272 bandwidth_text.Position(glm::vec3(-25.0f, 25.0f + 6 * ls, 0.0f), Gravity::NORTH_EAST);
273 bandwidth_text.Foreground(glm::vec4(1.0f));
274 bandwidth_text.Background(glm::vec4(0.5f));
275 bandwidth_text.Set(env.assets.small_ui_font, "TX: 0.0KB/s RX: 0.0KB/s");
276 rtt_text.Position(glm::vec3(-25.0f, 25.0f + 7 * ls, 0.0f), Gravity::NORTH_EAST);
277 rtt_text.Foreground(glm::vec4(1.0f));
278 rtt_text.Background(glm::vec4(0.5f));
279 rtt_text.Set(env.assets.small_ui_font, "RTT: unavailable");
280 packet_loss_text.Position(glm::vec3(-25.0f, 25.0f + 8 * ls, 0.0f), Gravity::NORTH_EAST);
281 packet_loss_text.Foreground(glm::vec4(1.0f));
282 packet_loss_text.Background(glm::vec4(0.5f));
283 packet_loss_text.Set(env.assets.small_ui_font, "Packet loss: 0.0%");
286 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
287 messages.Foreground(glm::vec4(1.0f));
288 messages.Background(glm::vec4(0.5f));
291 PrimitiveMesh::Buffer buf;
292 buf.vertices = std::vector<glm::vec3>({
293 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
294 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
296 buf.indices = std::vector<PrimitiveMesh::Index>({
299 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
300 crosshair.Update(buf);
305 PrimitiveMesh::Buffer outl_buf;
309 void HUD::FocusBlock(const Chunk &chunk, int index) {
310 const Block &block = chunk.BlockAt(index);
311 const BlockType &type = chunk.Type(index);
313 type.OutlinePrimitiveMesh(outl_buf);
314 outline.Update(outl_buf);
315 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
316 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
317 outline_transform *= glm::scale(glm::vec3(1.005f));
318 outline_visible = true;
323 << ", face: " << block.GetFace()
324 << ", turn: " << block.GetTurn();
325 block_text.Set(env.assets.small_ui_font, s.str());
331 void HUD::FocusEntity(const Entity &entity) {
334 s << "Entity: " << entity.Name();
335 entity_text.Set(env.assets.small_ui_font, s.str());
341 void HUD::FocusNone() {
342 outline_visible = false;
347 void HUD::DisplayNone() {
348 block_visible = false;
351 void HUD::Display(const BlockType &type) {
353 type.FillEntityMesh(block_buf);
354 block.Update(block_buf);
356 block_label.Set(env.assets.small_ui_font, type.label);
358 block_visible = type.visible;
362 void HUD::UpdateDebug() {
368 void HUD::UpdateCounter() {
370 s << std::setprecision(3) <<
371 "avg: " << env.counter.Average().running << "ms, "
372 "peak: " << env.counter.Peak().running << "ms";
373 std::string text = s.str();
374 counter_text.Set(env.assets.small_ui_font, text);
377 void HUD::UpdatePosition() {
379 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
380 position_text.Set(env.assets.small_ui_font, s.str());
383 void HUD::UpdateOrientation() {
385 s << std::setprecision(3) << "pitch: " << glm::degrees(player.GetEntity().Pitch())
386 << ", yaw: " << glm::degrees(player.GetEntity().Yaw());
387 orientation_text.Set(env.assets.small_ui_font, s.str());
390 void HUD::PostMessage(const char *msg) {
391 messages.PushLine(msg);
394 std::cout << msg << std::endl;
398 void HUD::UpdateNetStats(const CongestionControl &stat) {
399 if (!config.video.debug) return;
402 s << std::fixed << std::setprecision(1)
403 << "TX: " << stat.Upstream()
404 << "KB/s, RX: " << stat.Downstream() << "KB/s";
405 bandwidth_text.Set(env.assets.small_ui_font, s.str());
408 s << "RTT: " << stat.RoundTripTime() << "ms";
409 rtt_text.Set(env.assets.small_ui_font, s.str());
412 s << "Packet loss: " << (stat.PacketLoss() * 100.0f) << "%";
413 packet_loss_text.Set(env.assets.small_ui_font, s.str());
419 void HUD::Update(int dt) {
420 msg_timer.Update(dt);
421 if (msg_timer.HitOnce()) {
425 if (config.video.debug) {
426 if (env.counter.Changed()) {
434 void HUD::Render(Viewport &viewport) noexcept {
436 if (outline_visible && config.video.world) {
437 PlainColor &outline_prog = viewport.WorldColorProgram();
438 outline_prog.SetM(outline_transform);
442 // clear depth buffer so everything renders above the world
443 viewport.ClearDepth();
445 if (config.video.hud) {
448 DirectionalLighting &world_prog = viewport.HUDProgram();
449 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
450 world_prog.SetLightColor({ 1.0f, 1.0f, 1.0f });
451 world_prog.SetAmbientColor({ 0.1f, 0.1f, 0.1f });
452 // disable distance fog
453 world_prog.SetFogDensity(0.0f);
455 viewport.DisableBlending();
456 world_prog.SetM(block_transform);
458 block_label.Render(viewport);
462 if (msg_keep || msg_timer.Running()) {
463 messages.Render(viewport);
467 PlainColor &outline_prog = viewport.HUDColorProgram();
468 viewport.EnableInvertBlending();
469 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
470 outline_prog.SetM(viewport.Cursor());
471 crosshair.DrawLines();
475 if (config.video.debug) {
476 counter_text.Render(viewport);
477 position_text.Render(viewport);
478 orientation_text.Render(viewport);
480 block_text.Render(viewport);
481 } else if (show_entity) {
482 entity_text.Render(viewport);
485 bandwidth_text.Render(viewport);
486 rtt_text.Render(viewport);
487 packet_loss_text.Render(viewport);
493 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
500 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
501 const BlockType &old_type = chunk.Type(index);
502 chunk.SetBlock(index, block);
503 const BlockType &new_type = chunk.Type(index);
504 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
505 if (new_type.id == 0) {
506 if (old_type.remove_sound >= 0) {
507 audio.Play(sounds[old_type.remove_sound], coords);
510 if (new_type.place_sound >= 0) {
511 audio.Play(sounds[new_type.place_sound], coords);
517 Interface::Interface(
519 const Keymap &keymap,
520 PlayerController &pc,
521 ClientController &cc)
533 void Interface::Lock() {
539 void Interface::Unlock() {
543 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
544 if (!config.input.keyboard) return;
546 Keymap::Action action = keymap.Lookup(event);
548 case Keymap::MOVE_FORWARD:
552 case Keymap::MOVE_BACKWARD:
556 case Keymap::MOVE_LEFT:
560 case Keymap::MOVE_RIGHT:
564 case Keymap::MOVE_UP:
568 case Keymap::MOVE_DOWN:
573 case Keymap::PRIMARY:
574 player_ctrl.StartPrimaryAction();
576 case Keymap::SECONDARY:
577 player_ctrl.StartSecondaryAction();
579 case Keymap::TERTIARY:
580 player_ctrl.StartTertiaryAction();
583 case Keymap::INV_NEXT:
586 case Keymap::INV_PREVIOUS:
599 InvAbs(action - Keymap::INV_1);
606 case Keymap::TOGGLE_AUDIO:
607 client_ctrl.SetAudio(!config.audio.enabled);
609 case Keymap::TOGGLE_VIDEO:
610 client_ctrl.SetVideo(!config.video.world);
612 case Keymap::TOGGLE_HUD:
613 client_ctrl.SetHUD(!config.video.hud);
615 case Keymap::TOGGLE_DEBUG:
616 client_ctrl.SetDebug(!config.video.debug);
618 case Keymap::CAMERA_NEXT:
619 client_ctrl.NextCamera();
627 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
628 if (!config.input.keyboard) return;
630 switch (keymap.Lookup(event)) {
631 case Keymap::MOVE_FORWARD:
635 case Keymap::MOVE_BACKWARD:
639 case Keymap::MOVE_LEFT:
643 case Keymap::MOVE_RIGHT:
647 case Keymap::MOVE_UP:
651 case Keymap::MOVE_DOWN:
656 case Keymap::PRIMARY:
657 player_ctrl.StopPrimaryAction();
659 case Keymap::SECONDARY:
660 player_ctrl.StopSecondaryAction();
662 case Keymap::TERTIARY:
663 player_ctrl.StopTertiaryAction();
671 void Interface::Handle(const SDL_MouseMotionEvent &event) {
672 if (locked || !config.input.mouse) return;
673 player_ctrl.TurnHead(
674 event.yrel * config.input.pitch_sensitivity,
675 event.xrel * config.input.yaw_sensitivity);
678 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
679 if (!config.input.mouse) return;
681 switch (event.button) {
682 case SDL_BUTTON_LEFT:
683 player_ctrl.StartPrimaryAction();
685 case SDL_BUTTON_RIGHT:
686 player_ctrl.StartSecondaryAction();
688 case SDL_BUTTON_MIDDLE:
689 player_ctrl.StartTertiaryAction();
694 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
695 if (!config.input.mouse) return;
697 switch (event.button) {
698 case SDL_BUTTON_LEFT:
699 player_ctrl.StopPrimaryAction();
701 case SDL_BUTTON_RIGHT:
702 player_ctrl.StopSecondaryAction();
704 case SDL_BUTTON_MIDDLE:
705 player_ctrl.StopTertiaryAction();
711 void Interface::Handle(const SDL_MouseWheelEvent &event) {
712 if (!config.input.mouse) return;
716 } else if (event.y > 0) {
721 void Interface::UpdateMovement() {
722 player_ctrl.SetMovement(glm::vec3(fwd - rev));
725 void Interface::InvAbs(int s) {
726 int slot = s % num_slots;
730 player_ctrl.SelectInventory(slot);
733 void Interface::InvRel(int delta) {
734 InvAbs(player_ctrl.GetPlayer().GetInventorySlot() + delta);
743 void Keymap::Map(SDL_Scancode scancode, Action action) {
744 if (scancode > MAX_SCANCODE) {
745 throw std::runtime_error("refusing to map scancode: too damn high");
747 codemap[scancode] = action;
750 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
751 if (scancode < NUM_SCANCODES) {
752 return codemap[scancode];
759 void Keymap::LoadDefault() {
760 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
761 Map(SDL_SCANCODE_W, MOVE_FORWARD);
762 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
763 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
764 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
765 Map(SDL_SCANCODE_A, MOVE_LEFT);
766 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
767 Map(SDL_SCANCODE_D, MOVE_RIGHT);
768 Map(SDL_SCANCODE_SPACE, MOVE_UP);
769 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
770 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
771 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
772 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
774 Map(SDL_SCANCODE_TAB, INV_NEXT);
775 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
776 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
777 Map(SDL_SCANCODE_1, INV_1);
778 Map(SDL_SCANCODE_2, INV_2);
779 Map(SDL_SCANCODE_3, INV_3);
780 Map(SDL_SCANCODE_4, INV_4);
781 Map(SDL_SCANCODE_5, INV_5);
782 Map(SDL_SCANCODE_6, INV_6);
783 Map(SDL_SCANCODE_7, INV_7);
784 Map(SDL_SCANCODE_8, INV_8);
785 Map(SDL_SCANCODE_9, INV_9);
786 Map(SDL_SCANCODE_0, INV_10);
788 Map(SDL_SCANCODE_INSERT, SECONDARY);
789 Map(SDL_SCANCODE_MENU, TERTIARY);
790 Map(SDL_SCANCODE_DELETE, PRIMARY);
791 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
793 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
794 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
795 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
796 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
797 Map(SDL_SCANCODE_F5, CAMERA_NEXT);
799 Map(SDL_SCANCODE_ESCAPE, EXIT);
803 void Keymap::Load(std::istream &is) {
804 TokenStreamReader in(is);
805 std::string key_name;
806 std::string action_name;
809 while (in.HasMore()) {
810 if (in.Peek().type == Token::STRING) {
811 in.ReadString(key_name);
812 key = SDL_GetScancodeFromName(key_name.c_str());
814 key = SDL_Scancode(in.GetInt());
816 in.Skip(Token::EQUALS);
817 in.ReadIdentifier(action_name);
818 action = StringToAction(action_name);
819 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
820 in.Skip(Token::SEMICOLON);
826 void Keymap::Save(std::ostream &out) {
827 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
828 if (codemap[i] == NONE) continue;
830 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
846 out << " = " << ActionToString(codemap[i]) << std::endl;;
853 std::map<std::string, Keymap::Action> action_map = {
854 { "none", Keymap::NONE },
855 { "move_forward", Keymap::MOVE_FORWARD },
856 { "move_backward", Keymap::MOVE_BACKWARD },
857 { "move_left", Keymap::MOVE_LEFT },
858 { "move_right", Keymap::MOVE_RIGHT },
859 { "move_up", Keymap::MOVE_UP },
860 { "move_down", Keymap::MOVE_DOWN },
862 { "primary", Keymap::PRIMARY },
863 { "secondary", Keymap::SECONDARY },
864 { "tertiary", Keymap::TERTIARY },
866 { "inventory_next", Keymap::INV_NEXT },
867 { "inventory_prev", Keymap::INV_PREVIOUS },
868 { "inventory_1", Keymap::INV_1 },
869 { "inventory_2", Keymap::INV_2 },
870 { "inventory_3", Keymap::INV_3 },
871 { "inventory_4", Keymap::INV_4 },
872 { "inventory_5", Keymap::INV_5 },
873 { "inventory_6", Keymap::INV_6 },
874 { "inventory_7", Keymap::INV_7 },
875 { "inventory_8", Keymap::INV_8 },
876 { "inventory_9", Keymap::INV_9 },
877 { "inventory_10", Keymap::INV_10 },
879 { "toggle_audio", Keymap::TOGGLE_AUDIO },
880 { "toggle_video", Keymap::TOGGLE_VIDEO },
881 { "toggle_hud", Keymap::TOGGLE_HUD },
882 { "toggle_debug", Keymap::TOGGLE_DEBUG },
883 { "camera_next", Keymap::CAMERA_NEXT },
885 { "exit", Keymap::EXIT },
890 const char *Keymap::ActionToString(Action action) {
891 for (const auto &entry : action_map) {
892 if (action == entry.second) {
893 return entry.first.c_str();
899 Keymap::Action Keymap::StringToAction(const std::string &str) {
900 auto entry = action_map.find(str);
901 if (entry != action_map.end()) {
902 return entry->second;
904 std::cerr << "unknown action \"" << str << '"' << std::endl;