CMT.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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 "CPreGame.h"
  10. #include "CCastleInterface.h"
  11. #include "../lib/CConsoleHandler.h"
  12. #include "UIFramework/CCursorHandler.h"
  13. #include "../lib/CGameState.h"
  14. #include "../CCallback.h"
  15. #include "CPlayerInterface.h"
  16. #include "CAdvmapInterface.h"
  17. #include "../lib/CBuildingHandler.h"
  18. #include "CVideoHandler.h"
  19. #include "../lib/CHeroHandler.h"
  20. #include "../lib/CCreatureHandler.h"
  21. #include "../lib/CSpellHandler.h"
  22. #include "CMusicHandler.h"
  23. #include "CVideoHandler.h"
  24. #include "../lib/CLodHandler.h"
  25. #include "CDefHandler.h"
  26. #include "../lib/CGeneralTextHandler.h"
  27. #include "Graphics.h"
  28. #include "Client.h"
  29. #include "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/CObjectHandler.h"
  36. #include "../lib/CArtHandler.h"
  37. #include "../lib/CScriptingModule.h"
  38. #include "../lib/GameConstants.h"
  39. #include "UIFramework/CGuiHandler.h"
  40. #ifdef _WIN32
  41. #include "SDL_syswm.h"
  42. #endif
  43. #include "../lib/CDefObjInfoHandler.h"
  44. #include "../lib/UnlockGuard.h"
  45. #if __MINGW32__
  46. #undef main
  47. #endif
  48. namespace po = boost::program_options;
  49. /*
  50. * CMT.cpp, part of VCMI engine
  51. *
  52. * Authors: listed in file AUTHORS in main folder
  53. *
  54. * License: GNU General Public License v2.0 or later
  55. * Full text of license available in license.txt file, in main folder
  56. *
  57. */
  58. std::string NAME_AFFIX = "client";
  59. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  60. CGuiHandler GH;
  61. static CClient *client=NULL;
  62. SDL_Surface *screen = NULL, //main screen surface
  63. *screen2 = NULL,//and hlp surface (used to store not-active interfaces layer)
  64. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  65. static boost::thread *mainGUIThread;
  66. VCMIDirs GVCMIDirs;
  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);
  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. out >> si;
  92. while(GH.topInt())
  93. GH.popIntTotally(GH.topInt());
  94. startGame(&si);
  95. }
  96. }
  97. void init()
  98. {
  99. CStopWatch tmh, pomtime;
  100. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  101. int rmask = 0xff000000;int gmask = 0x00ff0000;int bmask = 0x0000ff00;int amask = 0x000000ff;
  102. #else
  103. int rmask = 0x000000ff; int gmask = 0x0000ff00; int bmask = 0x00ff0000; int amask = 0xff000000;
  104. #endif
  105. CSDL_Ext::std32bppSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, 1, 32, rmask, gmask, bmask, amask);
  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. initDLL(::console,logfile);
  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. #else
  160. int main(int argc, char** argv)
  161. #endif
  162. {
  163. tlog0 << "Starting... " << std::endl;
  164. po::options_description opts("Allowed options");
  165. opts.add_options()
  166. ("help,h", "display help and exit")
  167. ("version,v", "display version information and exit")
  168. ("battle,b", po::value<std::string>(), "runs game in duel mode (battle-only")
  169. ("start", po::value<std::string>(), "starts game from saved StartInfo file")
  170. ("onlyAI", "runs without GUI, all players will be default AI")
  171. ("oneGoodAI", "puts one default AI and the rest will be GeniusAI")
  172. ("autoSkip", "automatically skip turns in GUI")
  173. ("nointro,i", "skips intro movies");
  174. po::variables_map vm;
  175. if(argc > 1)
  176. {
  177. try
  178. {
  179. po::store(po::parse_command_line(argc, argv, opts), vm);
  180. }
  181. catch(std::exception &e)
  182. {
  183. tlog1 << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  184. }
  185. }
  186. po::notify(vm);
  187. if(vm.count("help"))
  188. {
  189. prog_help(opts);
  190. return 0;
  191. }
  192. if(vm.count("version"))
  193. {
  194. prog_version();
  195. return 0;
  196. }
  197. //Set environment vars to make window centered. Sometimes work, sometimes not. :/
  198. putenv((char*)"SDL_VIDEO_WINDOW_POS");
  199. putenv((char*)"SDL_VIDEO_CENTERED=1");
  200. CStopWatch total, pomtime;
  201. std::cout.flags(std::ios::unitbuf);
  202. logfile = new std::ofstream((GVCMIDirs.UserPath + "/VCMI_Client_log.txt").c_str());
  203. console = new CConsoleHandler;
  204. *console->cb = boost::bind(&processCommand, _1);
  205. console->start();
  206. atexit(dispose);
  207. tlog0 <<"Creating console and logfile: "<<pomtime.getDiff() << std::endl;
  208. settings.init();
  209. conf.init();
  210. tlog0 <<"Loading settings: "<<pomtime.getDiff() << std::endl;
  211. tlog0 << NAME << std::endl;
  212. srand ( time(NULL) );
  213. CCS = new CClientState;
  214. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
  215. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
  216. {
  217. tlog1<<"Something was wrong: "<< SDL_GetError() << std::endl;
  218. exit(-1);
  219. }
  220. atexit(SDL_Quit);
  221. const JsonNode& video = settings["video"];
  222. const JsonNode& res = video["menuRes"];
  223. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  224. tlog0 <<"\tInitializing screen: "<<pomtime.getDiff() << std::endl;
  225. // Initialize video
  226. #if defined _M_X64 && defined _WIN32 //Win64 -> cannot load 32-bit DLLs for video handling
  227. CCS->videoh = new CEmptyVideoPlayer;
  228. #else
  229. CCS->videoh = new CVideoPlayer;
  230. #endif
  231. tlog0<<"\tInitializing video: "<<pomtime.getDiff()<<std::endl;
  232. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  233. boost::thread loading(init);
  234. if(!vm.count("battle") && !vm.count("nointro"))
  235. playIntro();
  236. SDL_FillRect(screen,NULL,0);
  237. CSDL_Ext::update(screen);
  238. loading.join();
  239. tlog0<<"Initialization of VCMI (together): "<<total.getDiff()<<std::endl;
  240. if(!vm.count("battle"))
  241. {
  242. gOnlyAI = vm.count("onlyAI");
  243. Settings session = settings.write["session"];
  244. session["autoSkip"].Bool() = vm.count("autoSkip");
  245. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  246. if(!vm.count("start"))
  247. GH.curInt = new CGPreGame; //will set CGP pointer to itself
  248. else
  249. startGameFromFile(vm["start"].as<std::string>());
  250. }
  251. else
  252. {
  253. StartInfo *si = new StartInfo();
  254. si->mode = StartInfo::DUEL;
  255. si->mapname = vm["battle"].as<std::string>();
  256. si->playerInfos[0].color = 0;
  257. si->playerInfos[1].color = 1;
  258. startGame(si);
  259. }
  260. mainGUIThread = new boost::thread(&CGuiHandler::run, boost::ref(GH));
  261. listenForEvents();
  262. return 0;
  263. }
  264. void printInfoAboutIntObject(const CIntObject *obj, int level)
  265. {
  266. int tabs = level;
  267. while(tabs--) tlog4 << '\t';
  268. tlog4 << typeid(*obj).name() << " *** " << (obj->active ? "" : "not ") << "active";
  269. tlog4 << " at " << obj->pos.x <<"x"<< obj->pos.y << "\n";
  270. BOOST_FOREACH(const CIntObject *child, obj->children)
  271. printInfoAboutIntObject(child, level+1);
  272. }
  273. void processCommand(const std::string &message)
  274. {
  275. std::istringstream readed;
  276. readed.str(message);
  277. std::string cn; //command name
  278. readed >> cn;
  279. if(LOCPLINT && LOCPLINT->cingconsole)
  280. LOCPLINT->cingconsole->print(message);
  281. if(ermInteractiveMode)
  282. {
  283. if(cn == "exit")
  284. {
  285. ermInteractiveMode = false;
  286. return;
  287. }
  288. else
  289. {
  290. if(client && client->erm)
  291. client->erm->executeUserCommand(message);
  292. tlog0 << "erm>";
  293. }
  294. }
  295. else if(message==std::string("die, fool"))
  296. {
  297. exit(EXIT_SUCCESS);
  298. }
  299. else if(cn == "erm")
  300. {
  301. ermInteractiveMode = true;
  302. tlog0 << "erm>";
  303. }
  304. else if(cn==std::string("activate"))
  305. {
  306. int what;
  307. readed >> what;
  308. switch (what)
  309. {
  310. case 0:
  311. GH.topInt()->activate();
  312. break;
  313. case 1:
  314. adventureInt->activate();
  315. break;
  316. case 2:
  317. LOCPLINT->castleInt->activate();
  318. break;
  319. }
  320. }
  321. else if(cn=="redraw")
  322. {
  323. GH.totalRedraw();
  324. }
  325. else if(cn=="screen")
  326. {
  327. tlog0 << "Screenbuf points to ";
  328. if(screenBuf == screen)
  329. tlog1 << "screen";
  330. else if(screenBuf == screen2)
  331. tlog1 << "screen2";
  332. else
  333. tlog1 << "?!?";
  334. tlog1 << std::endl;
  335. SDL_SaveBMP(screen, "Screen_c.bmp");
  336. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  337. }
  338. else if(cn=="save")
  339. {
  340. std::string fname;
  341. readed >> fname;
  342. client->save(fname);
  343. }
  344. //else if(cn=="list")
  345. //{
  346. // if(CPG)
  347. // for(int i = 0; i < CPG->ourScenSel->mapsel.ourGames.size(); i++)
  348. // tlog0 << i << ".\t" << CPG->ourScenSel->mapsel.ourGames[i]->filename << std::endl;
  349. //}
  350. else if(cn=="load")
  351. {
  352. // TODO: this code should end the running game and manage to call startGame instead
  353. std::string fname;
  354. readed >> fname;
  355. client->loadGame(fname);
  356. }
  357. //else if(cn=="ln")
  358. //{
  359. // int num;
  360. // readed >> num;
  361. // std::string &name = CPG->ourScenSel->mapsel.ourGames[num]->filename;
  362. // client->load(name.substr(0, name.size()-6));
  363. //}
  364. else if(cn=="resolution" || cn == "r")
  365. {
  366. if(LOCPLINT)
  367. {
  368. tlog1 << "Resolution can be set only before starting the game.\n";
  369. return;
  370. }
  371. std::map<std::pair<int,int>, config::GUIOptions >::iterator j;
  372. int i=1, hlp=1;
  373. tlog4 << "Available screen resolutions:\n";
  374. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end(); j++)
  375. tlog4 << i++ <<". " << j->first.first << " x " << j->first.second << std::endl;
  376. tlog4 << "Type number from 1 to " << i-1 << " to set appropriate resolution or 0 to cancel.\n";
  377. std::cin >> i;
  378. if(i < 0 || i > conf.guiOptions.size() || std::cin.bad() || std::cin.fail())
  379. {
  380. std::cin.clear();
  381. tlog1 << "Invalid resolution ID! Not a number between 0 and " << conf.guiOptions.size() << ". No settings changed.\n";
  382. }
  383. else if(!i)
  384. {
  385. return;
  386. }
  387. else
  388. {
  389. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end() && hlp++<i; j++); //move j to the i-th resolution info
  390. Settings res = settings.write["video"]["gameRes"];
  391. Settings screen = settings.write["video"]["screenRes"];
  392. res["width"].Float() = res["width"].Float() = j->first.first;
  393. screen["height"].Float() = screen["height"].Float() = j->first.second;
  394. conf.SetResolution(screen["width"].Float(), screen["height"].Float());
  395. tlog0 << "Screen resolution set to " << (int)screen["width"].Float() << " x "
  396. << (int)screen["height"].Float() <<". It will be applied when the game starts.\n";
  397. }
  398. }
  399. else if(message=="get txt")
  400. {
  401. boost::filesystem::create_directory("Extracted_txts");
  402. tlog0<<"Command accepted. Opening .lod file...\t";
  403. CLodHandler * txth = new CLodHandler;
  404. txth->init(GameConstants::DATA_DIR + "/Data/H3bitmap.lod","");
  405. tlog0<<"done.\nScanning .lod file\n";
  406. BOOST_FOREACH(Entry e, txth->entries)
  407. if( e.type == FILE_TEXT )
  408. txth->extractFile(std::string(GVCMIDirs.UserPath + "/Extracted_txts/")+e.name, e.name, FILE_TEXT);
  409. tlog0<<"\rExtracting done :)\n";
  410. }
  411. else if(cn=="crash")
  412. {
  413. int *ptr = NULL;
  414. *ptr = 666;
  415. //disaster!
  416. }
  417. else if(cn == "onlyai")
  418. {
  419. gOnlyAI = true;
  420. }
  421. else if (cn == "ai")
  422. {
  423. VLC->IS_AI_ENABLED = !VLC->IS_AI_ENABLED;
  424. tlog4 << "Current AI status: " << (VLC->IS_AI_ENABLED ? "enabled" : "disabled") << std::endl;
  425. }
  426. else if(cn == "mp" && adventureInt)
  427. {
  428. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  429. tlog0 << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  430. }
  431. else if(cn == "bonuses")
  432. {
  433. tlog0 << "Bonuses of " << adventureInt->selection->getHoverText() << std::endl
  434. << adventureInt->selection->getBonusList() << std::endl;
  435. tlog0 << "\nInherited bonuses:\n";
  436. TCNodes parents;
  437. adventureInt->selection->getParents(parents);
  438. BOOST_FOREACH(const CBonusSystemNode *parent, parents)
  439. {
  440. tlog0 << "\nBonuses from " << typeid(*parent).name() << std::endl << parent->getBonusList() << std::endl;
  441. }
  442. }
  443. else if(cn == "not dialog")
  444. {
  445. LOCPLINT->showingDialog->setn(false);
  446. }
  447. else if(cn == "gui")
  448. {
  449. BOOST_FOREACH(const IShowActivatable *child, GH.listInt)
  450. {
  451. if(const CIntObject *obj = dynamic_cast<const CIntObject *>(child))
  452. printInfoAboutIntObject(obj, 0);
  453. else
  454. tlog4 << typeid(*obj).name() << std::endl;
  455. }
  456. }
  457. else if(cn=="tell")
  458. {
  459. std::string what;
  460. int id1, id2;
  461. readed >> what >> id1 >> id2;
  462. if(what == "hs")
  463. {
  464. BOOST_FOREACH(const CGHeroInstance *h, LOCPLINT->cb->getHeroesInfo())
  465. if(h->type->ID == id1)
  466. if(const CArtifactInstance *a = h->getArt(id2))
  467. tlog4 << a->nodeName();
  468. }
  469. else if (what == "anim" )
  470. {
  471. CAnimation::getAnimInfo();
  472. }
  473. }
  474. else if (cn == "switchCreWin" )
  475. {
  476. Settings window = settings.write["general"]["classicCreatureWindow"];
  477. window->Bool() = !window->Bool();
  478. }
  479. else if(cn == "sinfo")
  480. {
  481. std::string fname;
  482. readed >> fname;
  483. if(fname.size() && SEL)
  484. {
  485. CSaveFile out(fname);
  486. out << SEL->sInfo;
  487. }
  488. }
  489. else if(cn == "start")
  490. {
  491. std::string fname;
  492. readed >> fname;
  493. startGameFromFile(fname);
  494. }
  495. else if(cn == "unlock")
  496. {
  497. std::string mxname;
  498. readed >> mxname;
  499. if(mxname == "pim" && LOCPLINT)
  500. LOCPLINT->pim->unlock();
  501. }
  502. else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  503. {
  504. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  505. LOCPLINT->cb->sendMessage(message);
  506. }
  507. }
  508. //plays intro, ends when intro is over or button has been pressed (handles events)
  509. void playIntro()
  510. {
  511. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 60, 40, screen, true))
  512. {
  513. CCS->videoh->openAndPlayVideo("AZVS.SMK", 60, 80, screen, true);
  514. }
  515. }
  516. void dispose()
  517. {
  518. if (console)
  519. delete console;
  520. delete logfile;
  521. }
  522. static void setScreenRes(int w, int h, int bpp, bool fullscreen)
  523. {
  524. // VCMI will only work with 2, 3 or 4 bytes per pixel
  525. vstd::amax(bpp, 16);
  526. vstd::amin(bpp, 32);
  527. // Try to use the best screen depth for the display
  528. int suggestedBpp = SDL_VideoModeOK(w, h, bpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  529. if(suggestedBpp == 0)
  530. {
  531. tlog1 << "Error: SDL says that " << w << "x" << h << " resolution is not available!\n";
  532. return;
  533. }
  534. bool bufOnScreen = (screenBuf == screen);
  535. if(suggestedBpp != bpp)
  536. {
  537. tlog2 << "Warning: SDL says that " << bpp << "bpp is wrong and suggests " << suggestedBpp << std::endl;
  538. }
  539. if(screen) //screen has been already initialized
  540. SDL_QuitSubSystem(SDL_INIT_VIDEO);
  541. SDL_InitSubSystem(SDL_INIT_VIDEO);
  542. if((screen = SDL_SetVideoMode(w, h, suggestedBpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0))) == NULL)
  543. {
  544. tlog1 << "Requested screen resolution is not available (" << w << "x" << h << "x" << suggestedBpp << "bpp)\n";
  545. throw "Requested screen resolution is not available\n";
  546. }
  547. tlog0 << "New screen flags: " << screen->flags << std::endl;
  548. if(screen2)
  549. SDL_FreeSurface(screen2);
  550. screen2 = CSDL_Ext::copySurface(screen);
  551. SDL_EnableUNICODE(1);
  552. SDL_WM_SetCaption(NAME.c_str(),""); //set window title
  553. SDL_ShowCursor(SDL_DISABLE);
  554. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  555. #ifdef _WIN32
  556. SDL_SysWMinfo wm;
  557. SDL_VERSION(&wm.version);
  558. int getwm = SDL_GetWMInfo(&wm);
  559. if(getwm == 1)
  560. {
  561. int sw = GetSystemMetrics(SM_CXSCREEN),
  562. sh = GetSystemMetrics(SM_CYSCREEN);
  563. RECT curpos;
  564. GetWindowRect(wm.window,&curpos);
  565. int ourw = curpos.right - curpos.left,
  566. ourh = curpos.bottom - curpos.top;
  567. SetWindowPos(wm.window, 0, (sw - ourw)/2, (sh - ourh)/2, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
  568. }
  569. else
  570. {
  571. tlog3 << "Something went wrong, getwm=" << getwm << std::endl;
  572. tlog3 << "SDL says: " << SDL_GetError() << std::endl;
  573. tlog3 << "Window won't be centered.\n";
  574. }
  575. #endif
  576. //TODO: centering game window on other platforms (or does the environment do their job correctly there?)
  577. screenBuf = bufOnScreen ? screen : screen2;
  578. setResolution = true;
  579. }
  580. static void listenForEvents()
  581. {
  582. while(1) //main SDL events loop
  583. {
  584. SDL_Event *ev = new SDL_Event();
  585. //tlog0 << "Waiting... ";
  586. int ret = SDL_WaitEvent(ev);
  587. //tlog0 << "got " << (int)ev->type;
  588. if (ret == 0 || (ev->type==SDL_QUIT) ||
  589. (ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4 && (ev->key.keysym.mod & KMOD_ALT)))
  590. {
  591. if (client)
  592. client->endGame();
  593. if (mainGUIThread)
  594. {
  595. GH.terminate = true;
  596. mainGUIThread->join();
  597. delete mainGUIThread;
  598. mainGUIThread = NULL;
  599. }
  600. delete console;
  601. console = NULL;
  602. SDL_Delay(750);
  603. SDL_Quit();
  604. tlog0 << "Ending...\n";
  605. break;
  606. }
  607. else if(LOCPLINT && ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4)
  608. {
  609. boost::unique_lock<boost::recursive_mutex> lock(*LOCPLINT->pim);
  610. bool full = !(screen->flags&SDL_FULLSCREEN);
  611. const JsonNode& video = settings["video"];
  612. const JsonNode& res = video["screenRes"];
  613. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), full);
  614. GH.totalRedraw();
  615. delete ev;
  616. continue;
  617. }
  618. else if(ev->type == SDL_USEREVENT)
  619. {
  620. switch(ev->user.code)
  621. {
  622. case 1:
  623. {
  624. tlog0 << "Changing resolution has been requested\n";
  625. const JsonNode& video = settings["video"];
  626. const JsonNode& res = video["gameRes"];
  627. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  628. break;
  629. }
  630. case 2:
  631. client->endGame();
  632. delete client;
  633. client = NULL;
  634. delete CGI->dobjinfo.get();
  635. const_cast<CGameInfo*>(CGI)->dobjinfo = new CDefObjInfoHandler;
  636. const_cast<CGameInfo*>(CGI)->dobjinfo->load();
  637. GH.curInt = CGP;
  638. GH.defActionsDef = 63;
  639. break;
  640. case 3:
  641. client->endGame(false);
  642. break;
  643. }
  644. delete ev;
  645. continue;
  646. }
  647. //tlog0 << " pushing ";
  648. {
  649. boost::unique_lock<boost::mutex> lock(eventsM);
  650. events.push(ev);
  651. }
  652. //tlog0 << " done\n";
  653. }
  654. }
  655. void startGame(StartInfo * options, CConnection *serv/* = NULL*/)
  656. {
  657. GH.curInt =NULL;
  658. SDL_FillRect(screen, 0, 0);
  659. if(gOnlyAI)
  660. {
  661. for(std::map<int, PlayerSettings>::iterator it = options->playerInfos.begin();
  662. it != options->playerInfos.end(); ++it)
  663. {
  664. it->second.human = false;
  665. }
  666. }
  667. const JsonNode& res = settings["video"]["screenRes"];
  668. if(screen->w != res["width"].Float() || screen->h != res["height"].Float())
  669. {
  670. requestChangingResolution();
  671. //allow event handling thread change resolution
  672. auto unlock = vstd::makeUnlockGuard(eventsM);
  673. while(!setResolution) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  674. }
  675. else
  676. setResolution = true;
  677. client = new CClient;
  678. CPlayerInterface::howManyPeople = 0;
  679. switch(options->mode) //new game
  680. {
  681. case StartInfo::NEW_GAME:
  682. case StartInfo::CAMPAIGN:
  683. case StartInfo::DUEL:
  684. client->newGame(serv, options);
  685. break;
  686. case StartInfo::LOAD_GAME:
  687. std::string fname = options->mapname;
  688. boost::algorithm::erase_last(fname,".vlgm1");
  689. client->loadGame(fname);
  690. break;
  691. }
  692. client->connectionHandler = new boost::thread(&CClient::run, client);
  693. }
  694. void requestChangingResolution()
  695. {
  696. //mark that we are going to change resolution
  697. setResolution = false;
  698. //push special event to order event reading thread to change resolution
  699. SDL_Event ev;
  700. ev.type = SDL_USEREVENT;
  701. ev.user.code = 1;
  702. SDL_PushEvent(&ev);
  703. }