ScreenHandler.cpp 16 KB

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