CMT.cpp 29 KB

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