CMT.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  1. /*
  2. * CMT.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. // CMT.cpp : Defines the entry point for the console application.
  11. //
  12. #include "StdInc.h"
  13. #include <boost/program_options.hpp>
  14. #include <vcmi/scripting/Service.h>
  15. #include "gui/SDL_Extensions.h"
  16. #include "CGameInfo.h"
  17. #include "mapHandler.h"
  18. #include "../lib/filesystem/Filesystem.h"
  19. #include "../lib/filesystem/FileStream.h"
  20. #include "mainmenu/CMainMenu.h"
  21. #include "lobby/CSelectionBase.h"
  22. #include "windows/CCastleInterface.h"
  23. #include "../lib/CConsoleHandler.h"
  24. #include "gui/CursorHandler.h"
  25. #include "../lib/CGameState.h"
  26. #include "../CCallback.h"
  27. #include "CPlayerInterface.h"
  28. #include "windows/CAdvmapInterface.h"
  29. #include "../lib/CBuildingHandler.h"
  30. #include "CVideoHandler.h"
  31. #include "../lib/CHeroHandler.h"
  32. #include "../lib/CCreatureHandler.h"
  33. #include "../lib/spells/CSpellHandler.h"
  34. #include "CMusicHandler.h"
  35. #include "../lib/CGeneralTextHandler.h"
  36. #include "Graphics.h"
  37. #include "Client.h"
  38. #include "../lib/CConfigHandler.h"
  39. #include "../lib/serializer/BinaryDeserializer.h"
  40. #include "../lib/serializer/BinarySerializer.h"
  41. #include "../lib/VCMI_Lib.h"
  42. #include "../lib/VCMIDirs.h"
  43. #include "../lib/NetPacks.h"
  44. #include "CMessage.h"
  45. #include "../lib/CModHandler.h"
  46. #include "../lib/ScriptHandler.h"
  47. #include "../lib/CTownHandler.h"
  48. #include "../lib/CArtHandler.h"
  49. #include "../lib/GameConstants.h"
  50. #include "gui/CGuiHandler.h"
  51. #include "../lib/logging/CBasicLogConfigurator.h"
  52. #include "../lib/StringConstants.h"
  53. #include "../lib/CPlayerState.h"
  54. #include "gui/CAnimation.h"
  55. #include "../lib/serializer/Connection.h"
  56. #include "CServerHandler.h"
  57. #include "gui/NotificationHandler.h"
  58. #include <boost/asio.hpp>
  59. #include "mainmenu/CPrologEpilogVideo.h"
  60. #include <vstd/StringUtils.h>
  61. #ifdef VCMI_WINDOWS
  62. #include "SDL_syswm.h"
  63. #endif
  64. #ifdef VCMI_ANDROID
  65. #include "lib/CAndroidVMHelper.h"
  66. #endif
  67. #include "../lib/UnlockGuard.h"
  68. #include "CMT.h"
  69. #if __MINGW32__
  70. #undef main
  71. #endif
  72. namespace po = boost::program_options;
  73. namespace po_style = boost::program_options::command_line_style;
  74. namespace bfs = boost::filesystem;
  75. std::string NAME_AFFIX = "client";
  76. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  77. CGuiHandler GH;
  78. int preferredDriverIndex = -1;
  79. SDL_Window * mainWindow = nullptr;
  80. SDL_Renderer * mainRenderer = nullptr;
  81. SDL_Texture * screenTexture = nullptr;
  82. extern boost::thread_specific_ptr<bool> inGuiThread;
  83. SDL_Surface *screen = nullptr, //main screen surface
  84. *screen2 = nullptr, //and hlp surface (used to store not-active interfaces layer)
  85. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  86. std::queue<SDL_Event> SDLEventsQueue;
  87. boost::mutex eventsM;
  88. static po::variables_map vm;
  89. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  90. #ifndef VCMI_IOS
  91. void processCommand(const std::string &message);
  92. #endif
  93. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo=true);
  94. void playIntro();
  95. static void mainLoop();
  96. static CBasicLogConfigurator *logConfig;
  97. #ifndef VCMI_WINDOWS
  98. #ifndef _GNU_SOURCE
  99. #define _GNU_SOURCE
  100. #endif
  101. #include <getopt.h>
  102. #endif
  103. void init()
  104. {
  105. CStopWatch tmh;
  106. loadDLLClasses();
  107. const_cast<CGameInfo*>(CGI)->setFromLib();
  108. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  109. }
  110. static void prog_version()
  111. {
  112. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  113. std::cout << VCMIDirs::get().genHelpString();
  114. }
  115. static void prog_help(const po::options_description &opts)
  116. {
  117. auto time = std::time(0);
  118. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  119. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  120. printf("This is free software; see the source for copying conditions. There is NO\n");
  121. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  122. printf("\n");
  123. std::cout << opts;
  124. }
  125. static void SDLLogCallback(void* userdata,
  126. int category,
  127. SDL_LogPriority priority,
  128. const char* message)
  129. {
  130. //todo: convert SDL log priority to vcmi log priority
  131. //todo: make separate log domain for SDL
  132. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  133. }
  134. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  135. int wmain(int argc, wchar_t* argv[])
  136. #elif defined(VCMI_IOS) || defined(VCMI_ANDROID)
  137. int SDL_main(int argc, char *argv[])
  138. #else
  139. int main(int argc, char * argv[])
  140. #endif
  141. {
  142. #ifdef VCMI_ANDROID
  143. // boost will crash without this
  144. setenv("LANG", "C", 1);
  145. #endif
  146. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  147. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  148. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  149. #endif
  150. std::cout << "Starting... " << std::endl;
  151. po::options_description opts("Allowed options");
  152. opts.add_options()
  153. ("help,h", "display help and exit")
  154. ("version,v", "display version information and exit")
  155. ("disable-shm", "force disable shared memory usage")
  156. ("enable-shm-uuid", "use UUID for shared memory identifier")
  157. ("testmap", po::value<std::string>(), "")
  158. ("testsave", po::value<std::string>(), "")
  159. ("spectate,s", "enable spectator interface for AI-only games")
  160. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  161. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  162. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  163. ("spectate-skip-battle", "skip battles in spectator view")
  164. ("spectate-skip-battle-result", "skip battle result window")
  165. ("onlyAI", "allow to run without human player, all players will be default AI")
  166. ("headless", "runs without GUI, implies --onlyAI")
  167. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  168. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  169. ("autoSkip", "automatically skip turns in GUI")
  170. ("disable-video", "disable video player")
  171. ("nointro,i", "skips intro movies")
  172. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  173. ("serverport", po::value<si64>(), "override port specified in config file")
  174. ("saveprefix", po::value<std::string>(), "prefix for auto save files")
  175. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days")
  176. ("lobby", "parameters address, port, uuid to connect ro remote lobby session")
  177. ("lobby-address", po::value<std::string>(), "address to remote lobby")
  178. ("lobby-port", po::value<ui16>(), "port to remote lobby")
  179. ("lobby-host", "if this client hosts session")
  180. ("lobby-uuid", po::value<std::string>(), "uuid to the server")
  181. ("lobby-connections", po::value<ui16>(), "connections of server")
  182. ("lobby-username", po::value<std::string>(), "player name")
  183. ("lobby-gamemode", po::value<ui16>(), "use 0 for new game and 1 for load game")
  184. ("uuid", po::value<std::string>(), "uuid for the client");
  185. if(argc > 1)
  186. {
  187. try
  188. {
  189. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  190. }
  191. catch(std::exception &e)
  192. {
  193. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  194. }
  195. }
  196. po::notify(vm);
  197. if(vm.count("help"))
  198. {
  199. prog_help(opts);
  200. #ifdef VCMI_IOS
  201. exit(0);
  202. #else
  203. return 0;
  204. #endif
  205. }
  206. if(vm.count("version"))
  207. {
  208. prog_version();
  209. #ifdef VCMI_IOS
  210. exit(0);
  211. #else
  212. return 0;
  213. #endif
  214. }
  215. // Init old logging system and new (temporary) logging system
  216. CStopWatch total, pomtime;
  217. std::cout.flags(std::ios::unitbuf);
  218. #ifndef VCMI_IOS
  219. console = new CConsoleHandler();
  220. *console->cb = processCommand;
  221. console->start();
  222. #endif
  223. const bfs::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  224. logConfig = new CBasicLogConfigurator(logPath, console);
  225. logConfig->configureDefault();
  226. logGlobal->info(NAME);
  227. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  228. logGlobal->info("The log file will be saved to %s", logPath);
  229. // Init filesystem and settings
  230. preinitDLL(::console);
  231. settings.init();
  232. Settings session = settings.write["session"];
  233. auto setSettingBool = [](std::string key, std::string arg) {
  234. Settings s = settings.write(vstd::split(key, "/"));
  235. if(::vm.count(arg))
  236. s->Bool() = true;
  237. else if(s->isNull())
  238. s->Bool() = false;
  239. };
  240. auto setSettingInteger = [](std::string key, std::string arg, si64 defaultValue) {
  241. Settings s = settings.write(vstd::split(key, "/"));
  242. if(::vm.count(arg))
  243. s->Integer() = ::vm[arg].as<si64>();
  244. else if(s->isNull())
  245. s->Integer() = defaultValue;
  246. };
  247. auto setSettingString = [](std::string key, std::string arg, std::string defaultValue) {
  248. Settings s = settings.write(vstd::split(key, "/"));
  249. if(::vm.count(arg))
  250. s->String() = ::vm[arg].as<std::string>();
  251. else if(s->isNull())
  252. s->String() = defaultValue;
  253. };
  254. setSettingBool("session/onlyai", "onlyAI");
  255. if(vm.count("headless"))
  256. {
  257. session["headless"].Bool() = true;
  258. session["onlyai"].Bool() = true;
  259. }
  260. else if(vm.count("spectate"))
  261. {
  262. session["spectate"].Bool() = true;
  263. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  264. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  265. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  266. if(vm.count("spectate-hero-speed"))
  267. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  268. if(vm.count("spectate-battle-speed"))
  269. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  270. }
  271. // Server settings
  272. setSettingBool("session/donotstartserver", "donotstartserver");
  273. // Shared memory options
  274. setSettingBool("session/disable-shm", "disable-shm");
  275. setSettingBool("session/enable-shm-uuid", "enable-shm-uuid");
  276. // Init special testing settings
  277. setSettingInteger("session/serverport", "serverport", 0);
  278. setSettingString("session/saveprefix", "saveprefix", "");
  279. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  280. // Initialize logging based on settings
  281. logConfig->configure();
  282. logGlobal->debug("settings = %s", settings.toJsonNode().toJson());
  283. // Some basic data validation to produce better error messages in cases of incorrect install
  284. auto testFile = [](std::string filename, std::string message) -> bool
  285. {
  286. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  287. return true;
  288. logGlobal->error("Error: %s was not found!", message);
  289. return false;
  290. };
  291. if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
  292. !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
  293. {
  294. exit(1); // These are unrecoverable errors
  295. }
  296. // these two are optional + some installs have them on CD and not in data directory
  297. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  298. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  299. conf.init();
  300. logGlobal->info("Loading settings: %d ms", pomtime.getDiff());
  301. srand ( (unsigned int)time(nullptr) );
  302. const JsonNode& video = settings["video"];
  303. const JsonNode& res = video["screenRes"];
  304. //something is really wrong...
  305. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  306. {
  307. logGlobal->error("Fatal error: failed to load settings!");
  308. logGlobal->error("Possible reasons:");
  309. logGlobal->error("\tCorrupted local configuration file at %s/settings.json", VCMIDirs::get().userConfigPath());
  310. logGlobal->error("\tMissing or corrupted global configuration file at %s/schemas/settings.json", VCMIDirs::get().userConfigPath());
  311. logGlobal->error("VCMI will now exit...");
  312. exit(EXIT_FAILURE);
  313. }
  314. if(!settings["session"]["headless"].Bool())
  315. {
  316. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_NOPARACHUTE))
  317. {
  318. logGlobal->error("Something was wrong: %s", SDL_GetError());
  319. exit(-1);
  320. }
  321. #ifdef VCMI_ANDROID
  322. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  323. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  324. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  325. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  326. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  327. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  328. #endif // VCMI_ANDROID
  329. GH.mainFPSmng->init(); //(!)init here AFTER SDL_Init() while using SDL for FPS management
  330. SDL_LogSetOutputFunction(&SDLLogCallback, nullptr);
  331. int driversCount = SDL_GetNumRenderDrivers();
  332. std::string preferredDriverName = video["driver"].String();
  333. logGlobal->info("Found %d render drivers", driversCount);
  334. for(int it = 0; it < driversCount; it++)
  335. {
  336. SDL_RendererInfo info;
  337. SDL_GetRenderDriverInfo(it,&info);
  338. std::string driverName(info.name);
  339. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  340. {
  341. preferredDriverIndex = it;
  342. logGlobal->info("\t%s (active)", driverName);
  343. }
  344. else
  345. logGlobal->info("\t%s", driverName);
  346. }
  347. setScreenRes((int)res["width"].Float(), (int)res["height"].Float(), (int)video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), (int)video["displayIndex"].Float());
  348. logGlobal->info("\tInitializing screen: %d ms", pomtime.getDiff());
  349. }
  350. CCS = new CClientState();
  351. CGI = new CGameInfo(); //contains all global informations about game (texts, lodHandlers, map handler etc.)
  352. CSH = new CServerHandler();
  353. // Initialize video
  354. #ifdef DISABLE_VIDEO
  355. CCS->videoh = new CEmptyVideoPlayer();
  356. #else
  357. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  358. CCS->videoh = new CVideoPlayer();
  359. else
  360. CCS->videoh = new CEmptyVideoPlayer();
  361. #endif
  362. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  363. if(!settings["session"]["headless"].Bool())
  364. {
  365. //initializing audio
  366. CCS->soundh = new CSoundHandler();
  367. CCS->soundh->init();
  368. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  369. CCS->musich = new CMusicHandler();
  370. CCS->musich->init();
  371. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  372. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  373. }
  374. #ifdef VCMI_MAC
  375. // Ctrl+click should be treated as a right click on Mac OS X
  376. SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
  377. #endif
  378. #ifndef VCMI_NO_THREADED_LOAD
  379. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  380. boost::thread loading(init);
  381. #else
  382. init();
  383. #endif
  384. if(!settings["session"]["headless"].Bool())
  385. {
  386. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  387. playIntro();
  388. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  389. SDL_RenderClear(mainRenderer);
  390. SDL_RenderPresent(mainRenderer);
  391. }
  392. #ifndef VCMI_NO_THREADED_LOAD
  393. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  394. {
  395. CAndroidVMHelper vmHelper;
  396. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  397. #endif // ANDROID
  398. loading.join();
  399. #ifdef VCMI_ANDROID
  400. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  401. }
  402. #endif // ANDROID
  403. #endif // THREADED
  404. if(!settings["session"]["headless"].Bool())
  405. {
  406. pomtime.getDiff();
  407. graphics = new Graphics(); // should be before curh
  408. CCS->curh = new CursorHandler();
  409. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  410. pomtime.getDiff();
  411. graphics->load();//must be after Content loading but should be in main thread
  412. logGlobal->info("Main graphics: %d ms", pomtime.getDiff());
  413. CMessage::init();
  414. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  415. CCS->curh->show();
  416. }
  417. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  418. session["autoSkip"].Bool() = vm.count("autoSkip");
  419. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  420. session["aiSolo"].Bool() = false;
  421. std::shared_ptr<CMainMenu> mmenu;
  422. if(vm.count("testmap"))
  423. {
  424. session["testmap"].String() = vm["testmap"].as<std::string>();
  425. session["onlyai"].Bool() = true;
  426. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  427. }
  428. else if(vm.count("testsave"))
  429. {
  430. session["testsave"].String() = vm["testsave"].as<std::string>();
  431. session["onlyai"].Bool() = true;
  432. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  433. }
  434. else
  435. {
  436. mmenu = CMainMenu::create();
  437. GH.curInt = mmenu.get();
  438. }
  439. std::vector<std::string> names;
  440. session["lobby"].Bool() = false;
  441. if(vm.count("lobby"))
  442. {
  443. session["lobby"].Bool() = true;
  444. session["host"].Bool() = false;
  445. session["address"].String() = vm["lobby-address"].as<std::string>();
  446. if(vm.count("lobby-username"))
  447. session["username"].String() = vm["lobby-username"].as<std::string>();
  448. else
  449. session["username"].String() = settings["launcher"]["lobbyUsername"].String();
  450. if(vm.count("lobby-gamemode"))
  451. session["gamemode"].Integer() = vm["lobby-gamemode"].as<ui16>();
  452. else
  453. session["gamemode"].Integer() = 0;
  454. CSH->uuid = vm["uuid"].as<std::string>();
  455. session["port"].Integer() = vm["lobby-port"].as<ui16>();
  456. logGlobal->info("Remote lobby mode at %s:%d, uuid is %s", session["address"].String(), session["port"].Integer(), CSH->uuid);
  457. if(vm.count("lobby-host"))
  458. {
  459. session["host"].Bool() = true;
  460. session["hostConnections"].String() = std::to_string(vm["lobby-connections"].as<ui16>());
  461. session["hostUuid"].String() = vm["lobby-uuid"].as<std::string>();
  462. logGlobal->info("This client will host session, server uuid is %s", session["hostUuid"].String());
  463. }
  464. //we should not reconnect to previous game in online mode
  465. Settings saveSession = settings.write["server"]["reconnect"];
  466. saveSession->Bool() = false;
  467. //start lobby immediately
  468. names.push_back(session["username"].String());
  469. ESelectionScreen sscreen = session["gamemode"].Integer() == 0 ? ESelectionScreen::newGame : ESelectionScreen::loadGame;
  470. mmenu->openLobby(sscreen, session["host"].Bool(), &names, ELoadMode::MULTI);
  471. }
  472. // Restore remote session - start game immediately
  473. if(settings["server"]["reconnect"].Bool())
  474. {
  475. CSH->restoreLastSession();
  476. }
  477. if(!settings["session"]["headless"].Bool())
  478. {
  479. mainLoop();
  480. }
  481. else
  482. {
  483. while(true)
  484. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  485. }
  486. return 0;
  487. }
  488. void printInfoAboutIntObject(const CIntObject *obj, int level)
  489. {
  490. std::stringstream sbuffer;
  491. sbuffer << std::string(level, '\t');
  492. sbuffer << typeid(*obj).name() << " *** ";
  493. if (obj->active)
  494. {
  495. #define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
  496. PRINT(LCLICK, 'L');
  497. PRINT(RCLICK, 'R');
  498. PRINT(HOVER, 'H');
  499. PRINT(MOVE, 'M');
  500. PRINT(KEYBOARD, 'K');
  501. PRINT(TIME, 'T');
  502. PRINT(GENERAL, 'A');
  503. PRINT(WHEEL, 'W');
  504. PRINT(DOUBLECLICK, 'D');
  505. #undef PRINT
  506. }
  507. else
  508. sbuffer << "inactive";
  509. sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
  510. sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
  511. logGlobal->info(sbuffer.str());
  512. for(const CIntObject *child : obj->children)
  513. printInfoAboutIntObject(child, level+1);
  514. }
  515. void removeGUI()
  516. {
  517. // CClient::endGame
  518. GH.curInt = nullptr;
  519. if(GH.topInt())
  520. GH.topInt()->deactivate();
  521. adventureInt = nullptr;
  522. GH.listInt.clear();
  523. GH.objsToBlit.clear();
  524. GH.statusbar = nullptr;
  525. logGlobal->info("Removed GUI.");
  526. LOCPLINT = nullptr;
  527. }
  528. #ifndef VCMI_IOS
  529. void processCommand(const std::string &message)
  530. {
  531. std::istringstream readed;
  532. readed.str(message);
  533. std::string cn; //command name
  534. readed >> cn;
  535. // Check mantis issue 2292 for details
  536. // if(LOCPLINT && LOCPLINT->cingconsole)
  537. // LOCPLINT->cingconsole->print(message);
  538. if(message==std::string("die, fool"))
  539. {
  540. exit(EXIT_SUCCESS);
  541. }
  542. else if(cn==std::string("activate"))
  543. {
  544. int what;
  545. readed >> what;
  546. switch (what)
  547. {
  548. case 0:
  549. GH.topInt()->activate();
  550. break;
  551. case 1:
  552. adventureInt->activate();
  553. break;
  554. case 2:
  555. LOCPLINT->castleInt->activate();
  556. break;
  557. }
  558. }
  559. else if(cn=="redraw")
  560. {
  561. GH.totalRedraw();
  562. }
  563. else if(cn=="screen")
  564. {
  565. std::cout << "Screenbuf points to ";
  566. if(screenBuf == screen)
  567. logGlobal->error("screen");
  568. else if(screenBuf == screen2)
  569. logGlobal->error("screen2");
  570. else
  571. logGlobal->error("?!?");
  572. SDL_SaveBMP(screen, "Screen_c.bmp");
  573. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  574. }
  575. else if(cn=="save")
  576. {
  577. if(!CSH->client)
  578. {
  579. std::cout << "Game in not active";
  580. return;
  581. }
  582. std::string fname;
  583. readed >> fname;
  584. CSH->client->save(fname);
  585. }
  586. // else if(cn=="load")
  587. // {
  588. // // TODO: this code should end the running game and manage to call startGame instead
  589. // std::string fname;
  590. // readed >> fname;
  591. // CSH->client->loadGame(fname);
  592. // }
  593. else if(message=="convert txt")
  594. {
  595. VLC->generaltexth->dumpAllTexts();
  596. }
  597. else if(message=="get config")
  598. {
  599. std::cout << "Command accepted.\t";
  600. const bfs::path outPath =
  601. VCMIDirs::get().userExtractedPath() / "configuration";
  602. bfs::create_directories(outPath);
  603. const std::vector<std::string> contentNames = {"heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills"};
  604. for(auto contentName : contentNames)
  605. {
  606. auto & content = (*VLC->modh->content)[contentName];
  607. auto contentOutPath = outPath / contentName;
  608. bfs::create_directories(contentOutPath);
  609. for(auto & iter : content.modData)
  610. {
  611. const JsonNode & modData = iter.second.modData;
  612. for(auto & nameAndObject : modData.Struct())
  613. {
  614. const JsonNode & object = nameAndObject.second;
  615. std::string name = CModHandler::normalizeIdentifier(object.meta, CModHandler::scopeBuiltin(), nameAndObject.first);
  616. boost::algorithm::replace_all(name,":","_");
  617. const bfs::path filePath = contentOutPath / (name + ".json");
  618. bfs::ofstream file(filePath);
  619. file << object.toJson();
  620. }
  621. }
  622. }
  623. std::cout << "\rExtracting done :)\n";
  624. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  625. }
  626. #if SCRIPTING_ENABLED
  627. else if(message=="get scripts")
  628. {
  629. std::cout << "Command accepted.\t";
  630. const bfs::path outPath =
  631. VCMIDirs::get().userExtractedPath() / "scripts";
  632. bfs::create_directories(outPath);
  633. for(auto & kv : VLC->scriptHandler->objects)
  634. {
  635. std::string name = kv.first;
  636. boost::algorithm::replace_all(name,":","_");
  637. const scripting::ScriptImpl * script = kv.second.get();
  638. bfs::path filePath = outPath / (name + ".lua");
  639. bfs::ofstream file(filePath);
  640. file << script->getSource();
  641. }
  642. std::cout << "\rExtracting done :)\n";
  643. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  644. }
  645. #endif
  646. else if(message=="get txt")
  647. {
  648. std::cout << "Command accepted.\t";
  649. const bfs::path outPath =
  650. VCMIDirs::get().userExtractedPath();
  651. auto list = CResourceHandler::get()->getFilteredFiles([](const ResourceID & ident)
  652. {
  653. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  654. });
  655. for (auto & filename : list)
  656. {
  657. const bfs::path filePath = outPath / (filename.getName() + ".TXT");
  658. bfs::create_directories(filePath.parent_path());
  659. bfs::ofstream file(filePath);
  660. auto text = CResourceHandler::get()->load(filename)->readAll();
  661. file.write((char*)text.first.get(), text.second);
  662. }
  663. std::cout << "\rExtracting done :)\n";
  664. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  665. }
  666. else if(cn=="crash")
  667. {
  668. int *ptr = nullptr;
  669. *ptr = 666;
  670. //disaster!
  671. }
  672. else if(cn == "mp" && adventureInt)
  673. {
  674. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  675. std::cout << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  676. }
  677. else if(cn == "bonuses")
  678. {
  679. bool jsonFormat = (message == "bonuses json");
  680. auto format = [jsonFormat](const BonusList & b) -> std::string
  681. {
  682. if(jsonFormat)
  683. return b.toJsonNode().toJson(true);
  684. std::ostringstream ss;
  685. ss << b;
  686. return ss.str();
  687. };
  688. std::cout << "Bonuses of " << adventureInt->selection->getObjectName() << std::endl
  689. << format(adventureInt->selection->getBonusList()) << std::endl;
  690. std::cout << "\nInherited bonuses:\n";
  691. TCNodes parents;
  692. adventureInt->selection->getParents(parents);
  693. for(const CBonusSystemNode *parent : parents)
  694. {
  695. std::cout << "\nBonuses from " << typeid(*parent).name() << std::endl << format(*parent->getAllBonuses(Selector::all, Selector::all)) << std::endl;
  696. }
  697. }
  698. else if(cn == "not dialog")
  699. {
  700. LOCPLINT->showingDialog->setn(false);
  701. }
  702. else if(cn == "gui")
  703. {
  704. for(auto & child : GH.listInt)
  705. {
  706. const auto childPtr = child.get();
  707. if(const CIntObject * obj = dynamic_cast<const CIntObject *>(childPtr))
  708. printInfoAboutIntObject(obj, 0);
  709. else
  710. std::cout << typeid(childPtr).name() << std::endl;
  711. }
  712. }
  713. else if(cn=="tell")
  714. {
  715. std::string what;
  716. int id1, id2;
  717. readed >> what >> id1 >> id2;
  718. if(what == "hs")
  719. {
  720. for(const CGHeroInstance *h : LOCPLINT->cb->getHeroesInfo())
  721. if(h->type->ID.getNum() == id1)
  722. if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
  723. std::cout << a->nodeName();
  724. }
  725. }
  726. else if (cn == "set")
  727. {
  728. std::string what, value;
  729. readed >> what;
  730. Settings conf = settings.write["session"][what];
  731. readed >> value;
  732. if (value == "on")
  733. {
  734. conf->Bool() = true;
  735. logGlobal->info("Option %s enabled!", what);
  736. }
  737. else if (value == "off")
  738. {
  739. conf->Bool() = false;
  740. logGlobal->info("Option %s disabled!", what);
  741. }
  742. }
  743. else if(cn == "unlock")
  744. {
  745. std::string mxname;
  746. readed >> mxname;
  747. if(mxname == "pim" && LOCPLINT)
  748. LOCPLINT->pim->unlock();
  749. }
  750. else if(cn == "def2bmp")
  751. {
  752. std::string URI;
  753. readed >> URI;
  754. std::unique_ptr<CAnimation> anim = std::make_unique<CAnimation>(URI);
  755. anim->preload();
  756. anim->exportBitmaps(VCMIDirs::get().userExtractedPath());
  757. }
  758. else if(cn == "extract")
  759. {
  760. std::string URI;
  761. readed >> URI;
  762. if (CResourceHandler::get()->existsResource(ResourceID(URI)))
  763. {
  764. const bfs::path outPath = VCMIDirs::get().userExtractedPath() / URI;
  765. auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll();
  766. bfs::create_directories(outPath.parent_path());
  767. bfs::ofstream outFile(outPath, bfs::ofstream::binary);
  768. outFile.write((char*)data.first.get(), data.second);
  769. }
  770. else
  771. logGlobal->error("File not found!");
  772. }
  773. else if(cn == "setBattleAI")
  774. {
  775. std::string fname;
  776. readed >> fname;
  777. std::cout << "Will try loading that AI to see if it is correct name...\n";
  778. try
  779. {
  780. if(auto ai = CDynLibHandler::getNewBattleAI(fname)) //test that given AI is indeed available... heavy but it is easy to make a typo and break the game
  781. {
  782. Settings neutralAI = settings.write["server"]["neutralAI"];
  783. neutralAI->String() = fname;
  784. std::cout << "Setting changed, from now the battle ai will be " << fname << "!\n";
  785. }
  786. }
  787. catch(std::exception &e)
  788. {
  789. logGlobal->warn("Failed opening %s: %s", fname, e.what());
  790. logGlobal->warn("Setting not changes, AI not found or invalid!");
  791. }
  792. }
  793. auto giveTurn = [&](PlayerColor player)
  794. {
  795. YourTurn yt;
  796. yt.player = player;
  797. yt.daysWithoutCastle = CSH->client->getPlayerState(player)->daysWithoutCastle;
  798. yt.applyCl(CSH->client);
  799. };
  800. Settings session = settings.write["session"];
  801. if(cn == "autoskip")
  802. {
  803. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  804. }
  805. else if(cn == "gosolo")
  806. {
  807. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  808. if(!CSH->client)
  809. {
  810. std::cout << "Game in not active";
  811. return;
  812. }
  813. PlayerColor color;
  814. if(session["aiSolo"].Bool())
  815. {
  816. for(auto & elem : CSH->client->gameState()->players)
  817. {
  818. if(elem.second.human)
  819. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  820. }
  821. }
  822. else
  823. {
  824. color = LOCPLINT->playerID;
  825. removeGUI();
  826. for(auto & elem : CSH->client->gameState()->players)
  827. {
  828. if(elem.second.human)
  829. {
  830. auto AiToGive = CSH->client->aiNameForPlayer(*CSH->client->getPlayerSettings(elem.first), false);
  831. logNetwork->info("Player %s will be lead by %s", elem.first, AiToGive);
  832. CSH->client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), elem.first);
  833. }
  834. }
  835. GH.totalRedraw();
  836. giveTurn(color);
  837. }
  838. session["aiSolo"].Bool() = !session["aiSolo"].Bool();
  839. }
  840. else if(cn == "controlai")
  841. {
  842. std::string colorName;
  843. readed >> colorName;
  844. boost::to_lower(colorName);
  845. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  846. if(!CSH->client)
  847. {
  848. std::cout << "Game in not active";
  849. return;
  850. }
  851. PlayerColor color;
  852. if(LOCPLINT)
  853. color = LOCPLINT->playerID;
  854. for(auto & elem : CSH->client->gameState()->players)
  855. {
  856. if(elem.second.human || (colorName.length() &&
  857. elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
  858. {
  859. continue;
  860. }
  861. removeGUI();
  862. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  863. }
  864. GH.totalRedraw();
  865. if(color != PlayerColor::NEUTRAL)
  866. giveTurn(color);
  867. }
  868. // Check mantis issue 2292 for details
  869. /* else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  870. {
  871. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  872. LOCPLINT->cb->sendMessage(message);
  873. }*/
  874. }
  875. #endif
  876. //plays intro, ends when intro is over or button has been pressed (handles events)
  877. void playIntro()
  878. {
  879. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 0, 1, true, true))
  880. {
  881. CCS->videoh->openAndPlayVideo("AZVS.SMK", 0, 1, true, true);
  882. }
  883. }
  884. #ifndef VCMI_IOS
  885. static bool checkVideoMode(int monitorIndex, int w, int h)
  886. {
  887. //we only check that our desired window size fits on screen
  888. SDL_DisplayMode mode;
  889. if (0 != SDL_GetDesktopDisplayMode(monitorIndex, &mode))
  890. {
  891. logGlobal->error("SDL_GetDesktopDisplayMode failed");
  892. logGlobal->error(SDL_GetError());
  893. return false;
  894. }
  895. logGlobal->info("Check display mode: requested %d x %d; available up to %d x %d ", w, h, mode.w, mode.h);
  896. if (!mode.w || !mode.h || (w <= mode.w && h <= mode.h))
  897. {
  898. return true;
  899. }
  900. return false;
  901. }
  902. #endif
  903. static void cleanupRenderer()
  904. {
  905. screenBuf = nullptr; //it`s a link - just nullify
  906. if(nullptr != screen2)
  907. {
  908. SDL_FreeSurface(screen2);
  909. screen2 = nullptr;
  910. }
  911. if(nullptr != screen)
  912. {
  913. SDL_FreeSurface(screen);
  914. screen = nullptr;
  915. }
  916. if(nullptr != screenTexture)
  917. {
  918. SDL_DestroyTexture(screenTexture);
  919. screenTexture = nullptr;
  920. }
  921. }
  922. static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIndex)
  923. {
  924. // VCMI will only work with 2 or 4 bytes per pixel
  925. vstd::amax(bpp, 16);
  926. vstd::amin(bpp, 32);
  927. if(bpp>16)
  928. bpp = 32;
  929. if(displayIndex < 0)
  930. {
  931. if (mainWindow != nullptr)
  932. displayIndex = SDL_GetWindowDisplayIndex(mainWindow);
  933. if (displayIndex < 0)
  934. displayIndex = 0;
  935. }
  936. #if defined(VCMI_ANDROID) || defined(VCMI_IOS)
  937. SDL_GetWindowSize(mainWindow, &w, &h);
  938. #else
  939. if(!checkVideoMode(displayIndex, w, h))
  940. {
  941. logGlobal->error("Error: SDL says that %dx%d resolution is not available!", w, h);
  942. }
  943. #endif
  944. bool bufOnScreen = (screenBuf == screen);
  945. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  946. /* match best rendering resolution */
  947. int renderWidth = 0, renderHeight = 0;
  948. auto aspectRatio = (float)w / (float)h;
  949. auto minDiff = 10.f;
  950. for (const auto& pair : conf.guiOptions)
  951. {
  952. int pWidth, pHeight;
  953. std::tie(pWidth, pHeight) = pair.first;
  954. /* filter out resolution which is larger than window */
  955. if (pWidth > w || pHeight > h)
  956. {
  957. continue;
  958. }
  959. auto ratio = (float)pWidth / (float)pHeight;
  960. auto diff = fabs(aspectRatio - ratio);
  961. /* select closest aspect ratio */
  962. if (diff < minDiff)
  963. {
  964. renderWidth = pWidth;
  965. renderHeight = pHeight;
  966. minDiff = diff;
  967. }
  968. /* select largest resolution meets prior conditions.
  969. * since there are resolutions like 1366x768(not exactly 16:9), a deviation of 0.005 is allowed. */
  970. else if (fabs(diff - minDiff) < 0.005f && pWidth > renderWidth)
  971. {
  972. renderWidth = pWidth;
  973. renderHeight = pHeight;
  974. }
  975. }
  976. if (renderWidth == 0)
  977. {
  978. // no matching resolution for upscaling - complain & fallback to default resolution.
  979. logGlobal->error("Failed to match rendering resolution for %dx%d!", w, h);
  980. Settings newRes = settings.write["video"]["screenRes"];
  981. std::tie(w, h) = conf.guiOptions.begin()->first;
  982. newRes["width"].Float() = w;
  983. newRes["height"].Float() = h;
  984. conf.SetResolution(w, h);
  985. logGlobal->error("Falling back to %dx%d", w, h);
  986. renderWidth = w;
  987. renderHeight = h;
  988. }
  989. else
  990. {
  991. logGlobal->info("Set logical rendering resolution to %dx%d", renderWidth, renderHeight);
  992. }
  993. cleanupRenderer();
  994. if(nullptr == mainWindow)
  995. {
  996. #if defined(VCMI_ANDROID) || defined(VCMI_IOS)
  997. auto createWindow = [displayIndex](Uint32 extraFlags) -> bool {
  998. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN | extraFlags);
  999. return mainWindow != nullptr;
  1000. };
  1001. # ifdef VCMI_IOS
  1002. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  1003. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  1004. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  1005. Uint32 windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  1006. if(!createWindow(windowFlags | SDL_WINDOW_METAL))
  1007. {
  1008. logGlobal->warn("Metal unavailable, using OpenGLES");
  1009. createWindow(windowFlags);
  1010. }
  1011. # else
  1012. createWindow(0);
  1013. # endif // VCMI_IOS
  1014. // SDL on mobile doesn't do proper letterboxing, and will show an annoying flickering in the blank space in case you're not using the full screen estate
  1015. // That's why we need to make sure our width and height we'll use below have the same aspect ratio as the screen itself to ensure we fill the full screen estate
  1016. SDL_Rect screenRect;
  1017. if(SDL_GetDisplayBounds(0, &screenRect) == 0)
  1018. {
  1019. const auto screenWidth = screenRect.w;
  1020. const auto screenHeight = screenRect.h;
  1021. const auto aspect = static_cast<double>(screenWidth) / screenHeight;
  1022. logGlobal->info("Screen size and aspect ratio: %dx%d (%lf)", screenWidth, screenHeight, aspect);
  1023. if((double)w / aspect > (double)h)
  1024. {
  1025. h = (int)round((double)w / aspect);
  1026. }
  1027. else
  1028. {
  1029. w = (int)round((double)h * aspect);
  1030. }
  1031. logGlobal->info("Changing logical screen size to %dx%d", w, h);
  1032. }
  1033. else
  1034. {
  1035. logGlobal->error("Can't fix aspect ratio for screen");
  1036. }
  1037. #else
  1038. if(fullscreen)
  1039. {
  1040. if(realFullscreen)
  1041. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), renderWidth, renderHeight, SDL_WINDOW_FULLSCREEN);
  1042. else //in windowed full-screen mode use desktop resolution
  1043. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
  1044. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  1045. }
  1046. else
  1047. {
  1048. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), w, h, 0);
  1049. }
  1050. #endif // defined(VCMI_ANDROID) || defined(VCMI_IOS)
  1051. if(nullptr == mainWindow)
  1052. {
  1053. throw std::runtime_error("Unable to create window\n");
  1054. }
  1055. //create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
  1056. mainRenderer = SDL_CreateRenderer(mainWindow,preferredDriverIndex,0);
  1057. if(nullptr == mainRenderer)
  1058. {
  1059. throw std::runtime_error("Unable to create renderer\n");
  1060. }
  1061. SDL_RendererInfo info;
  1062. SDL_GetRendererInfo(mainRenderer, &info);
  1063. logGlobal->info("Created renderer %s", info.name);
  1064. }
  1065. else
  1066. {
  1067. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  1068. if(fullscreen)
  1069. {
  1070. if(realFullscreen)
  1071. {
  1072. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  1073. SDL_DisplayMode mode;
  1074. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  1075. mode.w = renderWidth;
  1076. mode.h = renderHeight;
  1077. SDL_SetWindowDisplayMode(mainWindow, &mode);
  1078. }
  1079. else
  1080. {
  1081. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  1082. }
  1083. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  1084. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  1085. }
  1086. else
  1087. {
  1088. SDL_SetWindowFullscreen(mainWindow, 0);
  1089. SDL_SetWindowSize(mainWindow, w, h);
  1090. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  1091. }
  1092. #endif
  1093. }
  1094. if(!(fullscreen && realFullscreen))
  1095. {
  1096. SDL_RenderSetLogicalSize(mainRenderer, renderWidth, renderHeight);
  1097. //following line is bugged not only on android, do not re-enable without checking
  1098. //#ifndef VCMI_ANDROID
  1099. // // on android this stretches the game to fit the screen, not preserving aspect and apparently this also breaks coordinates scaling in mouse events
  1100. // SDL_RenderSetViewport(mainRenderer, nullptr);
  1101. //#endif
  1102. }
  1103. #if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
  1104. int bmask = 0xff000000;
  1105. int gmask = 0x00ff0000;
  1106. int rmask = 0x0000ff00;
  1107. int amask = 0x000000ff;
  1108. #else
  1109. int bmask = 0x000000ff;
  1110. int gmask = 0x0000ff00;
  1111. int rmask = 0x00ff0000;
  1112. int amask = 0xFF000000;
  1113. #endif
  1114. screen = SDL_CreateRGBSurface(0,renderWidth,renderHeight,bpp,rmask,gmask,bmask,amask);
  1115. if(nullptr == screen)
  1116. {
  1117. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", renderWidth, renderHeight, bpp, SDL_GetError());
  1118. throw std::runtime_error("Unable to create surface");
  1119. }
  1120. //No blending for screen itself. Required for proper cursor rendering.
  1121. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  1122. screenTexture = SDL_CreateTexture(mainRenderer,
  1123. SDL_PIXELFORMAT_ARGB8888,
  1124. SDL_TEXTUREACCESS_STREAMING,
  1125. renderWidth, renderHeight);
  1126. if(nullptr == screenTexture)
  1127. {
  1128. logGlobal->error("Unable to create screen texture");
  1129. logGlobal->error(SDL_GetError());
  1130. throw std::runtime_error("Unable to create screen texture");
  1131. }
  1132. screen2 = CSDL_Ext::copySurface(screen);
  1133. if(nullptr == screen2)
  1134. {
  1135. throw std::runtime_error("Unable to copy surface\n");
  1136. }
  1137. screenBuf = bufOnScreen ? screen : screen2;
  1138. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0);
  1139. SDL_RenderClear(mainRenderer);
  1140. SDL_RenderPresent(mainRenderer);
  1141. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  1142. {
  1143. NotificationHandler::init(mainWindow);
  1144. }
  1145. return true;
  1146. }
  1147. //used only once during initialization
  1148. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo)
  1149. {
  1150. if(!recreateWindow(w, h, bpp, fullscreen, displayIndex))
  1151. {
  1152. throw std::runtime_error("Requested screen resolution is not available\n");
  1153. }
  1154. }
  1155. static void fullScreenChanged()
  1156. {
  1157. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  1158. Settings full = settings.write["video"]["fullscreen"];
  1159. const bool toFullscreen = full->Bool();
  1160. auto bitsPerPixel = screen->format->BitsPerPixel;
  1161. auto w = screen->w;
  1162. auto h = screen->h;
  1163. if(!recreateWindow(w, h, bitsPerPixel, toFullscreen, -1))
  1164. {
  1165. //will return false and report error if video mode is not supported
  1166. return;
  1167. }
  1168. GH.totalRedraw();
  1169. }
  1170. static void handleEvent(SDL_Event & ev)
  1171. {
  1172. if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  1173. {
  1174. #ifdef VCMI_ANDROID
  1175. handleQuit(false);
  1176. #else
  1177. handleQuit();
  1178. #endif
  1179. return;
  1180. }
  1181. #ifdef VCMI_ANDROID
  1182. else if (ev.type == SDL_KEYDOWN && ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK)
  1183. {
  1184. handleQuit(true);
  1185. }
  1186. #endif
  1187. else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  1188. {
  1189. Settings full = settings.write["video"]["fullscreen"];
  1190. full->Bool() = !full->Bool();
  1191. return;
  1192. }
  1193. else if(ev.type == SDL_USEREVENT)
  1194. {
  1195. switch(ev.user.code)
  1196. {
  1197. case EUserEvent::FORCE_QUIT:
  1198. {
  1199. handleQuit(false);
  1200. return;
  1201. }
  1202. break;
  1203. case EUserEvent::RETURN_TO_MAIN_MENU:
  1204. {
  1205. CSH->endGameplay();
  1206. GH.defActionsDef = 63;
  1207. CMM->menu->switchToTab("main");
  1208. }
  1209. break;
  1210. case EUserEvent::RESTART_GAME:
  1211. {
  1212. CSH->sendRestartGame();
  1213. }
  1214. break;
  1215. case EUserEvent::CAMPAIGN_START_SCENARIO:
  1216. {
  1217. CSH->campaignServerRestartLock.set(true);
  1218. CSH->endGameplay();
  1219. auto ourCampaign = std::shared_ptr<CCampaignState>(reinterpret_cast<CCampaignState *>(ev.user.data1));
  1220. auto & epilogue = ourCampaign->camp->scenarios[ourCampaign->mapsConquered.back()].epilog;
  1221. auto finisher = [=]()
  1222. {
  1223. if(ourCampaign->mapsRemaining.size())
  1224. {
  1225. GH.pushInt(CMM);
  1226. GH.pushInt(CMM->menu);
  1227. CMM->openCampaignLobby(ourCampaign);
  1228. }
  1229. };
  1230. if(epilogue.hasPrologEpilog)
  1231. {
  1232. GH.pushIntT<CPrologEpilogVideo>(epilogue, finisher);
  1233. }
  1234. else
  1235. {
  1236. CSH->campaignServerRestartLock.waitUntil(false);
  1237. finisher();
  1238. }
  1239. }
  1240. break;
  1241. case EUserEvent::RETURN_TO_MENU_LOAD:
  1242. CSH->endGameplay();
  1243. GH.defActionsDef = 63;
  1244. CMM->menu->switchToTab("load");
  1245. break;
  1246. case EUserEvent::FULLSCREEN_TOGGLED:
  1247. fullScreenChanged();
  1248. break;
  1249. case EUserEvent::INTERFACE_CHANGED:
  1250. if(LOCPLINT)
  1251. LOCPLINT->updateAmbientSounds();
  1252. break;
  1253. default:
  1254. logGlobal->error("Unknown user event. Code %d", ev.user.code);
  1255. break;
  1256. }
  1257. return;
  1258. }
  1259. else if(ev.type == SDL_WINDOWEVENT)
  1260. {
  1261. switch (ev.window.event) {
  1262. case SDL_WINDOWEVENT_RESTORED:
  1263. #ifndef VCMI_IOS
  1264. fullScreenChanged();
  1265. #endif
  1266. break;
  1267. }
  1268. return;
  1269. }
  1270. else if(ev.type == SDL_SYSWMEVENT)
  1271. {
  1272. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  1273. {
  1274. NotificationHandler::handleSdlEvent(ev);
  1275. }
  1276. }
  1277. //preprocessing
  1278. if(ev.type == SDL_MOUSEMOTION)
  1279. {
  1280. CCS->curh->cursorMove(ev.motion.x, ev.motion.y);
  1281. }
  1282. {
  1283. boost::unique_lock<boost::mutex> lock(eventsM);
  1284. SDLEventsQueue.push(ev);
  1285. }
  1286. }
  1287. static void mainLoop()
  1288. {
  1289. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  1290. resChanged([](const JsonNode &newState){ CGuiHandler::pushSDLEvent(SDL_USEREVENT, EUserEvent::FULLSCREEN_TOGGLED); });
  1291. inGuiThread.reset(new bool(true));
  1292. GH.mainFPSmng->init();
  1293. while(1) //main SDL events loop
  1294. {
  1295. SDL_Event ev;
  1296. while(1 == SDL_PollEvent(&ev))
  1297. {
  1298. handleEvent(ev);
  1299. }
  1300. CSH->applyPacksOnLobbyScreen();
  1301. GH.renderFrame();
  1302. }
  1303. }
  1304. static void quitApplication()
  1305. {
  1306. if(!settings["session"]["headless"].Bool())
  1307. {
  1308. if(CSH->client)
  1309. CSH->endGameplay();
  1310. }
  1311. GH.listInt.clear();
  1312. GH.objsToBlit.clear();
  1313. CMM.reset();
  1314. if(!settings["session"]["headless"].Bool())
  1315. {
  1316. // cleanup, mostly to remove false leaks from analyzer
  1317. if(CCS)
  1318. {
  1319. CCS->musich->release();
  1320. CCS->soundh->release();
  1321. vstd::clear_pointer(CCS);
  1322. }
  1323. CMessage::dispose();
  1324. vstd::clear_pointer(graphics);
  1325. }
  1326. vstd::clear_pointer(VLC);
  1327. vstd::clear_pointer(console);// should be removed after everything else since used by logging
  1328. boost::this_thread::sleep(boost::posix_time::milliseconds(750));//???
  1329. if(!settings["session"]["headless"].Bool())
  1330. {
  1331. if(settings["general"]["notifications"].Bool())
  1332. {
  1333. NotificationHandler::destroy();
  1334. }
  1335. cleanupRenderer();
  1336. if(nullptr != mainRenderer)
  1337. {
  1338. SDL_DestroyRenderer(mainRenderer);
  1339. mainRenderer = nullptr;
  1340. }
  1341. if(nullptr != mainWindow)
  1342. {
  1343. SDL_DestroyWindow(mainWindow);
  1344. mainWindow = nullptr;
  1345. }
  1346. SDL_Quit();
  1347. }
  1348. if(logConfig != nullptr)
  1349. {
  1350. logConfig->deconfigure();
  1351. delete logConfig;
  1352. logConfig = nullptr;
  1353. }
  1354. std::cout << "Ending...\n";
  1355. exit(0);
  1356. }
  1357. void handleQuit(bool ask)
  1358. {
  1359. if(CSH->client && LOCPLINT && ask)
  1360. {
  1361. CCS->curh->set(Cursor::Map::POINTER);
  1362. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], [](){
  1363. // Workaround for assertion failure on exit:
  1364. // handleQuit() is alway called during SDL event processing
  1365. // during which, eventsM is kept locked
  1366. // this leads to assertion failure if boost::mutex is in locked state
  1367. eventsM.unlock();
  1368. quitApplication();
  1369. }, nullptr);
  1370. }
  1371. else
  1372. {
  1373. quitApplication();
  1374. }
  1375. }