CMT.cpp 39 KB

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