CMT.cpp 20 KB

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