CMT.cpp 39 KB

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