CMT.cpp 34 KB

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