CMT.cpp 29 KB

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