CMT.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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 "UIFramework/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 "UIFramework/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 "UIFramework/CGuiHandler.h"
  41. #ifdef _WIN32
  42. #include "SDL_syswm.h"
  43. #endif
  44. #include "../lib/CDefObjInfoHandler.h"
  45. #include "../lib/UnlockGuard.h"
  46. #if __MINGW32__
  47. #undef main
  48. #endif
  49. namespace po = boost::program_options;
  50. /*
  51. * CMT.cpp, part of VCMI engine
  52. *
  53. * Authors: listed in file AUTHORS in main folder
  54. *
  55. * License: GNU General Public License v2.0 or later
  56. * Full text of license available in license.txt file, in main folder
  57. *
  58. */
  59. std::string NAME_AFFIX = "client";
  60. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  61. CGuiHandler GH;
  62. static CClient *client=NULL;
  63. SDL_Surface *screen = NULL, //main screen surface
  64. *screen2 = NULL,//and hlp surface (used to store not-active interfaces layer)
  65. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  66. static boost::thread *mainGUIThread;
  67. std::queue<SDL_Event> events;
  68. boost::mutex eventsM;
  69. static bool gOnlyAI = false;
  70. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  71. static bool ermInteractiveMode = false; //structurize when time is right
  72. void processCommand(const std::string &message);
  73. static void setScreenRes(int w, int h, int bpp, bool fullscreen, bool resetVideo=true);
  74. void dispose();
  75. void playIntro();
  76. static void listenForEvents();
  77. //void requestChangingResolution();
  78. void startGame(StartInfo * options, CConnection *serv = NULL);
  79. #ifndef _WIN32
  80. #ifndef _GNU_SOURCE
  81. #define _GNU_SOURCE
  82. #endif
  83. #include <getopt.h>
  84. #endif
  85. void startGameFromFile(const std::string &fname)
  86. {
  87. if(fname.size() && boost::filesystem::exists(fname))
  88. {
  89. StartInfo si;
  90. CLoadFile out(fname);
  91. if(!out.sfile || !*out.sfile)
  92. {
  93. tlog1 << "Failed to open startfile, falling back to the main menu!\n";
  94. GH.curInt = CGPreGame::create();
  95. return;
  96. }
  97. out >> si;
  98. while(GH.topInt())
  99. GH.popIntTotally(GH.topInt());
  100. startGame(&si);
  101. }
  102. }
  103. void init()
  104. {
  105. CStopWatch tmh, pomtime;
  106. tlog0 << "\tInitializing minors: " << pomtime.getDiff() << std::endl;
  107. //initializing audio
  108. // Note: because of interface button range, volume can only be a
  109. // multiple of 11, from 0 to 99.
  110. CCS->soundh = new CSoundHandler;
  111. CCS->soundh->init();
  112. CCS->soundh->setVolume(settings["general"]["sound"].Float());
  113. CCS->musich = new CMusicHandler;
  114. CCS->musich->init();
  115. CCS->musich->setVolume(settings["general"]["music"].Float());
  116. tlog0<<"\tInitializing sound: "<<pomtime.getDiff()<<std::endl;
  117. tlog0<<"Initializing screen and sound handling: "<<tmh.getDiff()<<std::endl;
  118. loadDLLClasses();
  119. const_cast<CGameInfo*>(CGI)->setFromLib();
  120. CCS->soundh->initCreaturesSounds(CGI->creh->creatures);
  121. CCS->soundh->initSpellsSounds(CGI->spellh->spells);
  122. tlog0<<"Initializing VCMI_Lib: "<<tmh.getDiff()<<std::endl;
  123. pomtime.getDiff();
  124. CCS->curh = new CCursorHandler;
  125. CCS->curh->initCursor();
  126. CCS->curh->show();
  127. tlog0<<"Screen handler: "<<pomtime.getDiff()<<std::endl;
  128. pomtime.getDiff();
  129. graphics = new Graphics();
  130. graphics->loadHeroAnims();
  131. tlog0<<"\tMain graphics: "<<tmh.getDiff()<<std::endl;
  132. tlog0<<"Initializing game graphics: "<<tmh.getDiff()<<std::endl;
  133. CMessage::init();
  134. tlog0<<"Message handler: "<<tmh.getDiff()<<std::endl;
  135. //CPG = new CPreGame(); //main menu and submenus
  136. //tlog0<<"Initialization CPreGame (together): "<<tmh.getDif()<<std::endl;
  137. }
  138. static void prog_version(void)
  139. {
  140. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  141. printf(" data directory: %s\n", GameConstants::DATA_DIR.c_str());
  142. printf(" library directory: %s\n", GameConstants::LIB_DIR.c_str());
  143. printf(" binary directory: %s\n", GameConstants::BIN_DIR.c_str());
  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-2012 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 _WIN32
  158. int _tmain(int argc, _TCHAR* argv[])
  159. #elif defined(__APPLE__)
  160. int SDL_main(int argc, char *argv[])
  161. #else
  162. int main(int argc, char** argv)
  163. #endif
  164. {
  165. #ifdef __APPLE__
  166. // Correct working dir executable folder (not bundle folder) so we can use executable relative pathes
  167. std::string executablePath = argv[0];
  168. std::string workDir = executablePath.substr(0, executablePath.rfind('/'));
  169. chdir(workDir.c_str());
  170. FILE* check = fopen("../Data/game_data_prepared", "r");
  171. if (check == NULL) {
  172. system("open ./vcmibuilder.app");
  173. return 0;
  174. }
  175. fclose(check);
  176. #endif
  177. tlog0 << "Starting... " << std::endl;
  178. po::options_description opts("Allowed options");
  179. opts.add_options()
  180. ("help,h", "display help and exit")
  181. ("version,v", "display version information and exit")
  182. ("battle,b", po::value<std::string>(), "runs game in duel mode (battle-only")
  183. ("start", po::value<std::string>(), "starts game from saved StartInfo file")
  184. ("onlyAI", "runs without GUI, all players will be default AI")
  185. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  186. ("autoSkip", "automatically skip turns in GUI")
  187. ("disable-video", "disable video player")
  188. ("nointro,i", "skips intro movies");
  189. po::variables_map vm;
  190. if(argc > 1)
  191. {
  192. try
  193. {
  194. po::store(po::parse_command_line(argc, argv, opts), vm);
  195. }
  196. catch(std::exception &e)
  197. {
  198. tlog1 << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  199. }
  200. }
  201. po::notify(vm);
  202. if(vm.count("help"))
  203. {
  204. prog_help(opts);
  205. return 0;
  206. }
  207. if(vm.count("version"))
  208. {
  209. prog_version();
  210. return 0;
  211. }
  212. //Set environment vars to make window centered. Sometimes work, sometimes not. :/
  213. putenv((char*)"SDL_VIDEO_WINDOW_POS");
  214. putenv((char*)"SDL_VIDEO_CENTERED=1");
  215. CStopWatch total, pomtime;
  216. std::cout.flags(std::ios::unitbuf);
  217. logfile = new std::ofstream((GVCMIDirs.UserPath + "/VCMI_Client_log.txt").c_str());
  218. console = new CConsoleHandler;
  219. *console->cb = boost::bind(&processCommand, _1);
  220. console->start();
  221. atexit(dispose);
  222. tlog0 <<"Creating console and logfile: "<<pomtime.getDiff() << std::endl;
  223. preinitDLL(::console, logfile);
  224. settings.init();
  225. conf.init();
  226. tlog0 <<"Loading settings: "<<pomtime.getDiff() << std::endl;
  227. tlog0 << NAME << std::endl;
  228. srand ( time(NULL) );
  229. CCS = new CClientState;
  230. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
  231. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
  232. {
  233. tlog1<<"Something was wrong: "<< SDL_GetError() << std::endl;
  234. exit(-1);
  235. }
  236. atexit(SDL_Quit);
  237. const JsonNode& video = settings["video"];
  238. const JsonNode& res = video["screenRes"];
  239. //something is really wrong...
  240. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  241. {
  242. tlog0 << "Fatal error: failed to load settings!\n";
  243. tlog0 << "Possible reasons:\n";
  244. tlog0 << "\tCorrupted local configuration file at " << GVCMIDirs.UserPath << "/config/settings.json\n";
  245. tlog0 << "\tMissing or corrupted global configuration file at " << GameConstants::DATA_DIR << "/config/defaultSettings.json\n";
  246. tlog0 << "VCMI will now exit...\n";
  247. exit(EXIT_FAILURE);
  248. }
  249. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  250. tlog0 <<"\tInitializing screen: "<<pomtime.getDiff() << std::endl;
  251. // Initialize video
  252. #if DISABLE_VIDEO
  253. CCS->videoh = new CEmptyVideoPlayer;
  254. #else
  255. if (!vm.count("disable-video"))
  256. CCS->videoh = new CVideoPlayer;
  257. else
  258. CCS->videoh = new CEmptyVideoPlayer;
  259. #endif
  260. tlog0<<"\tInitializing video: "<<pomtime.getDiff()<<std::endl;
  261. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  262. boost::thread loading(init);
  263. if(!vm.count("battle") && !vm.count("nointro"))
  264. playIntro();
  265. SDL_FillRect(screen,NULL,0);
  266. CSDL_Ext::update(screen);
  267. loading.join();
  268. tlog0<<"Initialization of VCMI (together): "<<total.getDiff()<<std::endl;
  269. if(!vm.count("battle"))
  270. {
  271. gOnlyAI = vm.count("onlyAI");
  272. Settings session = settings.write["session"];
  273. session["autoSkip"].Bool() = vm.count("autoSkip");
  274. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  275. std::string fileToStartFrom; //none by default
  276. if(vm.count("start"))
  277. fileToStartFrom = vm["start"].as<std::string>();
  278. if(fileToStartFrom.size() && boost::filesystem::exists(fileToStartFrom))
  279. startGameFromFile(fileToStartFrom); //ommit pregame and start the game using settings from fiel
  280. else
  281. {
  282. if(fileToStartFrom.size())
  283. {
  284. tlog3 << "Warning: cannot find given file to start from (" << fileToStartFrom
  285. << "). Falling back to main menu.\n";
  286. }
  287. GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
  288. }
  289. }
  290. else
  291. {
  292. StartInfo *si = new StartInfo();
  293. si->mode = StartInfo::DUEL;
  294. si->mapname = vm["battle"].as<std::string>();
  295. si->playerInfos[0].color = 0;
  296. si->playerInfos[1].color = 1;
  297. startGame(si);
  298. }
  299. mainGUIThread = new boost::thread(&CGuiHandler::run, boost::ref(GH));
  300. listenForEvents();
  301. return 0;
  302. }
  303. void printInfoAboutIntObject(const CIntObject *obj, int level)
  304. {
  305. tlog4 << std::string(level, '\t');
  306. tlog4 << typeid(*obj).name() << " *** ";
  307. if (obj->active)
  308. {
  309. #define PRINT(check, text) if (obj->active & CIntObject::check) tlog4 << text
  310. PRINT(LCLICK, 'L');
  311. PRINT(RCLICK, 'R');
  312. PRINT(HOVER, 'H');
  313. PRINT(MOVE, 'M');
  314. PRINT(KEYBOARD, 'K');
  315. PRINT(TIME, 'T');
  316. PRINT(GENERAL, 'A');
  317. PRINT(WHEEL, 'W');
  318. PRINT(DOUBLECLICK, 'D');
  319. #undef PRINT
  320. }
  321. else
  322. tlog4 << "inactive";
  323. tlog4 << " at " << obj->pos.x <<"x"<< obj->pos.y;
  324. tlog4 << " (" << obj->pos.w <<"x"<< obj->pos.h << ")\n";
  325. BOOST_FOREACH(const CIntObject *child, obj->children)
  326. printInfoAboutIntObject(child, level+1);
  327. }
  328. void processCommand(const std::string &message)
  329. {
  330. std::istringstream readed;
  331. readed.str(message);
  332. std::string cn; //command name
  333. readed >> cn;
  334. if(LOCPLINT && LOCPLINT->cingconsole)
  335. LOCPLINT->cingconsole->print(message);
  336. if(ermInteractiveMode)
  337. {
  338. if(cn == "exit")
  339. {
  340. ermInteractiveMode = false;
  341. return;
  342. }
  343. else
  344. {
  345. if(client && client->erm)
  346. client->erm->executeUserCommand(message);
  347. tlog0 << "erm>";
  348. }
  349. }
  350. else if(message==std::string("die, fool"))
  351. {
  352. exit(EXIT_SUCCESS);
  353. }
  354. else if(cn == "erm")
  355. {
  356. ermInteractiveMode = true;
  357. tlog0 << "erm>";
  358. }
  359. else if(cn==std::string("activate"))
  360. {
  361. int what;
  362. readed >> what;
  363. switch (what)
  364. {
  365. case 0:
  366. GH.topInt()->activate();
  367. break;
  368. case 1:
  369. adventureInt->activate();
  370. break;
  371. case 2:
  372. LOCPLINT->castleInt->activate();
  373. break;
  374. }
  375. }
  376. else if(cn=="redraw")
  377. {
  378. GH.totalRedraw();
  379. }
  380. else if(cn=="screen")
  381. {
  382. tlog0 << "Screenbuf points to ";
  383. if(screenBuf == screen)
  384. tlog1 << "screen";
  385. else if(screenBuf == screen2)
  386. tlog1 << "screen2";
  387. else
  388. tlog1 << "?!?";
  389. tlog1 << std::endl;
  390. SDL_SaveBMP(screen, "Screen_c.bmp");
  391. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  392. }
  393. else if(cn=="save")
  394. {
  395. std::string fname;
  396. readed >> fname;
  397. client->save(fname);
  398. }
  399. else if(cn=="load")
  400. {
  401. // TODO: this code should end the running game and manage to call startGame instead
  402. std::string fname;
  403. readed >> fname;
  404. client->loadGame(fname);
  405. }/*
  406. else if(cn=="resolution" || cn == "r")
  407. {
  408. if(LOCPLINT)
  409. {
  410. tlog1 << "Resolution can be set only before starting the game.\n";
  411. return;
  412. }
  413. std::map<std::pair<int,int>, config::GUIOptions >::iterator j;
  414. int i=1;
  415. tlog4 << "Available screen resolutions:\n";
  416. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end(); j++)
  417. tlog4 << i++ <<". " << j->first.first << " x " << j->first.second << std::endl;
  418. tlog4 << "Type number from 1 to " << i-1 << " to set appropriate resolution or 0 to cancel.\n";
  419. std::cin >> i;
  420. if(i < 0 || i > conf.guiOptions.size() || std::cin.bad() || std::cin.fail())
  421. {
  422. std::cin.clear();
  423. tlog1 << "Invalid resolution ID! Not a number between 0 and " << conf.guiOptions.size() << ". No settings changed.\n";
  424. }
  425. else if(!i)
  426. {
  427. return;
  428. }
  429. else
  430. {
  431. auto j = conf.guiOptions.begin();
  432. std::advance(j, i - 1); //move j to the i-th resolution info
  433. const int w = j->first.first, h = j->first.second;
  434. Settings screen = settings.write["video"]["screenRes"];
  435. screen["width"].Float() = w;
  436. screen["height"].Float() = h;
  437. conf.SetResolution(screen["width"].Float(), screen["height"].Float());
  438. tlog0 << "Screen resolution set to " << (int)screen["width"].Float() << " x "
  439. << (int)screen["height"].Float() <<". It will be applied afters game restart.\n";
  440. }
  441. }*/
  442. else if(message=="get txt")
  443. {
  444. tlog0<<"Command accepted.\t";
  445. boost::filesystem::create_directory("Extracted_txts");
  446. auto iterator = CResourceHandler::get()->getIterator([](const ResourceID & ident)
  447. {
  448. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  449. });
  450. std::string basePath = CResourceHandler::get()->getResourceName(ResourceID("DATA")) + "/Extracted_txts/";
  451. while (iterator.hasNext())
  452. {
  453. std::ofstream file(basePath + iterator->getName() + ".TXT");
  454. auto text = CResourceHandler::get()->loadData(*iterator);
  455. file.write((char*)text.first.get(), text.second);
  456. ++iterator;
  457. }
  458. tlog0 << "\rExtracting done :)\n";
  459. tlog0 << " Extracted files can be found in " << basePath << " directory\n";
  460. }
  461. else if(cn=="crash")
  462. {
  463. int *ptr = NULL;
  464. *ptr = 666;
  465. //disaster!
  466. }
  467. else if(cn == "onlyai")
  468. {
  469. gOnlyAI = true;
  470. }
  471. else if (cn == "ai")
  472. {
  473. VLC->IS_AI_ENABLED = !VLC->IS_AI_ENABLED;
  474. tlog4 << "Current AI status: " << (VLC->IS_AI_ENABLED ? "enabled" : "disabled") << std::endl;
  475. }
  476. else if(cn == "mp" && adventureInt)
  477. {
  478. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  479. tlog0 << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  480. }
  481. else if(cn == "bonuses")
  482. {
  483. tlog0 << "Bonuses of " << adventureInt->selection->getHoverText() << std::endl
  484. << adventureInt->selection->getBonusList() << std::endl;
  485. tlog0 << "\nInherited bonuses:\n";
  486. TCNodes parents;
  487. adventureInt->selection->getParents(parents);
  488. BOOST_FOREACH(const CBonusSystemNode *parent, parents)
  489. {
  490. tlog0 << "\nBonuses from " << typeid(*parent).name() << std::endl << parent->getBonusList() << std::endl;
  491. }
  492. }
  493. else if(cn == "not dialog")
  494. {
  495. LOCPLINT->showingDialog->setn(false);
  496. }
  497. else if(cn == "gui")
  498. {
  499. BOOST_FOREACH(const IShowActivatable *child, GH.listInt)
  500. {
  501. if(const CIntObject *obj = dynamic_cast<const CIntObject *>(child))
  502. printInfoAboutIntObject(obj, 0);
  503. else
  504. tlog4 << typeid(*obj).name() << std::endl;
  505. }
  506. }
  507. else if(cn=="tell")
  508. {
  509. std::string what;
  510. int id1, id2;
  511. readed >> what >> id1 >> id2;
  512. if(what == "hs")
  513. {
  514. BOOST_FOREACH(const CGHeroInstance *h, LOCPLINT->cb->getHeroesInfo())
  515. if(h->type->ID == id1)
  516. if(const CArtifactInstance *a = h->getArt(id2))
  517. tlog4 << a->nodeName();
  518. }
  519. }
  520. else if (cn == "set")
  521. {
  522. std::string what, value;
  523. readed >> what;
  524. Settings conf = settings.write["session"][what];
  525. readed >> value;
  526. if (value == "on")
  527. conf->Bool() = true;
  528. else if (value == "off")
  529. conf->Bool() = false;
  530. }
  531. else if(cn == "sinfo")
  532. {
  533. std::string fname;
  534. readed >> fname;
  535. if(fname.size() && SEL)
  536. {
  537. CSaveFile out(fname);
  538. out << SEL->sInfo;
  539. }
  540. }
  541. else if(cn == "start")
  542. {
  543. std::string fname;
  544. readed >> fname;
  545. startGameFromFile(fname);
  546. }
  547. else if(cn == "unlock")
  548. {
  549. std::string mxname;
  550. readed >> mxname;
  551. if(mxname == "pim" && LOCPLINT)
  552. LOCPLINT->pim->unlock();
  553. }
  554. else if(cn == "setBattleAI")
  555. {
  556. std::string fname;
  557. readed >> fname;
  558. tlog0 << "Will try loading that AI to see if it is correct name...\n";
  559. 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
  560. {
  561. delete ai;
  562. Settings neutralAI = settings.write["server"]["neutralAI"];
  563. neutralAI->String() = fname;
  564. tlog0 << "Setting changed, from now the battle ai will be " << fname << "!\n";
  565. }
  566. else
  567. {
  568. tlog3 << "Setting not changes, no such AI found!\n";
  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. tlog1 << "Error: SDL says that " << w << "x" << h << " resolution is not available!\n";
  602. return;
  603. }
  604. bool bufOnScreen = (screenBuf == screen);
  605. if(suggestedBpp != bpp)
  606. {
  607. tlog2 << "Note: SDL suggests to use " << suggestedBpp << " bpp instead of" << bpp << " bpp " << std::endl;
  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. tlog1 << "Requested screen resolution is not available (" << w << "x" << h << "x" << suggestedBpp << "bpp)\n";
  619. throw std::runtime_error("Requested screen resolution is not available\n");
  620. }
  621. tlog0 << "New screen flags: " << screen->flags << std::endl;
  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. tlog3 << "Something went wrong, getwm=" << getwm << std::endl;
  646. tlog3 << "SDL says: " << SDL_GetError() << std::endl;
  647. tlog3 << "Window won't be centered.\n";
  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. tlog1 << "Error: SDL says that " << screen->w << "x" << screen->h << " resolution is not available!\n";
  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. //tlog0 << "Waiting... ";
  679. int ret = SDL_WaitEvent(&ev);
  680. //tlog0 << "got " << (int)ev.type;
  681. if (ret == 0 || (ev.type==SDL_QUIT) ||
  682. (ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  683. {
  684. if (client)
  685. client->endGame();
  686. if (mainGUIThread)
  687. {
  688. GH.terminate = true;
  689. mainGUIThread->join();
  690. delete mainGUIThread;
  691. mainGUIThread = NULL;
  692. }
  693. delete console;
  694. console = NULL;
  695. SDL_Delay(750);
  696. SDL_Quit();
  697. tlog0 << "Ending...\n";
  698. break;
  699. }
  700. else if(LOCPLINT && ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  701. {
  702. Settings full = settings.write["video"]["fullscreen"];
  703. full->Bool() = !full->Bool();
  704. continue;
  705. }
  706. else if(ev.type == SDL_USEREVENT)
  707. {
  708. auto endGame = []
  709. {
  710. client->endGame();
  711. vstd::clear_pointer(client);
  712. delete CGI->dobjinfo.get();
  713. const_cast<CGameInfo*>(CGI)->dobjinfo = new CDefObjInfoHandler;
  714. const_cast<CGameInfo*>(CGI)->dobjinfo->load();
  715. const_cast<CGameInfo*>(CGI)->modh->reload(); //add info about new creatures to dobjinfo
  716. };
  717. switch(ev.user.code)
  718. {
  719. /* case CHANGE_SCREEN_RESOLUTION:
  720. {
  721. tlog0 << "Changing resolution has been requested\n";
  722. const JsonNode& video = settings["video"];
  723. const JsonNode& res = video["gameRes"];
  724. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  725. break;
  726. }*/
  727. case RETURN_TO_MAIN_MENU:
  728. {
  729. // StartInfo si = *client->getStartInfo();
  730. // if(si.mode == StartInfo::CAMPAIGN)
  731. // GH.pushInt( new CBonusSelection(si.campState) );
  732. // else
  733. {
  734. endGame();
  735. CGPreGame::create();
  736. GH.curInt = CGP;
  737. GH.defActionsDef = 63;
  738. }
  739. }
  740. break;
  741. case STOP_CLIENT:
  742. client->endGame(false);
  743. break;
  744. case RESTART_GAME:
  745. {
  746. StartInfo si = *client->getStartInfo(true);
  747. endGame();
  748. startGame(&si);
  749. }
  750. break;
  751. case RETURN_TO_MENU_LOAD:
  752. endGame();
  753. CGPreGame::create();
  754. GH.defActionsDef = 63;
  755. CGP->update();
  756. CGP->menu->switchToTab(vstd::find_pos(CGP->menu->menuNameToEntry, "load"));
  757. GH.curInt = CGP;
  758. break;
  759. case FULLSCREEN_TOGGLED:
  760. fullScreenChanged();
  761. break;
  762. default:
  763. tlog1 << "Error: unknown user event. Code " << ev.user.code << std::endl;
  764. assert(0);
  765. }
  766. continue;
  767. }
  768. //tlog0 << " pushing ";
  769. {
  770. boost::unique_lock<boost::mutex> lock(eventsM);
  771. events.push(ev);
  772. }
  773. //tlog0 << " done\n";
  774. }
  775. }
  776. void startGame(StartInfo * options, CConnection *serv/* = NULL*/)
  777. {
  778. if(gOnlyAI)
  779. {
  780. for(auto it = options->playerInfos.begin(); it != options->playerInfos.end(); ++it)
  781. {
  782. it->second.playerID = PlayerSettings::PLAYER_AI;
  783. }
  784. }
  785. /* const JsonNode& res = settings["video"]["screenRes"];
  786. if(screen->w != res["width"].Float() || screen->h != res["height"].Float())
  787. {
  788. requestChangingResolution();
  789. //allow event handling thread change resolution
  790. auto unlock = vstd::makeUnlockGuard(eventsM);
  791. while(!setResolution) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  792. }
  793. else
  794. setResolution = true;*/
  795. client = new CClient;
  796. CPlayerInterface::howManyPeople = 0;
  797. switch(options->mode) //new game
  798. {
  799. case StartInfo::NEW_GAME:
  800. case StartInfo::CAMPAIGN:
  801. case StartInfo::DUEL:
  802. client->newGame(serv, options);
  803. break;
  804. case StartInfo::LOAD_GAME:
  805. std::string fname = options->mapname;
  806. boost::algorithm::erase_last(fname,".vlgm1");
  807. client->loadGame(fname);
  808. break;
  809. }
  810. client->connectionHandler = new boost::thread(&CClient::run, client);
  811. }
  812. /*
  813. void requestChangingResolution()
  814. {
  815. //mark that we are going to change resolution
  816. setResolution = false;
  817. //push special event to order event reading thread to change resolution
  818. SDL_Event ev;
  819. ev.type = SDL_USEREVENT;
  820. ev.user.code = CHANGE_SCREEN_RESOLUTION;
  821. SDL_PushEvent(&ev);
  822. }
  823. */