game_dispatch.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // game_dispatch.cpp
  3. // gameutils
  4. //
  5. // Created by Sam Jaffe on 9/2/16.
  6. //
  7. #include <thread>
  8. #include "game/engine/game_dispatch.hpp"
  9. #include "game/engine/events.hpp"
  10. #include "game/engine/scene.hpp"
  11. #include "game/util/env.hpp"
  12. namespace engine {
  13. namespace {
  14. event::event_type mask(event::event_type t, bool pressed) {
  15. return static_cast<event::event_type>(
  16. t | (pressed ? event::PRESSED_MASK : event::RELEASED_MASK));
  17. }
  18. }
  19. game_dispatch::game_dispatch()
  20. : screen_size(env::screen_size()),
  21. minimum_frame_duration(engine::fps::v60), scenes(),
  22. current_timestamp(clock::now()), curr_scene() {}
  23. game_dispatch::current_scene_info::current_scene_info() {}
  24. game_dispatch::current_scene_info::current_scene_info(scene * curr)
  25. : ptr(curr), current_scene_id(ptr->id), local_size(ptr->size()) {}
  26. void game_dispatch::process_key_event(raw_key_t key, bool press) {
  27. if (!curr_scene.is_keyboard_event) return;
  28. auto const & binding = curr_scene.ptr->keys();
  29. auto it = binding.find(key);
  30. if (it == binding.end()) return;
  31. curr_scene.ptr->handle_key_event(
  32. {it->second, mask(event::KEY_MASK, press)});
  33. }
  34. void game_dispatch::process_mouse_event(math::vec2 mouse_pos, bool press) {
  35. if (!curr_scene.is_mouse_event) return;
  36. math::vec2 local_scene_position =
  37. mouse_pos * curr_scene.local_size / screen_size;
  38. curr_scene.ptr->handle_mouse_event(
  39. {local_scene_position, mask(event::MOUSE_MASK, press)});
  40. }
  41. tick game_dispatch::get_tick() {
  42. timestamp now = clock::now();
  43. return {now, now - current_timestamp};
  44. }
  45. float game_dispatch::next_frame() {
  46. tick t = get_tick();
  47. while (t.since < minimum_frame_duration) {
  48. std::this_thread::sleep_for(minimum_frame_duration - t.since);
  49. t = get_tick();
  50. }
  51. current_timestamp = t.now;
  52. return std::chrono::duration<float>(t.since).count();
  53. }
  54. void game_dispatch::update() { curr_scene.ptr->update(next_frame()); }
  55. void game_dispatch::render() { curr_scene.ptr->render(); }
  56. }