/* * FarmlandsGame.cpp * * Created on: Nov 7, 2016 * Author: tibi */ #include #include #include #include #include #include #include #include #include using namespace farmlands::graphics; using namespace farmlands::graphics::backend; using namespace farmlands::resources; namespace farmlands { namespace controller { FarmlandsGame::FarmlandsGame() : m_running(true), m_time(0) { } bool FarmlandsGame::initialize() { bool ok = true; // Initialize render system ok &= SdlRenderer::instance().initialize(&GameState::current().renderContext); if (!ok) return false; // Initialize & load resources ResourceManager::instance().initialize(); ResourceManager::instance().loadGame(); GameState::current().renderContext.viewport.pixelsPerUnitX = GameState::current().scene->cellWidth; GameState::current().renderContext.viewport.pixelsPerUnitY = GameState::current().scene->cellHeight; // Finish initialization GameState::current().scene->root.onInitialize(); GameState::current().gameInitialized = true; return true; } void FarmlandsGame::onUpdateLogic() { GameState::current().scene->root.onUpdateLogic(); } void FarmlandsGame::onPreRender() { GameState::current().scene->root.onPreRender(); SdlRenderer::instance().renderBegin(); } void FarmlandsGame::onRender() { GameState::current().scene->root.onRender(); } void FarmlandsGame::onEvent(SDL_Event& event) { // Let controllers handle event if (GameState::current().scene->root.onEvent(event)) return; // Nobody? Handle global events switch(event.type) { case SDL_QUIT: stop(); break; case SDL_KEYDOWN: if (event.key.keysym.scancode == SDL_Scancode::SDL_SCANCODE_ESCAPE) stop(); break; case SDL_WINDOWEVENT_RESIZED: break; } } void FarmlandsGame::onPostRender() { SdlRenderer::instance().renderEnd(); GameState::current().scene->root.onPostRender(); } void FarmlandsGame::stop() { m_running = false; GameState::current().scene->root.onDestroy(); } int FarmlandsGame::run() { // Initialize game if (!initialize()) return 1; // Main loop while(m_running) { // Update elapsed time Uint32 now = SDL_GetTicks(); GameState::current().elapsedTime = (now - m_time) * 0.001f; m_time = now; SDL_Event event; while (SDL_PollEvent(&event)) onEvent(event); onUpdateLogic(); onPreRender(); onRender(); onPostRender(); } // Cleanup return 0; } } }