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);
48 PlayerController::~PlayerController() {
49 if (&player.GetEntity().GetController() == this) {
50 player.GetEntity().UnsetController();
54 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
55 if (dot(m, m) > 1.0f) {
56 move_dir = normalize(m);
63 glm::vec3 PlayerController::ControlForce(const Entity &e, const EntityState &s) const {
64 if (!iszero(move_dir)) {
65 // scale input by max velocity, apply yaw, and transform to world space
66 return TargetVelocity(glm::vec3(glm::vec4(rotateY(move_dir * e.MaxVelocity(), s.yaw), 0.0f) * transpose(e.Transform())), s, 5.0f);
68 // target velocity of 0 is the same as halt
73 void PlayerController::TurnHead(float dp, float dy) noexcept {
74 player.GetEntity().TurnHead(dp, dy);
77 float PlayerController::GetPitch() const noexcept {
78 return player.GetEntity().Pitch();
81 float PlayerController::GetYaw() const noexcept {
82 return player.GetEntity().Yaw();
85 void PlayerController::SelectInventory(int i) noexcept {
86 player.SetInventorySlot(i);
89 int PlayerController::InventorySlot() const noexcept {
90 return player.GetInventorySlot();
93 void PlayerController::Invalidate() noexcept {
97 void PlayerController::UpdatePlayer() noexcept {
99 Ray aim = player.Aim();
100 if (!world.Intersection(aim, player.GetEntity().ChunkCoords(), aim_world)) {
101 aim_world = WorldCollision();
103 if (!world.Intersection(aim, player.GetEntity(), aim_entity)) {
104 aim_entity = EntityCollision();
106 if (aim_world && aim_entity) {
107 // got both, pick the closest one
108 if (aim_world.depth < aim_entity.depth) {
109 aim_entity = EntityCollision();
111 aim_world = WorldCollision();
119 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
120 : PlayerController(world, player)
123 , remove_timer(0.25f) {
127 void DirectInput::Update(Entity &, float dt) {
128 Invalidate(); // world has changed in the meantime
131 remove_timer.Update(dt);
132 if (remove_timer.Hit()) {
136 place_timer.Update(dt);
137 if (place_timer.Hit()) {
142 void DirectInput::StartPrimaryAction() {
143 if (!remove_timer.Running()) {
145 remove_timer.Start();
149 void DirectInput::StopPrimaryAction() {
153 void DirectInput::StartSecondaryAction() {
154 if (!place_timer.Running()) {
160 void DirectInput::StopSecondaryAction() {
164 void DirectInput::StartTertiaryAction() {
168 void DirectInput::StopTertiaryAction() {
172 void DirectInput::PickBlock() {
174 if (!BlockFocus()) return;
175 SelectInventory(BlockFocus().GetBlock().type - 1);
178 void DirectInput::PlaceBlock() {
180 if (!BlockFocus()) return;
182 BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
186 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
190 void DirectInput::RemoveBlock() {
192 if (!BlockFocus()) return;
193 manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
198 HUD::HUD(Environment &env, Config &config, const Player &player)
204 , outline_transform(1.0f)
205 , outline_visible(false)
209 , block_transform(1.0f)
211 , block_visible(false)
225 , messages(env.assets.small_ui_font)
230 const float ls = env.assets.small_ui_font.LineSkip();
233 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
234 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
235 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
236 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
237 block_label.Position(
238 glm::vec3(50.0f, 85.0f, 0.0f),
242 block_label.Foreground(glm::vec4(1.0f));
243 block_label.Background(glm::vec4(0.5f));
246 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
247 counter_text.Foreground(glm::vec4(1.0f));
248 counter_text.Background(glm::vec4(0.5f));
249 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
250 position_text.Foreground(glm::vec4(1.0f));
251 position_text.Background(glm::vec4(0.5f));
252 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
253 orientation_text.Foreground(glm::vec4(1.0f));
254 orientation_text.Background(glm::vec4(0.5f));
255 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
256 block_text.Foreground(glm::vec4(1.0f));
257 block_text.Background(glm::vec4(0.5f));
258 block_text.Set(env.assets.small_ui_font, "Block: none");
259 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
260 entity_text.Foreground(glm::vec4(1.0f));
261 entity_text.Background(glm::vec4(0.5f));
262 entity_text.Set(env.assets.small_ui_font, "Entity: none");
265 bandwidth_text.Position(glm::vec3(-25.0f, 25.0f + 6 * ls, 0.0f), Gravity::NORTH_EAST);
266 bandwidth_text.Foreground(glm::vec4(1.0f));
267 bandwidth_text.Background(glm::vec4(0.5f));
268 bandwidth_text.Set(env.assets.small_ui_font, "TX: 0.0KB/s RX: 0.0KB/s");
269 rtt_text.Position(glm::vec3(-25.0f, 25.0f + 7 * ls, 0.0f), Gravity::NORTH_EAST);
270 rtt_text.Foreground(glm::vec4(1.0f));
271 rtt_text.Background(glm::vec4(0.5f));
272 rtt_text.Set(env.assets.small_ui_font, "RTT: unavailable");
273 packet_loss_text.Position(glm::vec3(-25.0f, 25.0f + 8 * ls, 0.0f), Gravity::NORTH_EAST);
274 packet_loss_text.Foreground(glm::vec4(1.0f));
275 packet_loss_text.Background(glm::vec4(0.5f));
276 packet_loss_text.Set(env.assets.small_ui_font, "Packet loss: 0.0%");
279 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
280 messages.Foreground(glm::vec4(1.0f));
281 messages.Background(glm::vec4(0.5f));
284 PrimitiveMesh::Buffer buf;
285 buf.vertices = std::vector<glm::vec3>({
286 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
287 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
289 buf.indices = std::vector<PrimitiveMesh::Index>({
292 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
293 crosshair.Update(buf);
298 PrimitiveMesh::Buffer outl_buf;
302 void HUD::FocusBlock(const Chunk &chunk, int index) {
303 const Block &block = chunk.BlockAt(index);
304 const BlockType &type = chunk.Type(index);
306 type.OutlinePrimitiveMesh(outl_buf);
307 outline.Update(outl_buf);
308 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
309 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
310 outline_transform *= glm::scale(glm::vec3(1.005f));
311 outline_visible = true;
316 << ", face: " << block.GetFace()
317 << ", turn: " << block.GetTurn();
318 block_text.Set(env.assets.small_ui_font, s.str());
324 void HUD::FocusEntity(const Entity &entity) {
327 s << "Entity: " << entity.Name();
328 entity_text.Set(env.assets.small_ui_font, s.str());
334 void HUD::FocusNone() {
335 outline_visible = false;
340 void HUD::DisplayNone() {
341 block_visible = false;
344 void HUD::Display(const BlockType &type) {
346 type.FillEntityMesh(block_buf);
347 block.Update(block_buf);
349 block_label.Set(env.assets.small_ui_font, type.label);
351 block_visible = type.visible;
355 void HUD::UpdateDebug() {
361 void HUD::UpdateCounter() {
363 s << std::setprecision(3) <<
364 "avg: " << env.counter.Average().running << "ms, "
365 "peak: " << env.counter.Peak().running << "ms";
366 std::string text = s.str();
367 counter_text.Set(env.assets.small_ui_font, text);
370 void HUD::UpdatePosition() {
372 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
373 position_text.Set(env.assets.small_ui_font, s.str());
376 void HUD::UpdateOrientation() {
378 s << std::setprecision(3) << "pitch: " << glm::degrees(player.GetEntity().Pitch())
379 << ", yaw: " << glm::degrees(player.GetEntity().Yaw());
380 orientation_text.Set(env.assets.small_ui_font, s.str());
383 void HUD::PostMessage(const char *msg) {
384 messages.PushLine(msg);
387 std::cout << msg << std::endl;
391 void HUD::UpdateNetStats(const CongestionControl &stat) {
392 if (!config.video.debug) return;
395 s << std::fixed << std::setprecision(1)
396 << "TX: " << stat.Upstream()
397 << "KB/s, RX: " << stat.Downstream() << "KB/s";
398 bandwidth_text.Set(env.assets.small_ui_font, s.str());
401 s << "RTT: " << stat.RoundTripTime() << "ms";
402 rtt_text.Set(env.assets.small_ui_font, s.str());
405 s << "Packet loss: " << (stat.PacketLoss() * 100.0f) << "%";
406 packet_loss_text.Set(env.assets.small_ui_font, s.str());
412 void HUD::Update(int dt) {
413 msg_timer.Update(dt);
414 if (msg_timer.HitOnce()) {
418 if (config.video.debug) {
419 if (env.counter.Changed()) {
427 void HUD::Render(Viewport &viewport) noexcept {
429 if (outline_visible && config.video.world) {
430 PlainColor &outline_prog = viewport.WorldColorProgram();
431 outline_prog.SetM(outline_transform);
435 // clear depth buffer so everything renders above the world
436 viewport.ClearDepth();
438 if (config.video.hud) {
441 DirectionalLighting &world_prog = viewport.HUDProgram();
442 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
443 world_prog.SetLightColor({ 1.0f, 1.0f, 1.0f });
444 world_prog.SetAmbientColor({ 0.1f, 0.1f, 0.1f });
445 // disable distance fog
446 world_prog.SetFogDensity(0.0f);
448 viewport.DisableBlending();
449 world_prog.SetM(block_transform);
451 block_label.Render(viewport);
455 if (msg_keep || msg_timer.Running()) {
456 messages.Render(viewport);
460 PlainColor &outline_prog = viewport.HUDColorProgram();
461 viewport.EnableInvertBlending();
462 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
463 outline_prog.SetM(viewport.Cursor());
464 crosshair.DrawLines();
468 if (config.video.debug) {
469 counter_text.Render(viewport);
470 position_text.Render(viewport);
471 orientation_text.Render(viewport);
473 block_text.Render(viewport);
474 } else if (show_entity) {
475 entity_text.Render(viewport);
478 bandwidth_text.Render(viewport);
479 rtt_text.Render(viewport);
480 packet_loss_text.Render(viewport);
486 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
493 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
494 const BlockType &old_type = chunk.Type(index);
495 chunk.SetBlock(index, block);
496 const BlockType &new_type = chunk.Type(index);
497 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
498 if (new_type.id == 0) {
499 if (old_type.remove_sound >= 0) {
500 audio.Play(sounds[old_type.remove_sound], coords);
503 if (new_type.place_sound >= 0) {
504 audio.Play(sounds[new_type.place_sound], coords);
510 Interface::Interface(
512 const Keymap &keymap,
513 PlayerController &pc,
514 ClientController &cc)
526 void Interface::Lock() {
532 void Interface::Unlock() {
536 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
537 if (!config.input.keyboard) return;
539 Keymap::Action action = keymap.Lookup(event);
541 case Keymap::MOVE_FORWARD:
545 case Keymap::MOVE_BACKWARD:
549 case Keymap::MOVE_LEFT:
553 case Keymap::MOVE_RIGHT:
557 case Keymap::MOVE_UP:
561 case Keymap::MOVE_DOWN:
566 case Keymap::PRIMARY:
567 player_ctrl.StartPrimaryAction();
569 case Keymap::SECONDARY:
570 player_ctrl.StartSecondaryAction();
572 case Keymap::TERTIARY:
573 player_ctrl.StartTertiaryAction();
576 case Keymap::INV_NEXT:
579 case Keymap::INV_PREVIOUS:
592 InvAbs(action - Keymap::INV_1);
599 case Keymap::TOGGLE_AUDIO:
600 client_ctrl.SetAudio(!config.audio.enabled);
602 case Keymap::TOGGLE_VIDEO:
603 client_ctrl.SetVideo(!config.video.world);
605 case Keymap::TOGGLE_HUD:
606 client_ctrl.SetHUD(!config.video.hud);
608 case Keymap::TOGGLE_DEBUG:
609 client_ctrl.SetDebug(!config.video.debug);
611 case Keymap::CAMERA_NEXT:
612 client_ctrl.NextCamera();
620 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
621 if (!config.input.keyboard) return;
623 switch (keymap.Lookup(event)) {
624 case Keymap::MOVE_FORWARD:
628 case Keymap::MOVE_BACKWARD:
632 case Keymap::MOVE_LEFT:
636 case Keymap::MOVE_RIGHT:
640 case Keymap::MOVE_UP:
644 case Keymap::MOVE_DOWN:
649 case Keymap::PRIMARY:
650 player_ctrl.StopPrimaryAction();
652 case Keymap::SECONDARY:
653 player_ctrl.StopSecondaryAction();
655 case Keymap::TERTIARY:
656 player_ctrl.StopTertiaryAction();
664 void Interface::Handle(const SDL_MouseMotionEvent &event) {
665 if (locked || !config.input.mouse) return;
666 player_ctrl.TurnHead(
667 event.yrel * config.input.pitch_sensitivity,
668 event.xrel * config.input.yaw_sensitivity);
671 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
672 if (!config.input.mouse) return;
674 switch (event.button) {
675 case SDL_BUTTON_LEFT:
676 player_ctrl.StartPrimaryAction();
678 case SDL_BUTTON_RIGHT:
679 player_ctrl.StartSecondaryAction();
681 case SDL_BUTTON_MIDDLE:
682 player_ctrl.StartTertiaryAction();
687 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
688 if (!config.input.mouse) return;
690 switch (event.button) {
691 case SDL_BUTTON_LEFT:
692 player_ctrl.StopPrimaryAction();
694 case SDL_BUTTON_RIGHT:
695 player_ctrl.StopSecondaryAction();
697 case SDL_BUTTON_MIDDLE:
698 player_ctrl.StopTertiaryAction();
704 void Interface::Handle(const SDL_MouseWheelEvent &event) {
705 if (!config.input.mouse) return;
709 } else if (event.y > 0) {
714 void Interface::UpdateMovement() {
715 player_ctrl.SetMovement(glm::vec3(fwd - rev));
718 void Interface::InvAbs(int s) {
719 int slot = s % num_slots;
723 player_ctrl.SelectInventory(slot);
726 void Interface::InvRel(int delta) {
727 InvAbs(player_ctrl.GetPlayer().GetInventorySlot() + delta);
736 void Keymap::Map(SDL_Scancode scancode, Action action) {
737 if (scancode > MAX_SCANCODE) {
738 throw std::runtime_error("refusing to map scancode: too damn high");
740 codemap[scancode] = action;
743 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
744 if (scancode < NUM_SCANCODES) {
745 return codemap[scancode];
752 void Keymap::LoadDefault() {
753 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
754 Map(SDL_SCANCODE_W, MOVE_FORWARD);
755 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
756 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
757 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
758 Map(SDL_SCANCODE_A, MOVE_LEFT);
759 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
760 Map(SDL_SCANCODE_D, MOVE_RIGHT);
761 Map(SDL_SCANCODE_SPACE, MOVE_UP);
762 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
763 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
764 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
765 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
767 Map(SDL_SCANCODE_TAB, INV_NEXT);
768 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
769 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
770 Map(SDL_SCANCODE_1, INV_1);
771 Map(SDL_SCANCODE_2, INV_2);
772 Map(SDL_SCANCODE_3, INV_3);
773 Map(SDL_SCANCODE_4, INV_4);
774 Map(SDL_SCANCODE_5, INV_5);
775 Map(SDL_SCANCODE_6, INV_6);
776 Map(SDL_SCANCODE_7, INV_7);
777 Map(SDL_SCANCODE_8, INV_8);
778 Map(SDL_SCANCODE_9, INV_9);
779 Map(SDL_SCANCODE_0, INV_10);
781 Map(SDL_SCANCODE_INSERT, SECONDARY);
782 Map(SDL_SCANCODE_MENU, TERTIARY);
783 Map(SDL_SCANCODE_DELETE, PRIMARY);
784 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
786 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
787 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
788 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
789 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
790 Map(SDL_SCANCODE_F5, CAMERA_NEXT);
792 Map(SDL_SCANCODE_ESCAPE, EXIT);
796 void Keymap::Load(std::istream &is) {
797 TokenStreamReader in(is);
798 std::string key_name;
799 std::string action_name;
802 while (in.HasMore()) {
803 if (in.Peek().type == Token::STRING) {
804 in.ReadString(key_name);
805 key = SDL_GetScancodeFromName(key_name.c_str());
807 key = SDL_Scancode(in.GetInt());
809 in.Skip(Token::EQUALS);
810 in.ReadIdentifier(action_name);
811 action = StringToAction(action_name);
812 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
813 in.Skip(Token::SEMICOLON);
819 void Keymap::Save(std::ostream &out) {
820 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
821 if (codemap[i] == NONE) continue;
823 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
839 out << " = " << ActionToString(codemap[i]) << std::endl;;
846 std::map<std::string, Keymap::Action> action_map = {
847 { "none", Keymap::NONE },
848 { "move_forward", Keymap::MOVE_FORWARD },
849 { "move_backward", Keymap::MOVE_BACKWARD },
850 { "move_left", Keymap::MOVE_LEFT },
851 { "move_right", Keymap::MOVE_RIGHT },
852 { "move_up", Keymap::MOVE_UP },
853 { "move_down", Keymap::MOVE_DOWN },
855 { "primary", Keymap::PRIMARY },
856 { "secondary", Keymap::SECONDARY },
857 { "tertiary", Keymap::TERTIARY },
859 { "inventory_next", Keymap::INV_NEXT },
860 { "inventory_prev", Keymap::INV_PREVIOUS },
861 { "inventory_1", Keymap::INV_1 },
862 { "inventory_2", Keymap::INV_2 },
863 { "inventory_3", Keymap::INV_3 },
864 { "inventory_4", Keymap::INV_4 },
865 { "inventory_5", Keymap::INV_5 },
866 { "inventory_6", Keymap::INV_6 },
867 { "inventory_7", Keymap::INV_7 },
868 { "inventory_8", Keymap::INV_8 },
869 { "inventory_9", Keymap::INV_9 },
870 { "inventory_10", Keymap::INV_10 },
872 { "toggle_audio", Keymap::TOGGLE_AUDIO },
873 { "toggle_video", Keymap::TOGGLE_VIDEO },
874 { "toggle_hud", Keymap::TOGGLE_HUD },
875 { "toggle_debug", Keymap::TOGGLE_DEBUG },
876 { "camera_next", Keymap::CAMERA_NEXT },
878 { "exit", Keymap::EXIT },
883 const char *Keymap::ActionToString(Action action) {
884 for (const auto &entry : action_map) {
885 if (action == entry.second) {
886 return entry.first.c_str();
892 Keymap::Action Keymap::StringToAction(const std::string &str) {
893 auto entry = action_map.find(str);
894 if (entry != action_map.end()) {
895 return entry->second;
897 std::cerr << "unknown action \"" << str << '"' << std::endl;