ScreenHandler.cpp 14 KB

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