CMT.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. // CMT.cpp : Defines the entry point for the console application.
  2. //
  3. #include "StdInc.h"
  4. #include <SDL_mixer.h>
  5. #include "gui/SDL_Extensions.h"
  6. #include "CGameInfo.h"
  7. #include "mapHandler.h"
  8. #include "../lib/filesystem/Filesystem.h"
  9. #include "CPreGame.h"
  10. #include "windows/CCastleInterface.h"
  11. #include "../lib/CConsoleHandler.h"
  12. #include "gui/CCursorHandler.h"
  13. #include "../lib/CGameState.h"
  14. #include "../CCallback.h"
  15. #include "CPlayerInterface.h"
  16. #include "windows/CAdvmapInterface.h"
  17. #include "../lib/CBuildingHandler.h"
  18. #include "CVideoHandler.h"
  19. #include "../lib/CHeroHandler.h"
  20. #include "../lib/CCreatureHandler.h"
  21. #include "../lib/CSpellHandler.h"
  22. #include "CMusicHandler.h"
  23. #include "CVideoHandler.h"
  24. #include "CDefHandler.h"
  25. #include "../lib/CGeneralTextHandler.h"
  26. #include "Graphics.h"
  27. #include "Client.h"
  28. #include "../lib/CConfigHandler.h"
  29. #include "../lib/Connection.h"
  30. #include "../lib/VCMI_Lib.h"
  31. #include "../lib/VCMIDirs.h"
  32. #include "../lib/NetPacks.h"
  33. #include "CMessage.h"
  34. #include "../lib/CModHandler.h"
  35. #include "../lib/CTownHandler.h"
  36. #include "../lib/CArtHandler.h"
  37. #include "../lib/CScriptingModule.h"
  38. #include "../lib/GameConstants.h"
  39. #include "gui/CGuiHandler.h"
  40. #include "../lib/logging/CBasicLogConfigurator.h"
  41. #include "../lib/CondSh.h"
  42. #ifdef VCMI_WINDOWS
  43. #include "SDL_syswm.h"
  44. #endif
  45. #include "../lib/UnlockGuard.h"
  46. #include "CMT.h"
  47. #if __MINGW32__
  48. #undef main
  49. #endif
  50. namespace po = boost::program_options;
  51. namespace bfs = boost::filesystem;
  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. #ifndef VCMI_SDL1
  66. int preferredDriverIndex = -1;
  67. SDL_Window * mainWindow = nullptr;
  68. SDL_Renderer * mainRenderer = nullptr;
  69. SDL_Texture * screenTexture = nullptr;
  70. #endif // VCMI_SDL1
  71. extern boost::thread_specific_ptr<bool> inGuiThread;
  72. SDL_Surface *screen = nullptr, //main screen surface
  73. *screen2 = nullptr, //and hlp surface (used to store not-active interfaces layer)
  74. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  75. std::queue<SDL_Event> events;
  76. boost::mutex eventsM;
  77. bool gNoGUI = false;
  78. static po::variables_map vm;
  79. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  80. static bool ermInteractiveMode = false; //structurize when time is right
  81. void processCommand(const std::string &message);
  82. static void setScreenRes(int w, int h, int bpp, bool fullscreen, bool resetVideo=true);
  83. void dispose();
  84. void playIntro();
  85. static void mainLoop();
  86. //void requestChangingResolution();
  87. void startGame(StartInfo * options, CConnection *serv = nullptr);
  88. void endGame();
  89. #ifndef VCMI_WINDOWS
  90. #ifndef _GNU_SOURCE
  91. #define _GNU_SOURCE
  92. #endif
  93. #include <getopt.h>
  94. #endif
  95. void startGameFromFile(const bfs::path &fname)
  96. {
  97. StartInfo si;
  98. try //attempt retrieving start info from given file
  99. {
  100. if(fname.empty() || !bfs::exists(fname))
  101. throw std::runtime_error("Startfile \"" + fname.string() + "\" does not exist!");
  102. CLoadFile out(fname);
  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 VCMI_APPLE
  158. void OSX_checkForUpdates();
  159. #endif
  160. #if defined(VCMI_WINDOWS) && !defined (__GNUC__)
  161. int wmain(int argc, wchar_t* argv[])
  162. #elif defined(VCMI_APPLE)
  163. int SDL_main(int argc, char *argv[])
  164. #else
  165. int main(int argc, char** argv)
  166. #endif
  167. {
  168. #ifdef VCMI_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").string().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 logPath = VCMIDirs::get().userCachePath() / "VCMI_Client_log.txt";
  242. CBasicLogConfigurator logConfig(logPath, console);
  243. logConfig.configureDefault();
  244. logGlobal->infoStream() << "Creating console and configuring logger: " << pomtime.getDiff();
  245. logGlobal->infoStream() << "The log file will be saved to " << logPath;
  246. #ifdef VCMI_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 data"))
  265. exit(1); // These are unrecoverable errors
  266. // these two are optional + some installs have them on CD and not in data directory
  267. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  268. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  269. conf.init();
  270. logGlobal->infoStream() <<"Loading settings: "<<pomtime.getDiff();
  271. logGlobal->infoStream() << NAME;
  272. srand ( time(nullptr) );
  273. const JsonNode& video = settings["video"];
  274. const JsonNode& res = video["screenRes"];
  275. //something is really wrong...
  276. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  277. {
  278. logGlobal->errorStream() << "Fatal error: failed to load settings!";
  279. logGlobal->errorStream() << "Possible reasons:";
  280. logGlobal->errorStream() << "\tCorrupted local configuration file at " << VCMIDirs::get().userConfigPath() << "/settings.json";
  281. logGlobal->errorStream() << "\tMissing or corrupted global configuration file at " << VCMIDirs::get().userConfigPath() << "/schemas/settings.json";
  282. logGlobal->errorStream() << "VCMI will now exit...";
  283. exit(EXIT_FAILURE);
  284. }
  285. if(!gNoGUI)
  286. {
  287. #ifdef VCMI_SDL1
  288. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
  289. #else
  290. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_NOPARACHUTE))
  291. #endif
  292. {
  293. logGlobal->errorStream()<<"Something was wrong: "<< SDL_GetError();
  294. exit(-1);
  295. }
  296. GH.mainFPSmng->init(); //(!)init here AFTER SDL_Init() while using SDL for FPS management
  297. atexit(SDL_Quit);
  298. #ifndef VCMI_SDL1
  299. int driversCount = SDL_GetNumRenderDrivers();
  300. std::string preferredDriverName = video["driver"].String();
  301. logGlobal->infoStream() << "Found " << driversCount << " render drivers";
  302. for(int it = 0; it < driversCount; it++)
  303. {
  304. SDL_RendererInfo info;
  305. SDL_GetRenderDriverInfo(it,&info);
  306. std::string driverName(info.name);
  307. logGlobal->infoStream() << "\t" << driverName;
  308. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  309. {
  310. preferredDriverIndex = it;
  311. logGlobal->infoStream() << "\t\twill select this";
  312. }
  313. }
  314. #endif // VCMI_SDL1
  315. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  316. logGlobal->infoStream() <<"\tInitializing screen: "<<pomtime.getDiff();
  317. }
  318. CCS = new CClientState;
  319. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
  320. // Initialize video
  321. #ifdef DISABLE_VIDEO
  322. CCS->videoh = new CEmptyVideoPlayer;
  323. #else
  324. if (!gNoGUI && !vm.count("disable-video"))
  325. CCS->videoh = new CVideoPlayer;
  326. else
  327. CCS->videoh = new CEmptyVideoPlayer;
  328. #endif
  329. logGlobal->infoStream()<<"\tInitializing video: "<<pomtime.getDiff();
  330. #if defined(VCMI_ANDROID)
  331. //on Android threaded init is broken
  332. #define VCMI_NO_THREADED_LOAD
  333. #endif // defined
  334. //initializing audio
  335. // Note: because of interface button range, volume can only be a
  336. // multiple of 11, from 0 to 99.
  337. CCS->soundh = new CSoundHandler;
  338. CCS->soundh->init();
  339. CCS->soundh->setVolume(settings["general"]["sound"].Float());
  340. CCS->musich = new CMusicHandler;
  341. CCS->musich->init();
  342. CCS->musich->setVolume(settings["general"]["music"].Float());
  343. logGlobal->infoStream()<<"Initializing screen and sound handling: "<<pomtime.getDiff();
  344. #ifndef VCMI_NO_THREADED_LOAD
  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. init();
  349. #endif
  350. if(!gNoGUI )
  351. {
  352. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  353. playIntro();
  354. SDL_FillRect(screen,nullptr,0);
  355. }
  356. CSDL_Ext::update(screen);
  357. #ifndef VCMI_NO_THREADED_LOAD
  358. loading.join();
  359. #endif
  360. logGlobal->infoStream()<<"Initialization of VCMI (together): "<<total.getDiff();
  361. if(!vm.count("battle"))
  362. {
  363. Settings session = settings.write["session"];
  364. session["autoSkip"].Bool() = vm.count("autoSkip");
  365. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  366. bfs::path fileToStartFrom; //none by default
  367. if(vm.count("start"))
  368. fileToStartFrom = vm["start"].as<bfs::path>();
  369. if(!fileToStartFrom.empty() && bfs::exists(fileToStartFrom))
  370. startGameFromFile(fileToStartFrom); //ommit pregame and start the game using settings from file
  371. else
  372. {
  373. if(!fileToStartFrom.empty())
  374. {
  375. logGlobal->warnStream() << "Warning: cannot find given file to start from (" << fileToStartFrom
  376. << "). Falling back to main menu.";
  377. }
  378. GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
  379. }
  380. }
  381. else
  382. {
  383. auto si = new StartInfo();
  384. si->mode = StartInfo::DUEL;
  385. si->mapname = vm["battle"].as<std::string>();
  386. si->playerInfos[PlayerColor(0)].color = PlayerColor(0);
  387. si->playerInfos[PlayerColor(1)].color = PlayerColor(1);
  388. startGame(si);
  389. }
  390. if(!gNoGUI)
  391. {
  392. mainLoop();
  393. }
  394. else
  395. {
  396. while(true)
  397. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  398. }
  399. return 0;
  400. }
  401. void printInfoAboutIntObject(const CIntObject *obj, int level)
  402. {
  403. std::stringstream sbuffer;
  404. sbuffer << std::string(level, '\t');
  405. sbuffer << typeid(*obj).name() << " *** ";
  406. if (obj->active)
  407. {
  408. #define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
  409. PRINT(LCLICK, 'L');
  410. PRINT(RCLICK, 'R');
  411. PRINT(HOVER, 'H');
  412. PRINT(MOVE, 'M');
  413. PRINT(KEYBOARD, 'K');
  414. PRINT(TIME, 'T');
  415. PRINT(GENERAL, 'A');
  416. PRINT(WHEEL, 'W');
  417. PRINT(DOUBLECLICK, 'D');
  418. #undef PRINT
  419. }
  420. else
  421. sbuffer << "inactive";
  422. sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
  423. sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
  424. logGlobal->infoStream() << sbuffer.str();
  425. for(const CIntObject *child : obj->children)
  426. printInfoAboutIntObject(child, level+1);
  427. }
  428. void processCommand(const std::string &message)
  429. {
  430. std::istringstream readed;
  431. readed.str(message);
  432. std::string cn; //command name
  433. readed >> cn;
  434. if(LOCPLINT && LOCPLINT->cingconsole)
  435. LOCPLINT->cingconsole->print(message);
  436. if(ermInteractiveMode)
  437. {
  438. if(cn == "exit")
  439. {
  440. ermInteractiveMode = false;
  441. return;
  442. }
  443. else
  444. {
  445. if(client && client->erm)
  446. client->erm->executeUserCommand(message);
  447. std::cout << "erm>";
  448. }
  449. }
  450. else if(message==std::string("die, fool"))
  451. {
  452. exit(EXIT_SUCCESS);
  453. }
  454. else if(cn == "erm")
  455. {
  456. ermInteractiveMode = true;
  457. std::cout << "erm>";
  458. }
  459. else if(cn==std::string("activate"))
  460. {
  461. int what;
  462. readed >> what;
  463. switch (what)
  464. {
  465. case 0:
  466. GH.topInt()->activate();
  467. break;
  468. case 1:
  469. adventureInt->activate();
  470. break;
  471. case 2:
  472. LOCPLINT->castleInt->activate();
  473. break;
  474. }
  475. }
  476. else if(cn=="redraw")
  477. {
  478. GH.totalRedraw();
  479. }
  480. else if(cn=="screen")
  481. {
  482. std::cout << "Screenbuf points to ";
  483. if(screenBuf == screen)
  484. logGlobal->errorStream() << "screen";
  485. else if(screenBuf == screen2)
  486. logGlobal->errorStream() << "screen2";
  487. else
  488. logGlobal->errorStream() << "?!?";
  489. SDL_SaveBMP(screen, "Screen_c.bmp");
  490. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  491. }
  492. else if(cn=="save")
  493. {
  494. std::string fname;
  495. readed >> fname;
  496. client->save(fname);
  497. }
  498. else if(cn=="load")
  499. {
  500. // TODO: this code should end the running game and manage to call startGame instead
  501. std::string fname;
  502. readed >> fname;
  503. client->loadGame(fname);
  504. }
  505. else if(message=="get txt")
  506. {
  507. std::cout<<"Command accepted.\t";
  508. const bfs::path outPath =
  509. 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. const bfs::path filePath = outPath / (filename.getName() + ".TXT");
  517. bfs::create_directories(filePath.parent_path());
  518. bfs::ofstream file(filePath);
  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. const bfs::path outPath = VCMIDirs::get().userCachePath() / "extracted" / URI;
  626. bfs::create_directories(outPath);
  627. for (size_t i = 0; i < cde->ourImages.size(); ++i)
  628. {
  629. const bfs::path filePath = outPath / (boost::lexical_cast<std::string>(i)+".bmp");
  630. SDL_SaveBMP(cde->ourImages[i].bitmap, filePath.string().c_str());
  631. }
  632. }
  633. else
  634. logGlobal->errorStream() << "File not found!";
  635. }
  636. else if(cn == "extract")
  637. {
  638. std::string URI;
  639. readed >> URI;
  640. if (CResourceHandler::get()->existsResource(ResourceID(URI)))
  641. {
  642. const bfs::path outPath = VCMIDirs::get().userCachePath() / "extracted" / URI;
  643. auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll();
  644. bfs::create_directories(outPath.parent_path());
  645. bfs::ofstream outFile(outPath, bfs::ofstream::binary);
  646. outFile.write((char*)data.first.get(), data.second);
  647. }
  648. else
  649. logGlobal->errorStream() << "File not found!";
  650. }
  651. else if(cn == "setBattleAI")
  652. {
  653. std::string fname;
  654. readed >> fname;
  655. std::cout << "Will try loading that AI to see if it is correct name...\n";
  656. try
  657. {
  658. 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
  659. {
  660. Settings neutralAI = settings.write["server"]["neutralAI"];
  661. neutralAI->String() = fname;
  662. std::cout << "Setting changed, from now the battle ai will be " << fname << "!\n";
  663. }
  664. }
  665. catch(std::exception &e)
  666. {
  667. logGlobal->warnStream() << "Failed opening " << fname << ": " << e.what();
  668. logGlobal->warnStream() << "Setting not changes, AI not found or invalid!";
  669. }
  670. }
  671. else if(cn == "autoskip")
  672. {
  673. Settings session = settings.write["session"];
  674. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  675. }
  676. else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  677. {
  678. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  679. LOCPLINT->cb->sendMessage(message);
  680. }
  681. }
  682. //plays intro, ends when intro is over or button has been pressed (handles events)
  683. void playIntro()
  684. {
  685. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 60, 40, screen, true))
  686. {
  687. CCS->videoh->openAndPlayVideo("AZVS.SMK", 60, 80, screen, true);
  688. }
  689. }
  690. void dispose()
  691. {
  692. if (console)
  693. delete console;
  694. // cleanup, mostly to remove false leaks from analyzer
  695. CResourceHandler::clear();
  696. if (CCS)
  697. {
  698. CCS->musich->release();
  699. CCS->soundh->release();
  700. }
  701. CMessage::dispose();
  702. }
  703. static bool checkVideoMode(int monitorIndex, int w, int h, int& bpp, bool fullscreen)
  704. {
  705. #ifndef VCMI_SDL1
  706. SDL_DisplayMode mode;
  707. const int modeCount = SDL_GetNumDisplayModes(monitorIndex);
  708. for (int i = 0; i < modeCount; i++) {
  709. SDL_GetDisplayMode(0, i, &mode);
  710. if (!mode.w || !mode.h || (w >= mode.w && h >= mode.h)) {
  711. return true;
  712. }
  713. }
  714. return false;
  715. #else
  716. bpp = SDL_VideoModeOK(w, h, bpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  717. return !(bpp==0);
  718. #endif // VCMI_SDL1
  719. }
  720. #ifndef VCMI_SDL1
  721. static bool recreateWindow(int w, int h, int bpp, bool fullscreen)
  722. {
  723. // VCMI will only work with 2 or 4 bytes per pixel
  724. vstd::amax(bpp, 16);
  725. vstd::amin(bpp, 32);
  726. if(bpp>16)
  727. bpp = 32;
  728. int suggestedBpp = bpp;
  729. if(!checkVideoMode(0,w,h,suggestedBpp,fullscreen))
  730. {
  731. logGlobal->errorStream() << "Error: SDL says that " << w << "x" << h << " resolution is not available!";
  732. return false;
  733. }
  734. bool bufOnScreen = (screenBuf == screen);
  735. screenBuf = nullptr; //it`s a link - just nullify
  736. if(nullptr != screen2)
  737. {
  738. SDL_FreeSurface(screen2);
  739. screen2 = nullptr;
  740. }
  741. if(nullptr != screen)
  742. {
  743. SDL_FreeSurface(screen);
  744. screen = nullptr;
  745. }
  746. if(nullptr != screenTexture)
  747. {
  748. SDL_DestroyTexture(screenTexture);
  749. screenTexture = nullptr;
  750. }
  751. if(nullptr != mainRenderer)
  752. {
  753. SDL_DestroyRenderer(mainRenderer);
  754. mainRenderer = nullptr;
  755. }
  756. if(nullptr != mainWindow)
  757. {
  758. SDL_DestroyWindow(mainWindow);
  759. mainWindow = nullptr;
  760. }
  761. if(fullscreen)
  762. {
  763. //in full-screen mode always use desktop resolution
  764. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
  765. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  766. }
  767. else
  768. {
  769. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED, w, h, 0);
  770. }
  771. if(nullptr == mainWindow)
  772. {
  773. throw std::runtime_error("Unable to create window\n");
  774. }
  775. //create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
  776. mainRenderer = SDL_CreateRenderer(mainWindow,preferredDriverIndex,0);
  777. if(nullptr == mainRenderer)
  778. {
  779. throw std::runtime_error("Unable to create renderer\n");
  780. }
  781. SDL_RendererInfo info;
  782. SDL_GetRendererInfo(mainRenderer,&info);
  783. logGlobal->infoStream() << "Created renderer " << info.name;
  784. SDL_RenderSetLogicalSize(mainRenderer, w, h);
  785. SDL_RenderSetViewport(mainRenderer, nullptr);
  786. #if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
  787. int bmask = 0xff000000;
  788. int gmask = 0x00ff0000;
  789. int rmask = 0x0000ff00;
  790. int amask = 0x000000ff;
  791. #else
  792. int bmask = 0x000000ff;
  793. int gmask = 0x0000ff00;
  794. int rmask = 0x00ff0000;
  795. int amask = 0xFF000000;
  796. #endif
  797. screen = SDL_CreateRGBSurface(0,w,h,bpp,rmask,gmask,bmask,amask);
  798. if(nullptr == screen)
  799. {
  800. logGlobal->errorStream() << "Unable to create surface";
  801. logGlobal->errorStream() << w << " "<< h << " "<< bpp;
  802. logGlobal->errorStream() << SDL_GetError();
  803. throw std::runtime_error("Unable to create surface");
  804. }
  805. //No blending for screen itself. Required for proper cursor rendering.
  806. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  807. screenTexture = SDL_CreateTexture(mainRenderer,
  808. SDL_PIXELFORMAT_ARGB8888,
  809. SDL_TEXTUREACCESS_STREAMING,
  810. w, h);
  811. if(nullptr == screenTexture)
  812. {
  813. logGlobal->errorStream() << "Unable to create screen texture";
  814. logGlobal->errorStream() << SDL_GetError();
  815. throw std::runtime_error("Unable to create screen texture");
  816. }
  817. screen2 = CSDL_Ext::copySurface(screen);
  818. if(nullptr == screen2)
  819. {
  820. throw std::runtime_error("Unable to copy surface\n");
  821. }
  822. screenBuf = bufOnScreen ? screen : screen2;
  823. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0);
  824. SDL_RenderClear(mainRenderer);
  825. SDL_RenderPresent(mainRenderer);
  826. return true;
  827. }
  828. #endif
  829. //used only once during initialization
  830. static void setScreenRes(int w, int h, int bpp, bool fullscreen, bool resetVideo)
  831. {
  832. #ifdef VCMI_SDL1
  833. // VCMI will only work with 2, 3 or 4 bytes per pixel
  834. vstd::amax(bpp, 16);
  835. vstd::amin(bpp, 32);
  836. // Try to use the best screen depth for the display
  837. int suggestedBpp = SDL_VideoModeOK(w, h, bpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  838. if(suggestedBpp == 0)
  839. {
  840. logGlobal->errorStream() << "Error: SDL says that " << w << "x" << h << " resolution is not available!";
  841. return;
  842. }
  843. bool bufOnScreen = (screenBuf == screen);
  844. if(suggestedBpp != bpp)
  845. {
  846. logGlobal->infoStream() << boost::format("Using %s bpp (bits per pixel) for the video mode. Default or overridden setting was %s bpp.") % suggestedBpp % bpp;
  847. }
  848. //For some reason changing fullscreen via config window checkbox result in SDL_Quit event
  849. if (resetVideo)
  850. {
  851. if(screen) //screen has been already initialized
  852. SDL_QuitSubSystem(SDL_INIT_VIDEO);
  853. SDL_InitSubSystem(SDL_INIT_VIDEO);
  854. }
  855. if((screen = SDL_SetVideoMode(w, h, suggestedBpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0))) == nullptr)
  856. {
  857. logGlobal->errorStream() << "Requested screen resolution is not available (" << w << "x" << h << "x" << suggestedBpp << "bpp)";
  858. throw std::runtime_error("Requested screen resolution is not available\n");
  859. }
  860. logGlobal->infoStream() << "New screen flags: " << screen->flags;
  861. if(screen2)
  862. SDL_FreeSurface(screen2);
  863. screen2 = CSDL_Ext::copySurface(screen);
  864. SDL_EnableUNICODE(1);
  865. SDL_WM_SetCaption(NAME.c_str(),""); //set window title
  866. SDL_ShowCursor(SDL_DISABLE);
  867. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  868. #ifdef VCMI_WINDOWS
  869. SDL_SysWMinfo wm;
  870. SDL_VERSION(&wm.version);
  871. int getwm = SDL_GetWMInfo(&wm);
  872. if(getwm == 1)
  873. {
  874. int sw = GetSystemMetrics(SM_CXSCREEN),
  875. sh = GetSystemMetrics(SM_CYSCREEN);
  876. RECT curpos;
  877. GetWindowRect(wm.window,&curpos);
  878. int ourw = curpos.right - curpos.left,
  879. ourh = curpos.bottom - curpos.top;
  880. SetWindowPos(wm.window, 0, (sw - ourw)/2, (sh - ourh)/2, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
  881. }
  882. else
  883. {
  884. logGlobal->warnStream() << "Something went wrong, getwm=" << getwm;
  885. logGlobal->warnStream() << "SDL says: " << SDL_GetError();
  886. logGlobal->warnStream() << "Window won't be centered.";
  887. }
  888. #endif
  889. //TODO: centering game window on other platforms (or does the environment do their job correctly there?)
  890. screenBuf = bufOnScreen ? screen : screen2;
  891. //setResolution = true;
  892. #else
  893. if(!recreateWindow(w,h,bpp,fullscreen))
  894. {
  895. throw std::runtime_error("Requested screen resolution is not available\n");
  896. }
  897. #endif // VCMI_SDL1
  898. }
  899. static void fullScreenChanged()
  900. {
  901. boost::unique_lock<boost::recursive_mutex> lock(*LOCPLINT->pim);
  902. Settings full = settings.write["video"]["fullscreen"];
  903. const bool toFullscreen = full->Bool();
  904. auto bitsPerPixel = screen->format->BitsPerPixel;
  905. #ifdef VCMI_SDL1
  906. bitsPerPixel = SDL_VideoModeOK(screen->w, screen->h, bitsPerPixel, SDL_SWSURFACE|(toFullscreen?SDL_FULLSCREEN:0));
  907. if(bitsPerPixel == 0)
  908. {
  909. logGlobal->errorStream() << "Error: SDL says that " << screen->w << "x" << screen->h << " resolution is not available!";
  910. return;
  911. }
  912. bool bufOnScreen = (screenBuf == screen);
  913. screen = SDL_SetVideoMode(screen->w, screen->h, bitsPerPixel, SDL_SWSURFACE|(toFullscreen?SDL_FULLSCREEN:0));
  914. screenBuf = bufOnScreen ? screen : screen2;
  915. #else
  916. auto w = screen->w;
  917. auto h = screen->h;
  918. if(!recreateWindow(w,h,bitsPerPixel,toFullscreen))
  919. {
  920. //will return false and report error if video mode is not supported
  921. return;
  922. }
  923. #endif
  924. GH.totalRedraw();
  925. }
  926. static void handleEvent(SDL_Event & ev)
  927. {
  928. if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  929. {
  930. handleQuit();
  931. return;
  932. }
  933. #ifdef VCMI_SDL1
  934. //FIXME: this should work even in pregame
  935. else if(LOCPLINT && ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  936. #else
  937. else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  938. #endif // VCMI_SDL1
  939. {
  940. Settings full = settings.write["video"]["fullscreen"];
  941. full->Bool() = !full->Bool();
  942. return;
  943. }
  944. else if(ev.type == SDL_USEREVENT)
  945. {
  946. switch(ev.user.code)
  947. {
  948. case RETURN_TO_MAIN_MENU:
  949. {
  950. endGame();
  951. GH.curInt = CGPreGame::create();;
  952. GH.defActionsDef = 63;
  953. }
  954. break;
  955. case STOP_CLIENT:
  956. client->endGame(false);
  957. break;
  958. case RESTART_GAME:
  959. {
  960. StartInfo si = *client->getStartInfo(true);
  961. endGame();
  962. startGame(&si);
  963. }
  964. break;
  965. case PREPARE_RESTART_CAMPAIGN:
  966. {
  967. auto si = reinterpret_cast<StartInfo *>(ev.user.data1);
  968. endGame();
  969. startGame(si);
  970. }
  971. break;
  972. case RETURN_TO_MENU_LOAD:
  973. endGame();
  974. CGPreGame::create();
  975. GH.defActionsDef = 63;
  976. CGP->update();
  977. CGP->menu->switchToTab(vstd::find_pos(CGP->menu->menuNameToEntry, "load"));
  978. GH.curInt = CGP;
  979. break;
  980. case FULLSCREEN_TOGGLED:
  981. fullScreenChanged();
  982. break;
  983. default:
  984. logGlobal->errorStream() << "Unknown user event. Code " << ev.user.code;
  985. break;
  986. }
  987. return;
  988. }
  989. {
  990. boost::unique_lock<boost::mutex> lock(eventsM);
  991. events.push(ev);
  992. }
  993. }
  994. static void mainLoop()
  995. {
  996. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  997. resChanged([](const JsonNode &newState){ CGuiHandler::pushSDLEvent(SDL_USEREVENT, FULLSCREEN_TOGGLED); });
  998. inGuiThread.reset(new bool(true));
  999. GH.mainFPSmng->init();
  1000. while(1) //main SDL events loop
  1001. {
  1002. SDL_Event ev;
  1003. while(1 == SDL_PollEvent(&ev))
  1004. {
  1005. handleEvent(ev);
  1006. }
  1007. GH.renderFrame();
  1008. }
  1009. }
  1010. void startGame(StartInfo * options, CConnection *serv/* = nullptr*/)
  1011. {
  1012. if(vm.count("onlyAI"))
  1013. {
  1014. auto ais = vm.count("ai") ? vm["ai"].as<std::vector<std::string>>() : std::vector<std::string>();
  1015. int i = 0;
  1016. for(auto & elem : options->playerInfos)
  1017. {
  1018. elem.second.playerID = PlayerSettings::PLAYER_AI;
  1019. if(i < ais.size())
  1020. elem.second.name = ais[i++];
  1021. }
  1022. }
  1023. client = new CClient;
  1024. CPlayerInterface::howManyPeople = 0;
  1025. switch(options->mode) //new game
  1026. {
  1027. case StartInfo::NEW_GAME:
  1028. case StartInfo::CAMPAIGN:
  1029. case StartInfo::DUEL:
  1030. client->newGame(serv, options);
  1031. break;
  1032. case StartInfo::LOAD_GAME:
  1033. std::string fname = options->mapname;
  1034. boost::algorithm::erase_last(fname,".vlgm1");
  1035. client->loadGame(fname);
  1036. break;
  1037. }
  1038. client->connectionHandler = new boost::thread(&CClient::run, client);
  1039. }
  1040. void endGame()
  1041. {
  1042. client->endGame();
  1043. vstd::clear_pointer(client);
  1044. }
  1045. void handleQuit()
  1046. {
  1047. auto quitApplication = []()
  1048. {
  1049. if(client)
  1050. endGame();
  1051. delete console;
  1052. console = nullptr;
  1053. boost::this_thread::sleep(boost::posix_time::milliseconds(750));
  1054. if(!gNoGUI)
  1055. SDL_Quit();
  1056. std::cout << "Ending...\n";
  1057. exit(0);
  1058. };
  1059. if(client && LOCPLINT)
  1060. {
  1061. CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
  1062. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], quitApplication, 0);
  1063. }
  1064. else
  1065. {
  1066. quitApplication();
  1067. }
  1068. }