CMT.cpp 38 KB

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