CMT.cpp 20 KB

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