ScreenHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. /*
  2. * ScreenHandler.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 "ScreenHandler.h"
  12. #include "../../lib/CConfigHandler.h"
  13. #include "../../lib/constants/StringConstants.h"
  14. #include "../gui/CGuiHandler.h"
  15. #include "../eventsSDL/NotificationHandler.h"
  16. #include "../gui/WindowHandler.h"
  17. #include "CMT.h"
  18. #include "SDL_Extensions.h"
  19. #ifdef VCMI_ANDROID
  20. #include "../lib/CAndroidVMHelper.h"
  21. #endif
  22. #ifdef VCMI_IOS
  23. # include "ios/utils.h"
  24. #endif
  25. #include <SDL.h>
  26. // TODO: should be made into a private members of ScreenHandler
  27. static SDL_Window * mainWindow = nullptr;
  28. SDL_Renderer * mainRenderer = nullptr;
  29. SDL_Texture * screenTexture = nullptr;
  30. SDL_Surface * screen = nullptr; //main screen surface
  31. SDL_Surface * screen2 = nullptr; //and hlp surface (used to store not-active interfaces layer)
  32. 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
  33. static const std::string NAME = GameConstants::VCMI_VERSION; //application name
  34. std::tuple<int, int> ScreenHandler::getSupportedScalingRange() const
  35. {
  36. // Renderer upscaling factor. TODO: make configurable
  37. static const int scalingFactor = 2;
  38. // H3 resolution, any resolution smaller than that is not correctly supported
  39. static const Point minResolution = Point(800, 600) * scalingFactor;
  40. // arbitrary limit on *downscaling*. Allow some downscaling, if requested by user. Should be generally limited to 100+ for all but few devices
  41. static const double minimalScaling = 50;
  42. Point renderResolution = getRenderResolution();
  43. double reservedAreaWidth = settings["video"]["reservedWidth"].Float();
  44. Point availableResolution = Point(renderResolution.x * (1 - reservedAreaWidth), renderResolution.y);
  45. double maximalScalingWidth = 100.0 * availableResolution.x / minResolution.x;
  46. double maximalScalingHeight = 100.0 * availableResolution.y / minResolution.y;
  47. double maximalScaling = std::min(maximalScalingWidth, maximalScalingHeight);
  48. return { minimalScaling, maximalScaling };
  49. }
  50. Rect ScreenHandler::convertLogicalPointsToWindow(const Rect & input) const
  51. {
  52. Rect result;
  53. // FIXME: use SDL_RenderLogicalToWindow instead? Needs to be tested on ios
  54. float scaleX, scaleY;
  55. SDL_Rect viewport;
  56. SDL_RenderGetScale(mainRenderer, &scaleX, &scaleY);
  57. SDL_RenderGetViewport(mainRenderer, &viewport);
  58. #ifdef VCMI_IOS
  59. // TODO ios: looks like SDL bug actually, try fixing there
  60. const auto nativeScale = iOS_utils::screenScale();
  61. scaleX /= nativeScale;
  62. scaleY /= nativeScale;
  63. #endif
  64. result.x = (viewport.x + input.x) * scaleX;
  65. result.y = (viewport.y + input.y) * scaleY;
  66. result.w = input.w * scaleX;
  67. result.h = input.h * scaleY;
  68. return result;
  69. }
  70. Point ScreenHandler::getPreferredLogicalResolution() const
  71. {
  72. Point renderResolution = getRenderResolution();
  73. double reservedAreaWidth = settings["video"]["reservedWidth"].Float();
  74. Point availableResolution = Point(renderResolution.x * (1 - reservedAreaWidth), renderResolution.y);
  75. auto [minimalScaling, maximalScaling] = getSupportedScalingRange();
  76. int userScaling = settings["video"]["resolution"]["scaling"].Integer();
  77. int scaling = std::clamp(userScaling, minimalScaling, maximalScaling);
  78. Point logicalResolution = availableResolution * 100.0 / scaling;
  79. return logicalResolution;
  80. }
  81. int ScreenHandler::getScalingFactor() const
  82. {
  83. return 2;
  84. }
  85. Point ScreenHandler::getLogicalResolution() const
  86. {
  87. return Point(screen->w, screen->h) / getScalingFactor();
  88. }
  89. Point ScreenHandler::getRenderResolution() const
  90. {
  91. assert(mainRenderer != nullptr);
  92. Point result;
  93. SDL_GetRendererOutputSize(mainRenderer, &result.x, &result.y);
  94. return result;
  95. }
  96. Point ScreenHandler::getPreferredWindowResolution() const
  97. {
  98. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED)
  99. {
  100. SDL_Rect bounds;
  101. if (SDL_GetDisplayBounds(getPreferredDisplayIndex(), &bounds) == 0)
  102. return Point(bounds.w, bounds.h);
  103. }
  104. const JsonNode & video = settings["video"];
  105. int width = video["resolution"]["width"].Integer();
  106. int height = video["resolution"]["height"].Integer();
  107. return Point(width, height);
  108. }
  109. int ScreenHandler::getPreferredDisplayIndex() const
  110. {
  111. #ifdef VCMI_MOBILE
  112. // Assuming no multiple screens on Android / ios?
  113. return 0;
  114. #else
  115. if (mainWindow != nullptr)
  116. {
  117. int result = SDL_GetWindowDisplayIndex(mainWindow);
  118. if (result >= 0)
  119. return result;
  120. }
  121. return settings["video"]["displayIndex"].Integer();
  122. #endif
  123. }
  124. EWindowMode ScreenHandler::getPreferredWindowMode() const
  125. {
  126. #ifdef VCMI_MOBILE
  127. // On Android / ios game will always render to screen size
  128. return EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED;
  129. #else
  130. const JsonNode & video = settings["video"];
  131. bool fullscreen = video["fullscreen"].Bool();
  132. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  133. if (!fullscreen)
  134. return EWindowMode::WINDOWED;
  135. if (realFullscreen)
  136. return EWindowMode::FULLSCREEN_EXCLUSIVE;
  137. else
  138. return EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED;
  139. #endif
  140. }
  141. ScreenHandler::ScreenHandler()
  142. {
  143. #ifdef VCMI_WINDOWS
  144. // set VCMI as "per-monitor DPI awareness". This completely disables any DPI-scaling by system.
  145. // Might not be the best solution since VCMI can't automatically adjust to DPI changes (including moving to monitors with different DPI scaling)
  146. // However this fixed unintuitive bug where player selects specific resolution for windowed mode, but ends up with completely different one due to scaling
  147. // NOTE: requires SDL 2.24.
  148. SDL_SetHint(SDL_HINT_WINDOWS_DPI_AWARENESS, "permonitor");
  149. #endif
  150. if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER))
  151. {
  152. logGlobal->error("Something was wrong: %s", SDL_GetError());
  153. exit(-1);
  154. }
  155. const auto & logCallback = [](void * userdata, int category, SDL_LogPriority priority, const char * message)
  156. {
  157. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  158. };
  159. SDL_LogSetOutputFunction(logCallback, nullptr);
  160. #ifdef VCMI_ANDROID
  161. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  162. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  163. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  164. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  165. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  166. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  167. #endif // VCMI_ANDROID
  168. validateSettings();
  169. recreateWindowAndScreenBuffers();
  170. }
  171. void ScreenHandler::recreateWindowAndScreenBuffers()
  172. {
  173. destroyScreenBuffers();
  174. if(mainWindow == nullptr)
  175. initializeWindow();
  176. else
  177. updateWindowState();
  178. initializeScreenBuffers();
  179. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  180. {
  181. NotificationHandler::init(mainWindow);
  182. }
  183. }
  184. void ScreenHandler::updateWindowState()
  185. {
  186. #ifndef VCMI_MOBILE
  187. int displayIndex = getPreferredDisplayIndex();
  188. switch(getPreferredWindowMode())
  189. {
  190. case EWindowMode::FULLSCREEN_EXCLUSIVE:
  191. {
  192. // for some reason, VCMI fails to switch from FULLSCREEN_BORDERLESS_WINDOWED to FULLSCREEN_EXCLUSIVE directly
  193. // Switch to windowed mode first to avoid this bug
  194. SDL_SetWindowFullscreen(mainWindow, 0);
  195. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  196. SDL_DisplayMode mode;
  197. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  198. Point resolution = getPreferredWindowResolution();
  199. mode.w = resolution.x;
  200. mode.h = resolution.y;
  201. SDL_SetWindowDisplayMode(mainWindow, &mode);
  202. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  203. return;
  204. }
  205. case EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED:
  206. {
  207. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  208. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  209. return;
  210. }
  211. case EWindowMode::WINDOWED:
  212. {
  213. Point resolution = getPreferredWindowResolution();
  214. SDL_SetWindowFullscreen(mainWindow, 0);
  215. SDL_SetWindowSize(mainWindow, resolution.x, resolution.y);
  216. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  217. return;
  218. }
  219. }
  220. #endif
  221. }
  222. void ScreenHandler::initializeWindow()
  223. {
  224. mainWindow = createWindow();
  225. if(mainWindow == nullptr)
  226. {
  227. const char * error = SDL_GetError();
  228. Point dimensions = getPreferredWindowResolution();
  229. std::string messagePattern = "Failed to create SDL Window of size %d x %d. Reason: %s";
  230. std::string message = boost::str(boost::format(messagePattern) % dimensions.x % dimensions.y % error);
  231. handleFatalError(message, true);
  232. }
  233. // create first available renderer if no preferred one is set
  234. // use no SDL_RENDERER_SOFTWARE or SDL_RENDERER_ACCELERATED flag, so HW accelerated will be preferred but SW renderer will also be possible
  235. uint32_t rendererFlags = 0;
  236. if(settings["video"]["vsync"].Bool())
  237. {
  238. rendererFlags |= SDL_RENDERER_PRESENTVSYNC;
  239. }
  240. mainRenderer = SDL_CreateRenderer(mainWindow, getPreferredRenderingDriver(), rendererFlags);
  241. if(mainRenderer == nullptr)
  242. {
  243. const char * error = SDL_GetError();
  244. std::string messagePattern = "Failed to create SDL renderer. Reason: %s";
  245. std::string message = boost::str(boost::format(messagePattern) % error);
  246. handleFatalError(message, true);
  247. }
  248. SDL_RendererInfo info;
  249. SDL_GetRendererInfo(mainRenderer, &info);
  250. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, settings["video"]["scalingMode"].String().c_str());
  251. logGlobal->info("Created renderer %s", info.name);
  252. }
  253. void ScreenHandler::initializeScreenBuffers()
  254. {
  255. #ifdef VCMI_ENDIAN_BIG
  256. int bmask = 0xff000000;
  257. int gmask = 0x00ff0000;
  258. int rmask = 0x0000ff00;
  259. int amask = 0x000000ff;
  260. #else
  261. int bmask = 0x000000ff;
  262. int gmask = 0x0000ff00;
  263. int rmask = 0x00ff0000;
  264. int amask = 0xFF000000;
  265. #endif
  266. auto logicalSize = getPreferredLogicalResolution();
  267. SDL_RenderSetLogicalSize(mainRenderer, logicalSize.x, logicalSize.y);
  268. screen = SDL_CreateRGBSurface(0, logicalSize.x, logicalSize.y, 32, rmask, gmask, bmask, amask);
  269. if(nullptr == screen)
  270. {
  271. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", logicalSize.x, logicalSize.y, 32, SDL_GetError());
  272. throw std::runtime_error("Unable to create surface");
  273. }
  274. //No blending for screen itself. Required for proper cursor rendering.
  275. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  276. screenTexture = SDL_CreateTexture(mainRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, logicalSize.x, logicalSize.y);
  277. if(nullptr == screenTexture)
  278. {
  279. logGlobal->error("Unable to create screen texture");
  280. logGlobal->error(SDL_GetError());
  281. throw std::runtime_error("Unable to create screen texture");
  282. }
  283. screen2 = CSDL_Ext::copySurface(screen);
  284. if(nullptr == screen2)
  285. {
  286. throw std::runtime_error("Unable to copy surface\n");
  287. }
  288. if (GH.windows().count() > 1)
  289. screenBuf = screen2;
  290. else
  291. screenBuf = screen;
  292. clearScreen();
  293. }
  294. SDL_Window * ScreenHandler::createWindowImpl(Point dimensions, int flags, bool center)
  295. {
  296. int displayIndex = getPreferredDisplayIndex();
  297. int positionFlags = center ? SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex) : SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex);
  298. return SDL_CreateWindow(NAME.c_str(), positionFlags, positionFlags, dimensions.x, dimensions.y, flags);
  299. }
  300. SDL_Window * ScreenHandler::createWindow()
  301. {
  302. #ifndef VCMI_MOBILE
  303. Point dimensions = getPreferredWindowResolution();
  304. switch(getPreferredWindowMode())
  305. {
  306. case EWindowMode::FULLSCREEN_EXCLUSIVE:
  307. return createWindowImpl(dimensions, SDL_WINDOW_FULLSCREEN, false);
  308. case EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED:
  309. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN_DESKTOP, false);
  310. case EWindowMode::WINDOWED:
  311. return createWindowImpl(dimensions, SDL_WINDOW_RESIZABLE, true);
  312. default:
  313. return nullptr;
  314. };
  315. #endif
  316. #ifdef VCMI_IOS
  317. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  318. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  319. uint32_t windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  320. SDL_Window * result = createWindowImpl(Point(), windowFlags | SDL_WINDOW_METAL, false);
  321. if(result != nullptr)
  322. return result;
  323. logGlobal->warn("Metal unavailable, using OpenGLES");
  324. return createWindowImpl(Point(), windowFlags, false);
  325. #endif
  326. #ifdef VCMI_ANDROID
  327. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN, false);
  328. #endif
  329. }
  330. void ScreenHandler::onScreenResize()
  331. {
  332. recreateWindowAndScreenBuffers();
  333. }
  334. void ScreenHandler::validateSettings()
  335. {
  336. #ifndef VCMI_MOBILE
  337. {
  338. int displayIndex = settings["video"]["displayIndex"].Integer();
  339. int displaysCount = SDL_GetNumVideoDisplays();
  340. if (displayIndex >= displaysCount)
  341. {
  342. Settings writer = settings.write["video"]["displayIndex"];
  343. writer->Float() = 0;
  344. }
  345. }
  346. if (getPreferredWindowMode() == EWindowMode::WINDOWED)
  347. {
  348. //we only check that our desired window size fits on screen
  349. int displayIndex = getPreferredDisplayIndex();
  350. Point resolution = getPreferredWindowResolution();
  351. SDL_DisplayMode mode;
  352. if (SDL_GetDesktopDisplayMode(displayIndex, &mode) == 0)
  353. {
  354. if(resolution.x > mode.w || resolution.y > mode.h)
  355. {
  356. Settings writer = settings.write["video"]["resolution"];
  357. writer["width"].Float() = mode.w;
  358. writer["height"].Float() = mode.h;
  359. }
  360. }
  361. }
  362. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_EXCLUSIVE)
  363. {
  364. auto legalOptions = getSupportedResolutions();
  365. Point selectedResolution = getPreferredWindowResolution();
  366. if(!vstd::contains(legalOptions, selectedResolution))
  367. {
  368. // resolution selected for fullscreen mode is not supported by display
  369. // try to find current display resolution and use it instead as "reasonable default"
  370. SDL_DisplayMode mode;
  371. if (SDL_GetDesktopDisplayMode(getPreferredDisplayIndex(), &mode) == 0)
  372. {
  373. Settings writer = settings.write["video"]["resolution"];
  374. writer["width"].Float() = mode.w;
  375. writer["height"].Float() = mode.h;
  376. }
  377. }
  378. }
  379. #endif
  380. }
  381. int ScreenHandler::getPreferredRenderingDriver() const
  382. {
  383. int result = -1;
  384. const JsonNode & video = settings["video"];
  385. int driversCount = SDL_GetNumRenderDrivers();
  386. std::string preferredDriverName = video["driver"].String();
  387. logGlobal->info("Found %d render drivers", driversCount);
  388. for(int it = 0; it < driversCount; it++)
  389. {
  390. SDL_RendererInfo info;
  391. if (SDL_GetRenderDriverInfo(it, &info) == 0)
  392. {
  393. std::string driverName(info.name);
  394. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  395. {
  396. result = it;
  397. logGlobal->info("\t%s (active)", driverName);
  398. }
  399. else
  400. logGlobal->info("\t%s", driverName);
  401. }
  402. else
  403. logGlobal->info("\t(error)");
  404. }
  405. return result;
  406. }
  407. void ScreenHandler::destroyScreenBuffers()
  408. {
  409. // screenBuf is not a separate surface, but points to either screen or screen2 - just set to null
  410. screenBuf = nullptr;
  411. if(nullptr != screen2)
  412. {
  413. SDL_FreeSurface(screen2);
  414. screen2 = nullptr;
  415. }
  416. if(nullptr != screen)
  417. {
  418. SDL_FreeSurface(screen);
  419. screen = nullptr;
  420. }
  421. if(nullptr != screenTexture)
  422. {
  423. SDL_DestroyTexture(screenTexture);
  424. screenTexture = nullptr;
  425. }
  426. }
  427. void ScreenHandler::destroyWindow()
  428. {
  429. if(nullptr != mainRenderer)
  430. {
  431. SDL_DestroyRenderer(mainRenderer);
  432. mainRenderer = nullptr;
  433. }
  434. if(nullptr != mainWindow)
  435. {
  436. SDL_DestroyWindow(mainWindow);
  437. mainWindow = nullptr;
  438. }
  439. }
  440. void ScreenHandler::close()
  441. {
  442. if(settings["general"]["notifications"].Bool())
  443. NotificationHandler::destroy();
  444. destroyScreenBuffers();
  445. destroyWindow();
  446. SDL_Quit();
  447. }
  448. void ScreenHandler::clearScreen()
  449. {
  450. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  451. SDL_RenderClear(mainRenderer);
  452. SDL_RenderPresent(mainRenderer);
  453. }
  454. std::vector<Point> ScreenHandler::getSupportedResolutions() const
  455. {
  456. int displayID = getPreferredDisplayIndex();
  457. return getSupportedResolutions(displayID);
  458. }
  459. std::vector<Point> ScreenHandler::getSupportedResolutions( int displayIndex) const
  460. {
  461. //NOTE: this method is never called on Android/iOS, only on desktop systems
  462. std::vector<Point> result;
  463. int modesCount = SDL_GetNumDisplayModes(displayIndex);
  464. for (int i =0; i < modesCount; ++i)
  465. {
  466. SDL_DisplayMode mode;
  467. if (SDL_GetDisplayMode(displayIndex, i, &mode) == 0)
  468. {
  469. Point resolution(mode.w, mode.h);
  470. result.push_back(resolution);
  471. }
  472. }
  473. boost::range::sort(result, [](const auto & left, const auto & right)
  474. {
  475. return left.x * left.y < right.x * right.y;
  476. });
  477. // erase potential duplicates, e.g. resolutions with different framerate / bits per pixel
  478. result.erase(boost::unique(result).end(), result.end());
  479. return result;
  480. }
  481. bool ScreenHandler::hasFocus()
  482. {
  483. ui32 flags = SDL_GetWindowFlags(mainWindow);
  484. return flags & SDL_WINDOW_INPUT_FOCUS;
  485. }