CMT.cpp 36 KB

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