WindowHandler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /*
  2. * WindowHandler.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 "WindowHandler.h"
  12. #include "../../lib/CConfigHandler.h"
  13. #include "../gui/CGuiHandler.h"
  14. #include "../gui/NotificationHandler.h"
  15. #include "CMT.h"
  16. #include "SDL_Extensions.h"
  17. #ifdef VCMI_ANDROID
  18. #include "../lib/CAndroidVMHelper.h"
  19. #endif
  20. #include <SDL.h>
  21. SDL_Window * mainWindow = nullptr;
  22. SDL_Renderer * mainRenderer = nullptr;
  23. SDL_Texture * screenTexture = nullptr;
  24. SDL_Surface * screen = nullptr; //main screen surface
  25. SDL_Surface * screen2 = nullptr; //and hlp surface (used to store not-active interfaces layer)
  26. SDL_Surface * screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  27. static const std::string NAME_AFFIX = "client";
  28. static const std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  29. std::tuple<double, double> WindowHandler::getSupportedScalingRange() const
  30. {
  31. // H3 resolution, any resolution smaller than that is not correctly supported
  32. static const Point minResolution = {800, 600};
  33. // arbitrary limit on *downscaling*. Allow some downscaling, if requested by user. Should be generally limited to 100+ for all but few devices
  34. static const double minimalScaling = 50;
  35. Point renderResolution = getPreferredRenderingResolution();
  36. double maximalScalingWidth = 100.0 * renderResolution.x / minResolution.x;
  37. double maximalScalingHeight = 100.0 * renderResolution.y / minResolution.y;
  38. double maximalScaling = std::min(maximalScalingWidth, maximalScalingHeight);
  39. return { minimalScaling, maximalScaling };
  40. }
  41. Point WindowHandler::getPreferredLogicalResolution() const
  42. {
  43. Point renderResolution = getPreferredRenderingResolution();
  44. auto [minimalScaling, maximalScaling] = getSupportedScalingRange();
  45. double userScaling = settings["video"]["resolution"]["scaling"].Float();
  46. double scaling = std::clamp(userScaling, minimalScaling, maximalScaling);
  47. Point logicalResolution = renderResolution * 100.0 / scaling;
  48. return logicalResolution;
  49. }
  50. Point WindowHandler::getPreferredRenderingResolution() const
  51. {
  52. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_WINDOWED)
  53. {
  54. SDL_Rect bounds;
  55. SDL_GetDisplayBounds(getPreferredDisplayIndex(), &bounds);
  56. return Point(bounds.w, bounds.h);
  57. }
  58. else
  59. {
  60. const JsonNode & video = settings["video"];
  61. int width = video["resolution"]["width"].Integer();
  62. int height = video["resolution"]["height"].Integer();
  63. return Point(width, height);
  64. }
  65. }
  66. int WindowHandler::getPreferredDisplayIndex() const
  67. {
  68. #ifdef VCMI_MOBILE
  69. // Assuming no multiple screens on Android / ios?
  70. return 0;
  71. #else
  72. if (mainWindow != nullptr)
  73. return SDL_GetWindowDisplayIndex(mainWindow);
  74. else
  75. return settings["video"]["displayIndex"].Integer();
  76. #endif
  77. }
  78. EWindowMode WindowHandler::getPreferredWindowMode() const
  79. {
  80. #ifdef VCMI_MOBILE
  81. // On Android / ios game will always render to screen size
  82. return EWindowMode::FULLSCREEN_WINDOWED;
  83. #else
  84. const JsonNode & video = settings["video"];
  85. bool fullscreen = video["fullscreen"].Bool();
  86. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  87. if (!fullscreen)
  88. return EWindowMode::WINDOWED;
  89. if (realFullscreen)
  90. return EWindowMode::FULLSCREEN_TRUE;
  91. else
  92. return EWindowMode::FULLSCREEN_WINDOWED;
  93. #endif
  94. }
  95. WindowHandler::WindowHandler()
  96. {
  97. if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE))
  98. {
  99. logGlobal->error("Something was wrong: %s", SDL_GetError());
  100. exit(-1);
  101. }
  102. const auto & logCallback = [](void * userdata, int category, SDL_LogPriority priority, const char * message)
  103. {
  104. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  105. };
  106. SDL_LogSetOutputFunction(logCallback, nullptr);
  107. #ifdef VCMI_ANDROID
  108. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  109. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  110. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  111. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  112. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  113. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  114. #endif // VCMI_ANDROID
  115. validateSettings();
  116. recreateWindow();
  117. }
  118. bool WindowHandler::recreateWindow()
  119. {
  120. destroyScreen();
  121. if(mainWindow == nullptr)
  122. initializeRenderer();
  123. else
  124. updateFullscreenState();
  125. initializeScreen();
  126. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  127. {
  128. NotificationHandler::init(mainWindow);
  129. }
  130. return true;
  131. }
  132. void WindowHandler::updateFullscreenState()
  133. {
  134. #if !defined(VCMI_MOBILE)
  135. int displayIndex = getPreferredDisplayIndex();
  136. switch(getPreferredWindowMode())
  137. {
  138. case EWindowMode::FULLSCREEN_TRUE:
  139. {
  140. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  141. SDL_DisplayMode mode;
  142. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  143. Point resolution = getPreferredRenderingResolution();
  144. mode.w = resolution.x;
  145. mode.h = resolution.y;
  146. SDL_SetWindowDisplayMode(mainWindow, &mode);
  147. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  148. return;
  149. }
  150. case EWindowMode::FULLSCREEN_WINDOWED:
  151. {
  152. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  153. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  154. return;
  155. }
  156. case EWindowMode::WINDOWED:
  157. {
  158. Point resolution = getPreferredRenderingResolution();
  159. SDL_SetWindowFullscreen(mainWindow, 0);
  160. SDL_SetWindowSize(mainWindow, resolution.x, resolution.y);
  161. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  162. return;
  163. }
  164. }
  165. #endif
  166. }
  167. void WindowHandler::initializeRenderer()
  168. {
  169. mainWindow = createWindow();
  170. if(mainWindow == nullptr)
  171. throw std::runtime_error("Unable to create window\n");
  172. //create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
  173. mainRenderer = SDL_CreateRenderer(mainWindow, getPreferredRenderingDriver(), 0);
  174. if(mainRenderer == nullptr)
  175. throw std::runtime_error("Unable to create renderer\n");
  176. SDL_RendererInfo info;
  177. SDL_GetRendererInfo(mainRenderer, &info);
  178. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  179. logGlobal->info("Created renderer %s", info.name);
  180. }
  181. void WindowHandler::initializeScreen()
  182. {
  183. #ifdef VCMI_ENDIAN_BIG
  184. int bmask = 0xff000000;
  185. int gmask = 0x00ff0000;
  186. int rmask = 0x0000ff00;
  187. int amask = 0x000000ff;
  188. #else
  189. int bmask = 0x000000ff;
  190. int gmask = 0x0000ff00;
  191. int rmask = 0x00ff0000;
  192. int amask = 0xFF000000;
  193. #endif
  194. auto logicalSize = getPreferredLogicalResolution();
  195. SDL_RenderSetLogicalSize(mainRenderer, logicalSize.x, logicalSize.y);
  196. screen = SDL_CreateRGBSurface(0, logicalSize.x, logicalSize.y, 32, rmask, gmask, bmask, amask);
  197. if(nullptr == screen)
  198. {
  199. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", logicalSize.x, logicalSize.y, 32, SDL_GetError());
  200. throw std::runtime_error("Unable to create surface");
  201. }
  202. //No blending for screen itself. Required for proper cursor rendering.
  203. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  204. screenTexture = SDL_CreateTexture(mainRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, logicalSize.x, logicalSize.y);
  205. if(nullptr == screenTexture)
  206. {
  207. logGlobal->error("Unable to create screen texture");
  208. logGlobal->error(SDL_GetError());
  209. throw std::runtime_error("Unable to create screen texture");
  210. }
  211. screen2 = CSDL_Ext::copySurface(screen);
  212. if(nullptr == screen2)
  213. {
  214. throw std::runtime_error("Unable to copy surface\n");
  215. }
  216. screenBuf = screen;
  217. clearScreen();
  218. }
  219. SDL_Window * WindowHandler::createWindowImpl(Point dimensions, int flags, bool center)
  220. {
  221. int displayIndex = getPreferredDisplayIndex();
  222. int positionFlags = center ? SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex) : SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex);
  223. return SDL_CreateWindow(NAME.c_str(), positionFlags, positionFlags, dimensions.x, dimensions.y, flags);
  224. }
  225. SDL_Window * WindowHandler::createWindow()
  226. {
  227. #ifndef VCMI_MOBILE
  228. Point dimensions = getPreferredRenderingResolution();
  229. switch(getPreferredWindowMode())
  230. {
  231. case EWindowMode::FULLSCREEN_TRUE:
  232. return createWindowImpl(dimensions, SDL_WINDOW_FULLSCREEN, false);
  233. case EWindowMode::FULLSCREEN_WINDOWED:
  234. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN_DESKTOP, false);
  235. case EWindowMode::WINDOWED:
  236. return createWindowImpl(dimensions, 0, true);
  237. default:
  238. return nullptr;
  239. };
  240. #endif
  241. #ifdef VCMI_IOS
  242. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  243. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  244. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  245. uint32_t windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  246. SDL_Window * result = createWindowImpl(Point(), windowFlags | SDL_WINDOW_METAL, false);
  247. if(result != nullptr)
  248. return result;
  249. logGlobal->warn("Metal unavailable, using OpenGLES");
  250. return createWindowImpl(Point(), windowFlags, false);
  251. #endif
  252. #ifdef VCMI_ANDROID
  253. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN, false);
  254. #endif
  255. }
  256. void WindowHandler::onScreenResize()
  257. {
  258. if(!recreateWindow())
  259. {
  260. //will return false and report error if video mode is not supported
  261. return;
  262. }
  263. GH.onScreenResize();
  264. }
  265. void WindowHandler::validateSettings()
  266. {
  267. #if !defined(VCMI_MOBILE)
  268. {
  269. int displayIndex = settings["video"]["displayIndex"].Integer();
  270. int displaysCount = SDL_GetNumVideoDisplays();
  271. if (displayIndex >= displaysCount)
  272. {
  273. Settings writer = settings.write["video"]["displayIndex"];
  274. writer->Float() = 0;
  275. }
  276. }
  277. if (getPreferredWindowMode() == EWindowMode::WINDOWED)
  278. {
  279. //we only check that our desired window size fits on screen
  280. int displayIndex = getPreferredDisplayIndex();
  281. Point resolution = getPreferredRenderingResolution();
  282. SDL_DisplayMode mode;
  283. if (SDL_GetDesktopDisplayMode(displayIndex, &mode) == 0)
  284. {
  285. if(resolution.x > mode.w || resolution.y > mode.h)
  286. {
  287. Settings writer = settings.write["video"]["resolution"];
  288. writer["width"].Float() = mode.w;
  289. writer["height"].Float() = mode.h;
  290. }
  291. }
  292. }
  293. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_TRUE)
  294. {
  295. // TODO: check that display supports selected resolution
  296. }
  297. #endif
  298. }
  299. int WindowHandler::getPreferredRenderingDriver() const
  300. {
  301. int result = -1;
  302. const JsonNode & video = settings["video"];
  303. int driversCount = SDL_GetNumRenderDrivers();
  304. std::string preferredDriverName = video["driver"].String();
  305. logGlobal->info("Found %d render drivers", driversCount);
  306. for(int it = 0; it < driversCount; it++)
  307. {
  308. SDL_RendererInfo info;
  309. SDL_GetRenderDriverInfo(it, &info);
  310. std::string driverName(info.name);
  311. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  312. {
  313. result = it;
  314. logGlobal->info("\t%s (active)", driverName);
  315. }
  316. else
  317. logGlobal->info("\t%s", driverName);
  318. }
  319. return result;
  320. }
  321. void WindowHandler::destroyScreen()
  322. {
  323. screenBuf = nullptr; //it`s a link - just nullify
  324. if(nullptr != screen2)
  325. {
  326. SDL_FreeSurface(screen2);
  327. screen2 = nullptr;
  328. }
  329. if(nullptr != screen)
  330. {
  331. SDL_FreeSurface(screen);
  332. screen = nullptr;
  333. }
  334. if(nullptr != screenTexture)
  335. {
  336. SDL_DestroyTexture(screenTexture);
  337. screenTexture = nullptr;
  338. }
  339. }
  340. void WindowHandler::destroyWindow()
  341. {
  342. if(nullptr != mainRenderer)
  343. {
  344. SDL_DestroyRenderer(mainRenderer);
  345. mainRenderer = nullptr;
  346. }
  347. if(nullptr != mainWindow)
  348. {
  349. SDL_DestroyWindow(mainWindow);
  350. mainWindow = nullptr;
  351. }
  352. }
  353. void WindowHandler::close()
  354. {
  355. if(settings["general"]["notifications"].Bool())
  356. NotificationHandler::destroy();
  357. destroyScreen();
  358. destroyWindow();
  359. SDL_Quit();
  360. }
  361. void WindowHandler::clearScreen()
  362. {
  363. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  364. SDL_RenderClear(mainRenderer);
  365. SDL_RenderPresent(mainRenderer);
  366. }
  367. std::vector<Point> WindowHandler::getSupportedResolutions() const
  368. {
  369. int displayID = SDL_GetWindowDisplayIndex(mainWindow);
  370. return getSupportedResolutions(displayID);
  371. }
  372. std::vector<Point> WindowHandler::getSupportedResolutions( int displayIndex) const
  373. {
  374. //TODO: check this method on iOS / Android
  375. std::vector<Point> result;
  376. int modesCount = SDL_GetNumDisplayModes(displayIndex);
  377. for (int i =0; i < modesCount; ++i)
  378. {
  379. SDL_DisplayMode mode;
  380. if (SDL_GetDisplayMode(displayIndex, i, &mode) != 0)
  381. continue;
  382. Point resolution(mode.w, mode.h);
  383. result.push_back(resolution);
  384. }
  385. return result;
  386. }