GameEngine.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. * GameEngine.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "GameEngine.h"
  12. #include "GameLibrary.h"
  13. #include "Discord.h"
  14. #include "gui/CIntObject.h"
  15. #include "gui/CursorHandler.h"
  16. #include "gui/ShortcutHandler.h"
  17. #include "gui/FramerateManager.h"
  18. #include "gui/WindowHandler.h"
  19. #include "gui/EventDispatcher.h"
  20. #include "eventsSDL/InputHandler.h"
  21. #include "media/CMusicHandler.h"
  22. #include "media/CSoundHandler.h"
  23. #include "media/CVideoHandler.h"
  24. #include "media/CEmptyVideoPlayer.h"
  25. #include "adventureMap/AdventureMapInterface.h"
  26. #include "render/Canvas.h"
  27. #include "render/Colors.h"
  28. #include "render/IFont.h"
  29. #include "render/EFont.h"
  30. #include "renderSDL/ScreenHandler.h"
  31. #include "renderSDL/RenderHandler.h"
  32. #include "GameEngineUser.h"
  33. #include "battle/BattleInterface.h"
  34. #include "../lib/AsyncRunner.h"
  35. #include "../lib/CConfigHandler.h"
  36. #include "../lib/texts/TextOperations.h"
  37. #include "../lib/texts/CGeneralTextHandler.h"
  38. #include <SDL_render.h>
  39. std::unique_ptr<GameEngine> ENGINE;
  40. static thread_local bool inGuiThread = false;
  41. ObjectConstruction::ObjectConstruction(CIntObject *obj)
  42. {
  43. ENGINE->createdObj.push_front(obj);
  44. ENGINE->captureChildren = true;
  45. }
  46. ObjectConstruction::~ObjectConstruction()
  47. {
  48. assert(!ENGINE->createdObj.empty());
  49. ENGINE->createdObj.pop_front();
  50. ENGINE->captureChildren = !ENGINE->createdObj.empty();
  51. }
  52. GameEngine::GameEngine()
  53. : captureChildren(false)
  54. , fakeStatusBar(std::make_shared<EmptyStatusBar>())
  55. {
  56. inGuiThread = true;
  57. eventDispatcherInstance = std::make_unique<EventDispatcher>();
  58. windowHandlerInstance = std::make_unique<WindowHandler>();
  59. screenHandlerInstance = std::make_unique<ScreenHandler>();
  60. renderHandlerInstance = std::make_unique<RenderHandler>();
  61. shortcutsHandlerInstance = std::make_unique<ShortcutHandler>();
  62. inputHandlerInstance = std::make_unique<InputHandler>(); // Must be after windowHandlerInstance and shortcutsHandlerInstance
  63. framerateManagerInstance = std::make_unique<FramerateManager>(settings["video"]["targetfps"].Integer());
  64. discordInstance = std::make_unique<Discord>();
  65. #ifndef ENABLE_VIDEO
  66. videoPlayerInstance = std::make_unique<CEmptyVideoPlayer>();
  67. #else
  68. if (settings["session"]["disableVideo"].Bool())
  69. videoPlayerInstance = std::make_unique<CEmptyVideoPlayer>();
  70. else
  71. videoPlayerInstance = std::make_unique<CVideoPlayer>();
  72. #endif
  73. soundPlayerInstance = std::make_unique<CSoundHandler>();
  74. musicPlayerInstance = std::make_unique<CMusicHandler>();
  75. sound().setVolume(settings["general"]["sound"].Integer());
  76. music().setVolume(settings["general"]["music"].Integer());
  77. cursorHandlerInstance = std::make_unique<CursorHandler>();
  78. asyncTasks = std::make_unique<AsyncRunner>();
  79. }
  80. void GameEngine::handleEvents()
  81. {
  82. events().dispatchTimer(framerate().getElapsedMilliseconds());
  83. //player interface may want special event handling
  84. if(engineUser->capturedAllEvents())
  85. return;
  86. input().processEvents();
  87. }
  88. void GameEngine::fakeMouseMove()
  89. {
  90. dispatchMainThread([](){
  91. ENGINE->events().dispatchMouseMoved(Point(0, 0), ENGINE->getCursorPosition());
  92. });
  93. }
  94. [[noreturn]] void GameEngine::mainLoop()
  95. {
  96. for (;;)
  97. {
  98. input().fetchEvents();
  99. updateFrame();
  100. screenHandlerInstance->presentScreenTexture();
  101. framerate().framerateDelay(); // holds a constant FPS
  102. }
  103. }
  104. void GameEngine::updateFrame()
  105. {
  106. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  107. engineUser->onUpdate();
  108. handleEvents();
  109. windows().simpleRedraw();
  110. if (settings["video"]["performanceOverlay"]["show"].Bool())
  111. drawPerformanceOverlay();
  112. screenHandlerInstance->updateScreenTexture();
  113. windows().onFrameRendered();
  114. ENGINE->cursor().update();
  115. }
  116. GameEngine::~GameEngine()
  117. {
  118. // enforce deletion order on shutdown
  119. // all UI elements including adventure map must be destroyed before Gui Handler
  120. // proper solution would be removal of adventureInt global
  121. adventureInt.reset();
  122. }
  123. ShortcutHandler & GameEngine::shortcuts()
  124. {
  125. assert(shortcutsHandlerInstance);
  126. return *shortcutsHandlerInstance;
  127. }
  128. FramerateManager & GameEngine::framerate()
  129. {
  130. assert(framerateManagerInstance);
  131. return *framerateManagerInstance;
  132. }
  133. bool GameEngine::isKeyboardCtrlDown() const
  134. {
  135. return inputHandlerInstance->isKeyboardCtrlDown();
  136. }
  137. bool GameEngine::isKeyboardCmdDown() const
  138. {
  139. return inputHandlerInstance->isKeyboardCmdDown();
  140. }
  141. bool GameEngine::isKeyboardAltDown() const
  142. {
  143. return inputHandlerInstance->isKeyboardAltDown();
  144. }
  145. bool GameEngine::isKeyboardShiftDown() const
  146. {
  147. return inputHandlerInstance->isKeyboardShiftDown();
  148. }
  149. const Point & GameEngine::getCursorPosition() const
  150. {
  151. return inputHandlerInstance->getCursorPosition();
  152. }
  153. Point GameEngine::screenDimensions() const
  154. {
  155. return screenHandlerInstance->getLogicalResolution();
  156. }
  157. void GameEngine::drawPerformanceOverlay()
  158. {
  159. auto font = EFonts::FONT_SMALL;
  160. const auto & fontPtr = ENGINE->renderHandler().loadFont(font);
  161. Canvas target = screenHandler().getScreenCanvas();
  162. auto powerState = ENGINE->input().getPowerState();
  163. std::string powerSymbol = ""; // add symbol if emoji are supported (e.g. VCMI extras)
  164. if(powerState.powerState == PowerStateMode::ON_BATTERY)
  165. powerSymbol = fontPtr->canRepresentCharacter("🔋") ? "🔋 " : (LIBRARY->generaltexth->translate("vcmi.overlay.battery") + " ");
  166. else if(powerState.powerState == PowerStateMode::CHARGING)
  167. powerSymbol = fontPtr->canRepresentCharacter("🔌") ? "🔌 " : (LIBRARY->generaltexth->translate("vcmi.overlay.charging") + " ");
  168. std::string fps = std::to_string(framerate().getFramerate())+" FPS";
  169. std::string time = TextOperations::getFormattedTimeLocal(std::time(nullptr));
  170. std::string power = powerState.powerState == PowerStateMode::UNKNOWN ? "" : powerSymbol + std::to_string(powerState.percent) + "%";
  171. std::string textToDisplay = time + (power.empty() ? "" : " | " + power) + " | " + fps;
  172. maxPerformanceOverlayTextWidth = std::max(maxPerformanceOverlayTextWidth, static_cast<int>(fontPtr->getStringWidth(textToDisplay))); // do not get smaller (can cause graphical glitches)
  173. Rect targetArea;
  174. std::string edge = settings["video"]["performanceOverlay"]["edge"].String();
  175. int marginTopBottom = settings["video"]["performanceOverlay"]["marginTopBottom"].Integer();
  176. int marginLeftRight = settings["video"]["performanceOverlay"]["marginLeftRight"].Integer();
  177. Point boxSize(maxPerformanceOverlayTextWidth + 6, fontPtr->getLineHeight() + 2);
  178. if (edge == "topleft")
  179. targetArea = Rect(marginLeftRight, marginTopBottom, boxSize.x, boxSize.y);
  180. else if (edge == "topright")
  181. targetArea = Rect(screenDimensions().x - marginLeftRight - boxSize.x, marginTopBottom, boxSize.x, boxSize.y);
  182. else if (edge == "bottomleft")
  183. targetArea = Rect(marginLeftRight, screenDimensions().y - marginTopBottom - boxSize.y, boxSize.x, boxSize.y);
  184. else if (edge == "bottomright")
  185. targetArea = Rect(screenDimensions().x - marginLeftRight - boxSize.x, screenDimensions().y - marginTopBottom - boxSize.y, boxSize.x, boxSize.y);
  186. target.drawColor(targetArea.resize(1), Colors::BRIGHT_YELLOW);
  187. target.drawColor(targetArea, ColorRGBA(0, 0, 0));
  188. target.drawText(targetArea.center(), font, Colors::WHITE, ETextAlignment::CENTER, textToDisplay);
  189. }
  190. bool GameEngine::amIGuiThread()
  191. {
  192. return inGuiThread;
  193. }
  194. void GameEngine::dispatchMainThread(const std::function<void()> & functor)
  195. {
  196. inputHandlerInstance->dispatchMainThread(functor);
  197. }
  198. IScreenHandler & GameEngine::screenHandler()
  199. {
  200. return *screenHandlerInstance;
  201. }
  202. IRenderHandler & GameEngine::renderHandler()
  203. {
  204. return *renderHandlerInstance;
  205. }
  206. EventDispatcher & GameEngine::events()
  207. {
  208. return *eventDispatcherInstance;
  209. }
  210. InputHandler & GameEngine::input()
  211. {
  212. return *inputHandlerInstance;
  213. }
  214. WindowHandler & GameEngine::windows()
  215. {
  216. assert(windowHandlerInstance);
  217. return *windowHandlerInstance;
  218. }
  219. std::shared_ptr<IStatusBar> GameEngine::statusbar()
  220. {
  221. auto locked = currentStatusBar.lock();
  222. if (!locked)
  223. return fakeStatusBar;
  224. return locked;
  225. }
  226. void GameEngine::setStatusbar(const std::shared_ptr<IStatusBar> & newStatusBar)
  227. {
  228. currentStatusBar = newStatusBar;
  229. }
  230. void GameEngine::onScreenResize(bool resolutionChanged, bool windowResized)
  231. {
  232. if(resolutionChanged)
  233. if(!screenHandler().onScreenResize(windowResized))
  234. return;
  235. windows().onScreenResize();
  236. ENGINE->cursor().onScreenResize();
  237. }
  238. void GameEngine::setEngineUser(IGameEngineUser * user)
  239. {
  240. engineUser = user;
  241. }