CMT.cpp 29 KB

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