game_dispatch.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // game_dispatch.cpp
  3. // gameutils
  4. //
  5. // Created by Sam Jaffe on 9/2/16.
  6. //
  7. #include <thread>
  8. #include "game_dispatch.hpp"
  9. #include "events.hpp"
  10. #include "scene.hpp"
  11. namespace engine {
  12. namespace {
  13. event::event_type mask( event::event_type t, bool pressed ) {
  14. return static_cast<event::event_type>( t | ( pressed ? event::PRESSED_MASK : event::RELEASED_MASK ) );
  15. }
  16. }
  17. game_dispatch::game_dispatch( )
  18. : screen_size( { 1920.f, 1080.f } )
  19. , minimum_frame_duration( engine::FPS60 )
  20. , scenes( )
  21. , current_timestamp( clock::now( ) )
  22. , curr_scene( ) {
  23. }
  24. game_dispatch::current_scene_info::current_scene_info( ) {
  25. }
  26. game_dispatch::current_scene_info::current_scene_info( scene * curr )
  27. : ptr( curr )
  28. , current_scene_id( ptr->id )
  29. , local_size( ptr->get_size( ) ) {
  30. }
  31. void game_dispatch::process_key_event( raw_key_t key, bool press ) {
  32. if ( ! curr_scene.is_keyboard_event ) return;
  33. auto const & binding = curr_scene.ptr->get_binding( );
  34. auto it = binding.find( key );
  35. if ( it == binding.end( ) ) return;
  36. curr_scene.ptr->handle_key_event( {
  37. it->second,
  38. mask( event::KEY_MASK, press )
  39. } );
  40. }
  41. void game_dispatch::process_mouse_event( math::vec2 mouse_pos, bool press ) {
  42. if ( ! curr_scene.is_mouse_event ) return;
  43. math::vec2 local_scene_position = mouse_pos * curr_scene.local_size / screen_size;
  44. curr_scene.ptr->handle_mouse_event( {
  45. local_scene_position,
  46. mask( event::MOUSE_MASK, press )
  47. } );
  48. }
  49. tick game_dispatch::get_tick( ) {
  50. timestamp now = clock::now( );
  51. return { now, now - current_timestamp };
  52. }
  53. tick game_dispatch::next_frame( ) {
  54. tick t = get_tick( );
  55. while ( t.since < minimum_frame_duration ) {
  56. std::this_thread::sleep_for( minimum_frame_duration - t.since );
  57. t = get_tick( );
  58. }
  59. current_timestamp = t.now;
  60. return t;
  61. }
  62. void game_dispatch::gameloop( ) try {
  63. while ( running ) { single_frame( next_frame( ) ); }
  64. cleanup_resources( );
  65. exit( EXIT_SUCCESS );
  66. } catch ( std::exception const & ex ) {
  67. // todo: logging
  68. exit( EXIT_FAILURE );
  69. }
  70. void game_dispatch::quit( ) {
  71. running = false;
  72. }
  73. }