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)
48 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
49 if (dot(m, m) > 1.0f) {
50 move_dir = normalize(m);
57 void PlayerController::TurnHead(float dp, float dy) noexcept {
61 } else if (pitch < -PI / 2) {
67 } else if (yaw < -PI) {
73 void PlayerController::SelectInventory(int i) noexcept {
74 player.SetInventorySlot(i);
77 int PlayerController::InventorySlot() const noexcept {
78 return player.GetInventorySlot();
81 void PlayerController::Invalidate() noexcept {
85 void PlayerController::UpdatePlayer() noexcept {
86 constexpr float max_vel = 5.0f; // in m/s
88 player.GetEntity().Orientation(glm::quat(glm::vec3(0.0f, yaw, 0.0f)));
89 player.GetEntity().GetModel().EyesState().orientation = glm::quat(glm::vec3(pitch, 0.0f, 0.0f));
90 player.GetEntity().TargetVelocity(glm::rotateY(move_dir * max_vel, yaw));
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(256) {
120 void DirectInput::Update(int 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)
213 , messages(env.assets.small_ui_font)
218 const float ls = env.assets.small_ui_font.LineSkip();
221 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
222 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
223 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
224 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
225 block_label.Position(
226 glm::vec3(50.0f, 85.0f, 0.0f),
230 block_label.Foreground(glm::vec4(1.0f));
231 block_label.Background(glm::vec4(0.5f));
234 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
235 counter_text.Foreground(glm::vec4(1.0f));
236 counter_text.Background(glm::vec4(0.5f));
237 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
238 position_text.Foreground(glm::vec4(1.0f));
239 position_text.Background(glm::vec4(0.5f));
240 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
241 orientation_text.Foreground(glm::vec4(1.0f));
242 orientation_text.Background(glm::vec4(0.5f));
243 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
244 block_text.Foreground(glm::vec4(1.0f));
245 block_text.Background(glm::vec4(0.5f));
246 block_text.Set(env.assets.small_ui_font, "Block: none");
247 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
248 entity_text.Foreground(glm::vec4(1.0f));
249 entity_text.Background(glm::vec4(0.5f));
250 entity_text.Set(env.assets.small_ui_font, "Entity: none");
253 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
254 messages.Foreground(glm::vec4(1.0f));
255 messages.Background(glm::vec4(0.5f));
258 PrimitiveMesh::Buffer buf;
259 buf.vertices = std::vector<glm::vec3>({
260 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
261 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
263 buf.indices = std::vector<PrimitiveMesh::Index>({
266 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
267 crosshair.Update(buf);
272 PrimitiveMesh::Buffer outl_buf;
276 void HUD::FocusBlock(const Chunk &chunk, int index) {
277 const Block &block = chunk.BlockAt(index);
278 const BlockType &type = chunk.Type(index);
280 type.OutlinePrimitiveMesh(outl_buf);
281 outline.Update(outl_buf);
282 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
283 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
284 outline_transform *= glm::scale(glm::vec3(1.005f));
285 outline_visible = true;
290 << ", face: " << block.GetFace()
291 << ", turn: " << block.GetTurn();
292 block_text.Set(env.assets.small_ui_font, s.str());
298 void HUD::FocusEntity(const Entity &entity) {
301 s << "Entity: " << entity.Name();
302 entity_text.Set(env.assets.small_ui_font, s.str());
308 void HUD::FocusNone() {
309 outline_visible = false;
314 void HUD::DisplayNone() {
315 block_visible = false;
318 void HUD::Display(const BlockType &type) {
320 type.FillEntityMesh(block_buf);
321 block.Update(block_buf);
323 block_label.Set(env.assets.small_ui_font, type.label);
325 block_visible = type.visible;
329 void HUD::UpdateDebug() {
335 void HUD::UpdateCounter() {
337 s << std::setprecision(3) <<
338 "avg: " << env.counter.Average().running << "ms, "
339 "peak: " << env.counter.Peak().running << "ms";
340 std::string text = s.str();
341 counter_text.Set(env.assets.small_ui_font, text);
344 void HUD::UpdatePosition() {
346 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
347 position_text.Set(env.assets.small_ui_font, s.str());
350 void HUD::UpdateOrientation() {
351 //std::stringstream s;
352 //s << std::setprecision(3) << "pitch: " << rad2deg(ctrl.Pitch())
353 // << ", yaw: " << rad2deg(ctrl.Yaw());
354 //orientation_text.Set(env.assets.small_ui_font, s.str());
357 void HUD::PostMessage(const char *msg) {
358 messages.PushLine(msg);
361 std::cout << msg << std::endl;
365 void HUD::Update(int dt) {
366 msg_timer.Update(dt);
367 if (msg_timer.HitOnce()) {
371 if (config.video.debug) {
372 if (env.counter.Changed()) {
380 void HUD::Render(Viewport &viewport) noexcept {
382 if (outline_visible && config.video.world) {
383 PlainColor &outline_prog = viewport.WorldColorProgram();
384 outline_prog.SetM(outline_transform);
388 // clear depth buffer so everything renders above the world
389 viewport.ClearDepth();
391 if (config.video.hud) {
394 DirectionalLighting &world_prog = viewport.HUDProgram();
395 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
396 // disable distance fog
397 world_prog.SetFogDensity(0.0f);
399 viewport.DisableBlending();
400 world_prog.SetM(block_transform);
402 block_label.Render(viewport);
406 if (msg_keep || msg_timer.Running()) {
407 messages.Render(viewport);
411 PlainColor &outline_prog = viewport.HUDColorProgram();
412 viewport.EnableInvertBlending();
413 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
414 outline_prog.SetM(viewport.Cursor());
415 crosshair.DrawLines();
419 if (config.video.debug) {
420 counter_text.Render(viewport);
421 position_text.Render(viewport);
422 orientation_text.Render(viewport);
424 block_text.Render(viewport);
425 } else if (show_entity) {
426 entity_text.Render(viewport);
432 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
439 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
440 const BlockType &old_type = chunk.Type(index);
441 chunk.SetBlock(index, block);
442 const BlockType &new_type = chunk.Type(index);
443 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
444 if (new_type.id == 0) {
445 if (old_type.remove_sound >= 0) {
446 audio.Play(sounds[old_type.remove_sound], coords);
449 if (new_type.place_sound >= 0) {
450 audio.Play(sounds[new_type.place_sound], coords);
456 Interface::Interface(
458 const Keymap &keymap,
459 PlayerController &pc,
460 ClientController &cc)
473 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
474 if (!config.input.keyboard) return;
476 Keymap::Action action = keymap.Lookup(event);
478 case Keymap::MOVE_FORWARD:
482 case Keymap::MOVE_BACKWARD:
486 case Keymap::MOVE_LEFT:
490 case Keymap::MOVE_RIGHT:
494 case Keymap::MOVE_UP:
498 case Keymap::MOVE_DOWN:
503 case Keymap::PRIMARY:
504 player_ctrl.StartPrimaryAction();
506 case Keymap::SECONDARY:
507 player_ctrl.StartSecondaryAction();
509 case Keymap::TERTIARY:
510 player_ctrl.StartTertiaryAction();
513 case Keymap::INV_NEXT:
516 case Keymap::INV_PREVIOUS:
529 InvAbs(action - Keymap::INV_1);
536 case Keymap::TOGGLE_AUDIO:
537 config.audio.enabled = !config.audio.enabled;
538 client_ctrl.SetAudio(config.audio.enabled);
540 case Keymap::TOGGLE_VIDEO:
541 config.video.world = !config.video.world;
542 client_ctrl.SetVideo(config.video.world);
544 case Keymap::TOGGLE_HUD:
545 config.video.hud = !config.video.hud;
546 client_ctrl.SetHUD(config.video.hud);
548 case Keymap::TOGGLE_DEBUG:
549 config.video.debug = !config.video.debug;
550 client_ctrl.SetDebug(config.video.debug);
558 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
559 if (!config.input.keyboard) return;
561 switch (keymap.Lookup(event)) {
562 case Keymap::MOVE_FORWARD:
566 case Keymap::MOVE_BACKWARD:
570 case Keymap::MOVE_LEFT:
574 case Keymap::MOVE_RIGHT:
578 case Keymap::MOVE_UP:
582 case Keymap::MOVE_DOWN:
587 case Keymap::PRIMARY:
588 player_ctrl.StopPrimaryAction();
590 case Keymap::SECONDARY:
591 player_ctrl.StopSecondaryAction();
593 case Keymap::TERTIARY:
594 player_ctrl.StopTertiaryAction();
602 void Interface::Handle(const SDL_MouseMotionEvent &event) {
603 if (!config.input.mouse) return;
604 player_ctrl.TurnHead(
605 event.yrel * config.input.pitch_sensitivity,
606 event.xrel * config.input.yaw_sensitivity);
609 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
610 if (!config.input.mouse) return;
612 switch (event.button) {
613 case SDL_BUTTON_LEFT:
614 player_ctrl.StartPrimaryAction();
616 case SDL_BUTTON_RIGHT:
617 player_ctrl.StartSecondaryAction();
619 case SDL_BUTTON_MIDDLE:
620 player_ctrl.StartTertiaryAction();
625 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
626 if (!config.input.mouse) return;
628 switch (event.button) {
629 case SDL_BUTTON_LEFT:
630 player_ctrl.StopPrimaryAction();
632 case SDL_BUTTON_RIGHT:
633 player_ctrl.StopSecondaryAction();
635 case SDL_BUTTON_MIDDLE:
636 player_ctrl.StopTertiaryAction();
642 void Interface::Handle(const SDL_MouseWheelEvent &event) {
643 if (!config.input.mouse) return;
647 } else if (event.y > 0) {
652 void Interface::UpdateMovement() {
653 player_ctrl.SetMovement(glm::vec3(fwd - rev));
656 void Interface::InvAbs(int s) {
657 slot = s % num_slots;
661 player_ctrl.SelectInventory(slot);
664 void Interface::InvRel(int delta) {
665 InvAbs(slot + delta);
674 void Keymap::Map(SDL_Scancode scancode, Action action) {
675 if (scancode > MAX_SCANCODE) {
676 throw std::runtime_error("refusing to map scancode: too damn high");
678 codemap[scancode] = action;
681 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
682 if (scancode < NUM_SCANCODES) {
683 return codemap[scancode];
690 void Keymap::LoadDefault() {
691 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
692 Map(SDL_SCANCODE_W, MOVE_FORWARD);
693 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
694 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
695 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
696 Map(SDL_SCANCODE_A, MOVE_LEFT);
697 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
698 Map(SDL_SCANCODE_D, MOVE_RIGHT);
699 Map(SDL_SCANCODE_SPACE, MOVE_UP);
700 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
701 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
702 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
703 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
705 Map(SDL_SCANCODE_TAB, INV_NEXT);
706 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
707 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
708 Map(SDL_SCANCODE_1, INV_1);
709 Map(SDL_SCANCODE_2, INV_2);
710 Map(SDL_SCANCODE_3, INV_3);
711 Map(SDL_SCANCODE_4, INV_4);
712 Map(SDL_SCANCODE_5, INV_5);
713 Map(SDL_SCANCODE_6, INV_6);
714 Map(SDL_SCANCODE_7, INV_7);
715 Map(SDL_SCANCODE_8, INV_8);
716 Map(SDL_SCANCODE_9, INV_9);
717 Map(SDL_SCANCODE_0, INV_10);
719 Map(SDL_SCANCODE_INSERT, SECONDARY);
720 Map(SDL_SCANCODE_RETURN, SECONDARY);
721 Map(SDL_SCANCODE_MENU, TERTIARY);
722 Map(SDL_SCANCODE_DELETE, PRIMARY);
723 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
725 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
726 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
727 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
728 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
730 Map(SDL_SCANCODE_ESCAPE, EXIT);
734 void Keymap::Load(std::istream &is) {
735 TokenStreamReader in(is);
736 std::string key_name;
737 std::string action_name;
740 while (in.HasMore()) {
741 if (in.Peek().type == Token::STRING) {
742 in.ReadString(key_name);
743 key = SDL_GetScancodeFromName(key_name.c_str());
745 key = SDL_Scancode(in.GetInt());
747 in.Skip(Token::EQUALS);
748 in.ReadIdentifier(action_name);
749 action = StringToAction(action_name);
750 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
751 in.Skip(Token::SEMICOLON);
757 void Keymap::Save(std::ostream &out) {
758 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
759 if (codemap[i] == NONE) continue;
761 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
777 out << " = " << ActionToString(codemap[i]) << std::endl;;
784 std::map<std::string, Keymap::Action> action_map = {
785 { "none", Keymap::NONE },
786 { "move_forward", Keymap::MOVE_FORWARD },
787 { "move_backward", Keymap::MOVE_BACKWARD },
788 { "move_left", Keymap::MOVE_LEFT },
789 { "move_right", Keymap::MOVE_RIGHT },
790 { "move_up", Keymap::MOVE_UP },
791 { "move_down", Keymap::MOVE_DOWN },
793 { "primary", Keymap::PRIMARY },
794 { "secondary", Keymap::SECONDARY },
795 { "tertiary", Keymap::TERTIARY },
797 { "inventory_next", Keymap::INV_NEXT },
798 { "inventory_prev", Keymap::INV_PREVIOUS },
799 { "inventory_1", Keymap::INV_1 },
800 { "inventory_2", Keymap::INV_2 },
801 { "inventory_3", Keymap::INV_3 },
802 { "inventory_4", Keymap::INV_4 },
803 { "inventory_5", Keymap::INV_5 },
804 { "inventory_6", Keymap::INV_6 },
805 { "inventory_7", Keymap::INV_7 },
806 { "inventory_8", Keymap::INV_8 },
807 { "inventory_9", Keymap::INV_9 },
808 { "inventory_10", Keymap::INV_10 },
810 { "toggle_audio", Keymap::TOGGLE_AUDIO },
811 { "toggle_video", Keymap::TOGGLE_VIDEO },
812 { "toggle_hud", Keymap::TOGGLE_HUD },
813 { "toggle_debug", Keymap::TOGGLE_DEBUG },
815 { "exit", Keymap::EXIT },
820 const char *Keymap::ActionToString(Action action) {
821 for (const auto &entry : action_map) {
822 if (action == entry.second) {
823 return entry.first.c_str();
829 Keymap::Action Keymap::StringToAction(const std::string &str) {
830 auto entry = action_map.find(str);
831 if (entry != action_map.end()) {
832 return entry->second;
834 std::cerr << "unknown action \"" << str << '"' << std::endl;