CMT.cpp 34 KB

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