CMT.cpp 37 KB

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