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 "../graphics/Font.hpp"
16 #include "../graphics/Viewport.hpp"
17 #include "../io/TokenStreamReader.hpp"
18 #include "../model/shapes.hpp"
19 #include "../world/BlockLookup.hpp"
20 #include "../world/World.hpp"
21 #include "../world/WorldManipulator.hpp"
28 #include <glm/gtc/matrix_transform.hpp>
29 #include <glm/gtx/rotate_vector.hpp>
30 #include <glm/gtx/io.hpp>
35 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
51 void DirectInput::Update(int dt) {
52 dirty = true; // world has changed in the meantime
55 remove_timer.Update(dt);
56 if (remove_timer.Hit()) {
60 place_timer.Update(dt);
61 if (place_timer.Hit()) {
66 void DirectInput::SetMovement(const glm::vec3 &m) {
67 if (dot(m, m) > 1.0f) {
68 move_dir = normalize(m);
75 void DirectInput::TurnHead(float dp, float dy) {
79 } else if (pitch < -PI / 2) {
85 } else if (yaw < -PI) {
91 void DirectInput::StartPrimaryAction() {
92 if (!remove_timer.Running()) {
98 void DirectInput::StopPrimaryAction() {
102 void DirectInput::StartSecondaryAction() {
103 if (!place_timer.Running()) {
109 void DirectInput::StopSecondaryAction() {
113 void DirectInput::StartTertiaryAction() {
117 void DirectInput::StopTertiaryAction() {
121 void DirectInput::SelectInventory(int) {
124 void DirectInput::UpdatePlayer() {
125 constexpr float max_vel = 0.005f;
127 player.GetEntity().Orientation(glm::quat(glm::vec3(pitch, yaw, 0.0f)));
128 player.GetEntity().Velocity(glm::rotateY(move_dir * max_vel, yaw));
130 Ray aim = player.Aim();
131 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity().ChunkCoords(), aim_world)) {
132 aim_world = WorldCollision();
134 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity(), aim_entity)) {
135 aim_entity = EntityCollision();
137 if (aim_world && aim_entity) {
138 // got both, pick the closest one
139 if (aim_world.depth < aim_entity.depth) {
140 aim_entity = EntityCollision();
142 aim_world = WorldCollision();
145 // TODO: update outline if applicable
150 void DirectInput::PickBlock() {
152 if (!aim_world) return;
153 player.SetInventorySlot(aim_world.GetBlock().type - 1);
156 void DirectInput::PlaceBlock() {
158 if (!aim_world) return;
160 BlockLookup next_block(aim_world.chunk, aim_world.BlockPos(), Block::NormalFace(aim_world.normal));
164 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(player.GetInventorySlot() + 1));
168 void DirectInput::RemoveBlock() {
170 if (!aim_world) return;
171 manip.SetBlock(aim_world.GetChunk(), aim_world.block, Block(0));
176 HUD::HUD(Environment &env, Config &config, const Player &player)
182 , outline_transform(1.0f)
183 , outline_visible(false)
187 , block_transform(1.0f)
189 , block_visible(false)
198 , messages(env.assets.small_ui_font)
203 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
204 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
205 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
206 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
207 block_label.Position(
208 glm::vec3(50.0f, 85.0f, 0.0f),
212 block_label.Foreground(glm::vec4(1.0f));
213 block_label.Background(glm::vec4(0.5f));
216 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
217 counter_text.Foreground(glm::vec4(1.0f));
218 counter_text.Background(glm::vec4(0.5f));
219 position_text.Position(glm::vec3(-25.0f, 25.0f + env.assets.small_ui_font.LineSkip(), 0.0f), Gravity::NORTH_EAST);
220 position_text.Foreground(glm::vec4(1.0f));
221 position_text.Background(glm::vec4(0.5f));
222 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * env.assets.small_ui_font.LineSkip(), 0.0f), Gravity::NORTH_EAST);
223 orientation_text.Foreground(glm::vec4(1.0f));
224 orientation_text.Background(glm::vec4(0.5f));
225 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * env.assets.small_ui_font.LineSkip(), 0.0f), Gravity::NORTH_EAST);
226 block_text.Foreground(glm::vec4(1.0f));
227 block_text.Background(glm::vec4(0.5f));
228 block_text.Set(env.assets.small_ui_font, "Block: none");
229 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * env.assets.small_ui_font.LineSkip(), 0.0f), Gravity::NORTH_EAST);
230 entity_text.Foreground(glm::vec4(1.0f));
231 entity_text.Background(glm::vec4(0.5f));
232 entity_text.Set(env.assets.small_ui_font, "Entity: none");
235 messages.Position(glm::vec3(25.0f, -25.0f, 0.0f), Gravity::SOUTH_WEST);
236 messages.Foreground(glm::vec4(1.0f));
237 messages.Background(glm::vec4(0.5f));
240 OutlineModel::Buffer buf;
241 buf.vertices = std::vector<glm::vec3>({
242 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
243 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
245 buf.indices = std::vector<OutlineModel::Index>({
248 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f });
249 crosshair.Update(buf);
254 OutlineModel::Buffer outl_buf;
258 void HUD::FocusBlock(const Chunk &chunk, int index) {
259 const Block &block = chunk.BlockAt(index);
260 const BlockType &type = chunk.Type(index);
262 type.FillOutlineModel(outl_buf);
263 outline.Update(outl_buf);
264 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
265 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
266 outline_transform *= glm::scale(glm::vec3(1.005f));
267 outline_visible = true;
272 << ", face: " << block.GetFace()
273 << ", turn: " << block.GetTurn();
274 block_text.Set(env.assets.small_ui_font, s.str());
280 void HUD::FocusEntity(const Entity &entity) {
283 s << "Entity: " << entity.Name();
284 entity_text.Set(env.assets.small_ui_font, s.str());
290 void HUD::FocusNone() {
291 outline_visible = false;
296 void HUD::DisplayNone() {
297 block_visible = false;
300 void HUD::Display(const BlockType &type) {
302 type.FillEntityModel(block_buf);
303 block.Update(block_buf);
305 block_label.Set(env.assets.small_ui_font, type.label);
307 block_visible = type.visible;
311 void HUD::UpdateDebug() {
317 void HUD::UpdateCounter() {
319 s << std::setprecision(3) <<
320 "avg: " << env.counter.Average().running << "ms, "
321 "peak: " << env.counter.Peak().running << "ms";
322 std::string text = s.str();
323 counter_text.Set(env.assets.small_ui_font, text);
326 void HUD::UpdatePosition() {
328 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
329 position_text.Set(env.assets.small_ui_font, s.str());
332 void HUD::UpdateOrientation() {
333 //std::stringstream s;
334 //s << std::setprecision(3) << "pitch: " << rad2deg(ctrl.Pitch())
335 // << ", yaw: " << rad2deg(ctrl.Yaw());
336 //orientation_text.Set(env.assets.small_ui_font, s.str());
339 void HUD::PostMessage(const char *msg) {
340 messages.PushLine(msg);
343 std::cout << msg << std::endl;
347 void HUD::Update(int dt) {
348 msg_timer.Update(dt);
349 if (msg_timer.HitOnce()) {
353 if (config.video.debug) {
354 if (env.counter.Changed()) {
362 void HUD::Render(Viewport &viewport) noexcept {
364 if (outline_visible && config.video.world) {
365 PlainColor &outline_prog = viewport.WorldOutlineProgram();
366 outline_prog.SetM(outline_transform);
370 // clear depth buffer so everything renders above the world
371 viewport.ClearDepth();
373 if (config.video.hud) {
376 DirectionalLighting &world_prog = viewport.HUDProgram();
377 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
378 // disable distance fog
379 world_prog.SetFogDensity(0.0f);
381 viewport.DisableBlending();
382 world_prog.SetM(block_transform);
384 block_label.Render(viewport);
388 if (msg_timer.Running()) {
389 messages.Render(viewport);
393 PlainColor &outline_prog = viewport.HUDOutlineProgram();
394 viewport.EnableInvertBlending();
395 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
396 outline_prog.SetM(viewport.Cursor());
401 if (config.video.debug) {
402 counter_text.Render(viewport);
403 position_text.Render(viewport);
404 orientation_text.Render(viewport);
406 block_text.Render(viewport);
407 } else if (show_entity) {
408 entity_text.Render(viewport);
414 InteractiveManipulator::InteractiveManipulator(Environment &env, Entity &player)
417 , place_sound(env.loader.LoadSound("thump"))
418 , remove_sound(env.loader.LoadSound("plop")) {
422 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
423 chunk.SetBlock(index, block);
424 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
425 // TODO: get sound effect from block type
426 if (block.type == 0) {
427 audio.Play(remove_sound, coords);
429 audio.Play(place_sound, coords);
434 Interface::Interface(
436 const Keymap &keymap,
437 PlayerController &pc,
438 ClientController &cc)
451 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
452 if (!config.input.keyboard) return;
454 Keymap::Action action = keymap.Lookup(event);
456 case Keymap::MOVE_FORWARD:
460 case Keymap::MOVE_BACKWARD:
464 case Keymap::MOVE_LEFT:
468 case Keymap::MOVE_RIGHT:
472 case Keymap::MOVE_UP:
476 case Keymap::MOVE_DOWN:
481 case Keymap::PRIMARY:
482 player_ctrl.StartPrimaryAction();
484 case Keymap::SECONDARY:
485 player_ctrl.StartSecondaryAction();
487 case Keymap::TERTIARY:
488 player_ctrl.StartTertiaryAction();
491 case Keymap::INV_NEXT:
494 case Keymap::INV_PREVIOUS:
507 InvAbs(action - Keymap::INV_1);
514 case Keymap::TOGGLE_AUDIO:
515 config.audio.enabled = !config.audio.enabled;
516 client_ctrl.SetAudio(config.audio.enabled);
518 case Keymap::TOGGLE_VIDEO:
519 config.video.world = !config.video.world;
520 client_ctrl.SetVideo(config.video.world);
522 case Keymap::TOGGLE_HUD:
523 config.video.hud = !config.video.hud;
524 client_ctrl.SetHUD(config.video.hud);
526 case Keymap::TOGGLE_DEBUG:
527 config.video.debug = !config.video.debug;
528 client_ctrl.SetDebug(config.video.debug);
536 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
537 if (!config.input.keyboard) return;
539 switch (keymap.Lookup(event)) {
540 case Keymap::MOVE_FORWARD:
544 case Keymap::MOVE_BACKWARD:
548 case Keymap::MOVE_LEFT:
552 case Keymap::MOVE_RIGHT:
556 case Keymap::MOVE_UP:
560 case Keymap::MOVE_DOWN:
565 case Keymap::PRIMARY:
566 player_ctrl.StopPrimaryAction();
568 case Keymap::SECONDARY:
569 player_ctrl.StopSecondaryAction();
571 case Keymap::TERTIARY:
572 player_ctrl.StopTertiaryAction();
580 void Interface::Handle(const SDL_MouseMotionEvent &event) {
581 if (!config.input.mouse) return;
582 player_ctrl.TurnHead(
583 event.yrel * config.input.pitch_sensitivity,
584 event.xrel * config.input.yaw_sensitivity);
587 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
588 if (!config.input.mouse) return;
590 switch (event.button) {
591 case SDL_BUTTON_LEFT:
592 player_ctrl.StartPrimaryAction();
594 case SDL_BUTTON_RIGHT:
595 player_ctrl.StartSecondaryAction();
597 case SDL_BUTTON_MIDDLE:
598 player_ctrl.StartTertiaryAction();
603 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
604 if (!config.input.mouse) return;
606 switch (event.button) {
607 case SDL_BUTTON_LEFT:
608 player_ctrl.StopPrimaryAction();
610 case SDL_BUTTON_RIGHT:
611 player_ctrl.StopSecondaryAction();
613 case SDL_BUTTON_MIDDLE:
614 player_ctrl.StopTertiaryAction();
620 void Interface::Handle(const SDL_MouseWheelEvent &event) {
621 if (!config.input.mouse) return;
625 } else if (event.y > 0) {
630 void Interface::UpdateMovement() {
631 player_ctrl.SetMovement(glm::vec3(fwd - rev));
634 void Interface::InvAbs(int s) {
635 slot = s % num_slots;
641 void Interface::InvRel(int delta) {
642 InvAbs(slot + delta);
651 void Keymap::Map(SDL_Scancode scancode, Action action) {
652 if (scancode > MAX_SCANCODE) {
653 throw std::runtime_error("refusing to map scancode: too damn high");
655 codemap[scancode] = action;
658 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
659 if (scancode < NUM_SCANCODES) {
660 return codemap[scancode];
667 void Keymap::LoadDefault() {
668 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
669 Map(SDL_SCANCODE_W, MOVE_FORWARD);
670 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
671 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
672 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
673 Map(SDL_SCANCODE_A, MOVE_LEFT);
674 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
675 Map(SDL_SCANCODE_D, MOVE_RIGHT);
676 Map(SDL_SCANCODE_SPACE, MOVE_UP);
677 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
678 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
679 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
680 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
682 Map(SDL_SCANCODE_TAB, INV_NEXT);
683 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
684 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
685 Map(SDL_SCANCODE_1, INV_1);
686 Map(SDL_SCANCODE_2, INV_2);
687 Map(SDL_SCANCODE_3, INV_3);
688 Map(SDL_SCANCODE_4, INV_4);
689 Map(SDL_SCANCODE_5, INV_5);
690 Map(SDL_SCANCODE_6, INV_6);
691 Map(SDL_SCANCODE_7, INV_7);
692 Map(SDL_SCANCODE_8, INV_8);
693 Map(SDL_SCANCODE_9, INV_9);
694 Map(SDL_SCANCODE_0, INV_10);
696 Map(SDL_SCANCODE_INSERT, SECONDARY);
697 Map(SDL_SCANCODE_RETURN, SECONDARY);
698 Map(SDL_SCANCODE_MENU, TERTIARY);
699 Map(SDL_SCANCODE_DELETE, PRIMARY);
700 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
702 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
703 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
704 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
705 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
707 Map(SDL_SCANCODE_ESCAPE, EXIT);
711 void Keymap::Load(std::istream &is) {
712 TokenStreamReader in(is);
713 std::string key_name;
714 std::string action_name;
717 while (in.HasMore()) {
718 if (in.Peek().type == Token::STRING) {
719 in.ReadString(key_name);
720 key = SDL_GetScancodeFromName(key_name.c_str());
722 key = SDL_Scancode(in.GetInt());
724 in.Skip(Token::EQUALS);
725 in.ReadIdentifier(action_name);
726 action = StringToAction(action_name);
727 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
728 in.Skip(Token::SEMICOLON);
734 void Keymap::Save(std::ostream &out) {
735 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
736 if (codemap[i] == NONE) continue;
738 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
754 out << " = " << ActionToString(codemap[i]) << std::endl;;
761 std::map<std::string, Keymap::Action> action_map = {
762 { "none", Keymap::NONE },
763 { "move_forward", Keymap::MOVE_FORWARD },
764 { "move_backward", Keymap::MOVE_BACKWARD },
765 { "move_left", Keymap::MOVE_LEFT },
766 { "move_right", Keymap::MOVE_RIGHT },
767 { "move_up", Keymap::MOVE_UP },
768 { "move_down", Keymap::MOVE_DOWN },
770 { "primary", Keymap::PRIMARY },
771 { "secondary", Keymap::SECONDARY },
772 { "tertiary", Keymap::TERTIARY },
774 { "inventory_next", Keymap::INV_NEXT },
775 { "inventory_prev", Keymap::INV_PREVIOUS },
776 { "inventory_1", Keymap::INV_1 },
777 { "inventory_2", Keymap::INV_2 },
778 { "inventory_3", Keymap::INV_3 },
779 { "inventory_4", Keymap::INV_4 },
780 { "inventory_5", Keymap::INV_5 },
781 { "inventory_6", Keymap::INV_6 },
782 { "inventory_7", Keymap::INV_7 },
783 { "inventory_8", Keymap::INV_8 },
784 { "inventory_9", Keymap::INV_9 },
785 { "inventory_10", Keymap::INV_10 },
787 { "toggle_audio", Keymap::TOGGLE_AUDIO },
788 { "toggle_video", Keymap::TOGGLE_VIDEO },
789 { "toggle_hud", Keymap::TOGGLE_HUD },
790 { "toggle_debug", Keymap::TOGGLE_DEBUG },
792 { "exit", Keymap::EXIT },
797 const char *Keymap::ActionToString(Action action) {
798 for (const auto &entry : action_map) {
799 if (action == entry.second) {
800 return entry.first.c_str();
806 Keymap::Action Keymap::StringToAction(const std::string &str) {
807 auto entry = action_map.find(str);
808 if (entry != action_map.end()) {
809 return entry->second;
811 std::cerr << "unknown action \"" << str << '"' << std::endl;