CMT.cpp 28 KB

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