CMT.cpp 34 KB

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