CMT.cpp 26 KB

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