CMT.cpp 31 KB

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