// // game_dispatch.cpp // gameutils // // Created by Sam Jaffe on 9/2/16. // #include #include "game/engine/game_dispatch.hpp" #include "game/engine/events.hpp" #include "game/engine/scene.hpp" #include "game/graphics/object.hpp" #include "game/graphics/renderer.hpp" #include "game/util/env.hpp" namespace engine { namespace { event::event_type mask(event::event_type t, bool pressed) { return static_cast( t | (pressed ? event::PRESSED_MASK : event::RELEASED_MASK)); } } game_dispatch::game_dispatch(std::shared_ptr renderer) : renderer(renderer), screen_size(env::screen_size()), minimum_frame_duration(env::fps::v60), counter(minimum_frame_duration), scenes(), current_timestamp(env::clock::now()), curr_scene() {} game_dispatch::current_scene_info::current_scene_info() {} game_dispatch::current_scene_info::current_scene_info(scene * curr) : ptr(curr), current_scene_id(ptr->id), local_size(ptr->size()) {} void game_dispatch::process_key_event(raw_key_t key, bool press) { if (!curr_scene.is_keyboard_event) return; auto const & binding = curr_scene.ptr->keys(); auto it = binding.find(key); if (it == binding.end()) return; curr_scene.ptr->handle_key_event( {it->second, mask(event::KEY_MASK, press)}); } void game_dispatch::process_mouse_event(math::vec2 mouse_pos, bool press) { if (!curr_scene.is_mouse_event) return; math::vec2 local_scene_position = mouse_pos * curr_scene.local_size / screen_size; curr_scene.ptr->handle_mouse_event( {local_scene_position, mask(event::MOUSE_MASK, press)}); } env::clock::tick game_dispatch::next_frame() { env::clock::tick t(current_timestamp); while (t.since < minimum_frame_duration) { std::this_thread::sleep_for(minimum_frame_duration - t.since); t = env::clock::tick(current_timestamp); } current_timestamp = t.now; return t; } void game_dispatch::update() { env::clock::tick t = next_frame(); counter.set_frame_step(t.since); // curr_scene.ptr->update(std::chrono::duration(t.since).count()); } void game_dispatch::render() { graphics::batch_renderer batch(renderer.get()); for (auto & obj : counter.glyphs()) { batch.draw(obj); } // curr_scene.ptr->render(batch); } }