CMT.cpp 34 KB

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