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 "../world/BlockLookup.hpp"
21 #include "../world/World.hpp"
22 #include "../world/WorldManipulator.hpp"
29 #include <glm/gtc/matrix_transform.hpp>
30 #include <glm/gtx/rotate_vector.hpp>
31 #include <glm/gtx/io.hpp>
36 PlayerController::PlayerController(World &world, Player &player)
46 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
47 if (dot(m, m) > 1.0f) {
48 move_dir = normalize(m);
55 void PlayerController::TurnHead(float dp, float dy) noexcept {
56 player.GetEntity().TurnHead(dp, dy);
59 float PlayerController::GetPitch() const noexcept {
60 return player.GetEntity().Pitch();
63 float PlayerController::GetYaw() const noexcept {
64 return player.GetEntity().Yaw();
67 void PlayerController::SelectInventory(int i) noexcept {
68 player.SetInventorySlot(i);
71 int PlayerController::InventorySlot() const noexcept {
72 return player.GetInventorySlot();
75 void PlayerController::Invalidate() noexcept {
79 void PlayerController::UpdatePlayer() noexcept {
80 constexpr float max_vel = 5.0f; // in m/s
82 player.GetEntity().TargetVelocity(glm::rotateY(move_dir * max_vel, player.GetEntity().Yaw()));
84 Ray aim = player.Aim();
85 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity().ChunkCoords(), aim_world)) {
86 aim_world = WorldCollision();
88 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity(), aim_entity)) {
89 aim_entity = EntityCollision();
91 if (aim_world && aim_entity) {
92 // got both, pick the closest one
93 if (aim_world.depth < aim_entity.depth) {
94 aim_entity = EntityCollision();
96 aim_world = WorldCollision();
104 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
105 : PlayerController(world, player)
108 , remove_timer(256) {
112 void DirectInput::Update(int dt) {
113 Invalidate(); // world has changed in the meantime
116 remove_timer.Update(dt);
117 if (remove_timer.Hit()) {
121 place_timer.Update(dt);
122 if (place_timer.Hit()) {
127 void DirectInput::StartPrimaryAction() {
128 if (!remove_timer.Running()) {
130 remove_timer.Start();
134 void DirectInput::StopPrimaryAction() {
138 void DirectInput::StartSecondaryAction() {
139 if (!place_timer.Running()) {
145 void DirectInput::StopSecondaryAction() {
149 void DirectInput::StartTertiaryAction() {
153 void DirectInput::StopTertiaryAction() {
157 void DirectInput::PickBlock() {
159 if (!BlockFocus()) return;
160 SelectInventory(BlockFocus().GetBlock().type - 1);
163 void DirectInput::PlaceBlock() {
165 if (!BlockFocus()) return;
167 BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
171 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
175 void DirectInput::RemoveBlock() {
177 if (!BlockFocus()) return;
178 manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
183 HUD::HUD(Environment &env, Config &config, const Player &player)
189 , outline_transform(1.0f)
190 , outline_visible(false)
194 , block_transform(1.0f)
196 , block_visible(false)
205 , messages(env.assets.small_ui_font)
210 const float ls = env.assets.small_ui_font.LineSkip();
213 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
214 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
215 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
216 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
217 block_label.Position(
218 glm::vec3(50.0f, 85.0f, 0.0f),
222 block_label.Foreground(glm::vec4(1.0f));
223 block_label.Background(glm::vec4(0.5f));
226 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
227 counter_text.Foreground(glm::vec4(1.0f));
228 counter_text.Background(glm::vec4(0.5f));
229 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
230 position_text.Foreground(glm::vec4(1.0f));
231 position_text.Background(glm::vec4(0.5f));
232 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
233 orientation_text.Foreground(glm::vec4(1.0f));
234 orientation_text.Background(glm::vec4(0.5f));
235 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
236 block_text.Foreground(glm::vec4(1.0f));
237 block_text.Background(glm::vec4(0.5f));
238 block_text.Set(env.assets.small_ui_font, "Block: none");
239 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
240 entity_text.Foreground(glm::vec4(1.0f));
241 entity_text.Background(glm::vec4(0.5f));
242 entity_text.Set(env.assets.small_ui_font, "Entity: none");
245 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
246 messages.Foreground(glm::vec4(1.0f));
247 messages.Background(glm::vec4(0.5f));
250 PrimitiveMesh::Buffer buf;
251 buf.vertices = std::vector<glm::vec3>({
252 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
253 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
255 buf.indices = std::vector<PrimitiveMesh::Index>({
258 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
259 crosshair.Update(buf);
264 PrimitiveMesh::Buffer outl_buf;
268 void HUD::FocusBlock(const Chunk &chunk, int index) {
269 const Block &block = chunk.BlockAt(index);
270 const BlockType &type = chunk.Type(index);
272 type.OutlinePrimitiveMesh(outl_buf);
273 outline.Update(outl_buf);
274 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
275 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
276 outline_transform *= glm::scale(glm::vec3(1.005f));
277 outline_visible = true;
282 << ", face: " << block.GetFace()
283 << ", turn: " << block.GetTurn();
284 block_text.Set(env.assets.small_ui_font, s.str());
290 void HUD::FocusEntity(const Entity &entity) {
293 s << "Entity: " << entity.Name();
294 entity_text.Set(env.assets.small_ui_font, s.str());
300 void HUD::FocusNone() {
301 outline_visible = false;
306 void HUD::DisplayNone() {
307 block_visible = false;
310 void HUD::Display(const BlockType &type) {
312 type.FillEntityMesh(block_buf);
313 block.Update(block_buf);
315 block_label.Set(env.assets.small_ui_font, type.label);
317 block_visible = type.visible;
321 void HUD::UpdateDebug() {
327 void HUD::UpdateCounter() {
329 s << std::setprecision(3) <<
330 "avg: " << env.counter.Average().running << "ms, "
331 "peak: " << env.counter.Peak().running << "ms";
332 std::string text = s.str();
333 counter_text.Set(env.assets.small_ui_font, text);
336 void HUD::UpdatePosition() {
338 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
339 position_text.Set(env.assets.small_ui_font, s.str());
342 void HUD::UpdateOrientation() {
343 //std::stringstream s;
344 //s << std::setprecision(3) << "pitch: " << rad2deg(ctrl.Pitch())
345 // << ", yaw: " << rad2deg(ctrl.Yaw());
346 //orientation_text.Set(env.assets.small_ui_font, s.str());
349 void HUD::PostMessage(const char *msg) {
350 messages.PushLine(msg);
353 std::cout << msg << std::endl;
357 void HUD::Update(int dt) {
358 msg_timer.Update(dt);
359 if (msg_timer.HitOnce()) {
363 if (config.video.debug) {
364 if (env.counter.Changed()) {
372 void HUD::Render(Viewport &viewport) noexcept {
374 if (outline_visible && config.video.world) {
375 PlainColor &outline_prog = viewport.WorldColorProgram();
376 outline_prog.SetM(outline_transform);
380 // clear depth buffer so everything renders above the world
381 viewport.ClearDepth();
383 if (config.video.hud) {
386 DirectionalLighting &world_prog = viewport.HUDProgram();
387 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
388 // disable distance fog
389 world_prog.SetFogDensity(0.0f);
391 viewport.DisableBlending();
392 world_prog.SetM(block_transform);
394 block_label.Render(viewport);
398 if (msg_keep || msg_timer.Running()) {
399 messages.Render(viewport);
403 PlainColor &outline_prog = viewport.HUDColorProgram();
404 viewport.EnableInvertBlending();
405 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
406 outline_prog.SetM(viewport.Cursor());
407 crosshair.DrawLines();
411 if (config.video.debug) {
412 counter_text.Render(viewport);
413 position_text.Render(viewport);
414 orientation_text.Render(viewport);
416 block_text.Render(viewport);
417 } else if (show_entity) {
418 entity_text.Render(viewport);
424 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
431 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
432 const BlockType &old_type = chunk.Type(index);
433 chunk.SetBlock(index, block);
434 const BlockType &new_type = chunk.Type(index);
435 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
436 if (new_type.id == 0) {
437 if (old_type.remove_sound >= 0) {
438 audio.Play(sounds[old_type.remove_sound], coords);
441 if (new_type.place_sound >= 0) {
442 audio.Play(sounds[new_type.place_sound], coords);
448 Interface::Interface(
450 const Keymap &keymap,
451 PlayerController &pc,
452 ClientController &cc)
465 void Interface::Lock() {
471 void Interface::Unlock() {
475 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
476 if (!config.input.keyboard) return;
478 Keymap::Action action = keymap.Lookup(event);
480 case Keymap::MOVE_FORWARD:
484 case Keymap::MOVE_BACKWARD:
488 case Keymap::MOVE_LEFT:
492 case Keymap::MOVE_RIGHT:
496 case Keymap::MOVE_UP:
500 case Keymap::MOVE_DOWN:
505 case Keymap::PRIMARY:
506 player_ctrl.StartPrimaryAction();
508 case Keymap::SECONDARY:
509 player_ctrl.StartSecondaryAction();
511 case Keymap::TERTIARY:
512 player_ctrl.StartTertiaryAction();
515 case Keymap::INV_NEXT:
518 case Keymap::INV_PREVIOUS:
531 InvAbs(action - Keymap::INV_1);
538 case Keymap::TOGGLE_AUDIO:
539 config.audio.enabled = !config.audio.enabled;
540 client_ctrl.SetAudio(config.audio.enabled);
542 case Keymap::TOGGLE_VIDEO:
543 config.video.world = !config.video.world;
544 client_ctrl.SetVideo(config.video.world);
546 case Keymap::TOGGLE_HUD:
547 config.video.hud = !config.video.hud;
548 client_ctrl.SetHUD(config.video.hud);
550 case Keymap::TOGGLE_DEBUG:
551 config.video.debug = !config.video.debug;
552 client_ctrl.SetDebug(config.video.debug);
560 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
561 if (!config.input.keyboard) return;
563 switch (keymap.Lookup(event)) {
564 case Keymap::MOVE_FORWARD:
568 case Keymap::MOVE_BACKWARD:
572 case Keymap::MOVE_LEFT:
576 case Keymap::MOVE_RIGHT:
580 case Keymap::MOVE_UP:
584 case Keymap::MOVE_DOWN:
589 case Keymap::PRIMARY:
590 player_ctrl.StopPrimaryAction();
592 case Keymap::SECONDARY:
593 player_ctrl.StopSecondaryAction();
595 case Keymap::TERTIARY:
596 player_ctrl.StopTertiaryAction();
604 void Interface::Handle(const SDL_MouseMotionEvent &event) {
605 if (locked || !config.input.mouse) return;
606 player_ctrl.TurnHead(
607 event.yrel * config.input.pitch_sensitivity,
608 event.xrel * config.input.yaw_sensitivity);
611 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
612 if (!config.input.mouse) return;
614 switch (event.button) {
615 case SDL_BUTTON_LEFT:
616 player_ctrl.StartPrimaryAction();
618 case SDL_BUTTON_RIGHT:
619 player_ctrl.StartSecondaryAction();
621 case SDL_BUTTON_MIDDLE:
622 player_ctrl.StartTertiaryAction();
627 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
628 if (!config.input.mouse) return;
630 switch (event.button) {
631 case SDL_BUTTON_LEFT:
632 player_ctrl.StopPrimaryAction();
634 case SDL_BUTTON_RIGHT:
635 player_ctrl.StopSecondaryAction();
637 case SDL_BUTTON_MIDDLE:
638 player_ctrl.StopTertiaryAction();
644 void Interface::Handle(const SDL_MouseWheelEvent &event) {
645 if (!config.input.mouse) return;
649 } else if (event.y > 0) {
654 void Interface::UpdateMovement() {
655 player_ctrl.SetMovement(glm::vec3(fwd - rev));
658 void Interface::InvAbs(int s) {
659 slot = s % num_slots;
663 player_ctrl.SelectInventory(slot);
666 void Interface::InvRel(int delta) {
667 InvAbs(slot + delta);
676 void Keymap::Map(SDL_Scancode scancode, Action action) {
677 if (scancode > MAX_SCANCODE) {
678 throw std::runtime_error("refusing to map scancode: too damn high");
680 codemap[scancode] = action;
683 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
684 if (scancode < NUM_SCANCODES) {
685 return codemap[scancode];
692 void Keymap::LoadDefault() {
693 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
694 Map(SDL_SCANCODE_W, MOVE_FORWARD);
695 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
696 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
697 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
698 Map(SDL_SCANCODE_A, MOVE_LEFT);
699 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
700 Map(SDL_SCANCODE_D, MOVE_RIGHT);
701 Map(SDL_SCANCODE_SPACE, MOVE_UP);
702 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
703 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
704 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
705 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
707 Map(SDL_SCANCODE_TAB, INV_NEXT);
708 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
709 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
710 Map(SDL_SCANCODE_1, INV_1);
711 Map(SDL_SCANCODE_2, INV_2);
712 Map(SDL_SCANCODE_3, INV_3);
713 Map(SDL_SCANCODE_4, INV_4);
714 Map(SDL_SCANCODE_5, INV_5);
715 Map(SDL_SCANCODE_6, INV_6);
716 Map(SDL_SCANCODE_7, INV_7);
717 Map(SDL_SCANCODE_8, INV_8);
718 Map(SDL_SCANCODE_9, INV_9);
719 Map(SDL_SCANCODE_0, INV_10);
721 Map(SDL_SCANCODE_INSERT, SECONDARY);
722 Map(SDL_SCANCODE_RETURN, SECONDARY);
723 Map(SDL_SCANCODE_MENU, TERTIARY);
724 Map(SDL_SCANCODE_DELETE, PRIMARY);
725 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
727 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
728 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
729 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
730 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
732 Map(SDL_SCANCODE_ESCAPE, EXIT);
736 void Keymap::Load(std::istream &is) {
737 TokenStreamReader in(is);
738 std::string key_name;
739 std::string action_name;
742 while (in.HasMore()) {
743 if (in.Peek().type == Token::STRING) {
744 in.ReadString(key_name);
745 key = SDL_GetScancodeFromName(key_name.c_str());
747 key = SDL_Scancode(in.GetInt());
749 in.Skip(Token::EQUALS);
750 in.ReadIdentifier(action_name);
751 action = StringToAction(action_name);
752 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
753 in.Skip(Token::SEMICOLON);
759 void Keymap::Save(std::ostream &out) {
760 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
761 if (codemap[i] == NONE) continue;
763 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
779 out << " = " << ActionToString(codemap[i]) << std::endl;;
786 std::map<std::string, Keymap::Action> action_map = {
787 { "none", Keymap::NONE },
788 { "move_forward", Keymap::MOVE_FORWARD },
789 { "move_backward", Keymap::MOVE_BACKWARD },
790 { "move_left", Keymap::MOVE_LEFT },
791 { "move_right", Keymap::MOVE_RIGHT },
792 { "move_up", Keymap::MOVE_UP },
793 { "move_down", Keymap::MOVE_DOWN },
795 { "primary", Keymap::PRIMARY },
796 { "secondary", Keymap::SECONDARY },
797 { "tertiary", Keymap::TERTIARY },
799 { "inventory_next", Keymap::INV_NEXT },
800 { "inventory_prev", Keymap::INV_PREVIOUS },
801 { "inventory_1", Keymap::INV_1 },
802 { "inventory_2", Keymap::INV_2 },
803 { "inventory_3", Keymap::INV_3 },
804 { "inventory_4", Keymap::INV_4 },
805 { "inventory_5", Keymap::INV_5 },
806 { "inventory_6", Keymap::INV_6 },
807 { "inventory_7", Keymap::INV_7 },
808 { "inventory_8", Keymap::INV_8 },
809 { "inventory_9", Keymap::INV_9 },
810 { "inventory_10", Keymap::INV_10 },
812 { "toggle_audio", Keymap::TOGGLE_AUDIO },
813 { "toggle_video", Keymap::TOGGLE_VIDEO },
814 { "toggle_hud", Keymap::TOGGLE_HUD },
815 { "toggle_debug", Keymap::TOGGLE_DEBUG },
817 { "exit", Keymap::EXIT },
822 const char *Keymap::ActionToString(Action action) {
823 for (const auto &entry : action_map) {
824 if (action == entry.second) {
825 return entry.first.c_str();
831 Keymap::Action Keymap::StringToAction(const std::string &str) {
832 auto entry = action_map.find(str);
833 if (entry != action_map.end()) {
834 return entry->second;
836 std::cerr << "unknown action \"" << str << '"' << std::endl;