CMT.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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_ttf.h>
  13. #include <SDL_mixer.h>
  14. #include "SDL_Extensions.h"
  15. #include "SDL_framerate.h"
  16. #include "CGameInfo.h"
  17. #include "../mapHandler.h"
  18. #include "../global.h"
  19. #include "CPreGame.h"
  20. #include "CCastleInterface.h"
  21. #include "../CConsoleHandler.h"
  22. #include "CCursorHandler.h"
  23. #include "../lib/CGameState.h"
  24. #include "../CCallback.h"
  25. #include "CPlayerInterface.h"
  26. #include "CAdvmapInterface.h"
  27. #include "../hch/CBuildingHandler.h"
  28. #include "../hch/CVideoHandler.h"
  29. #include "../hch/CHeroHandler.h"
  30. #include "../hch/CCreatureHandler.h"
  31. #include "../hch/CSpellHandler.h"
  32. #include "../hch/CMusicHandler.h"
  33. #include "../hch/CVideoHandler.h"
  34. #include "../hch/CLodHandler.h"
  35. #include "../hch/CDefHandler.h"
  36. #include "../hch/CAmbarCendamo.h"
  37. #include "../hch/CGeneralTextHandler.h"
  38. #include "Graphics.h"
  39. #include "Client.h"
  40. #include "CConfigHandler.h"
  41. #include "../lib/Connection.h"
  42. #include "../lib/VCMI_Lib.h"
  43. #include "../lib/VCMIDirs.h"
  44. #include <cstdlib>
  45. #include "../lib/NetPacks.h"
  46. #include "SDL_syswm.h"
  47. #if __MINGW32__
  48. #undef main
  49. #endif
  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 = NAME_VER + std::string(" (") + NAME_AFFIX + ')'; //application name
  61. CGuiHandler GH;
  62. static CClient *client;
  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 *hhh;
  67. SystemOptions GDefaultOptions;
  68. VCMIDirs GVCMIDirs;
  69. std::queue<SDL_Event*> events;
  70. boost::mutex eventsM;
  71. TTF_Font * TNRB16, *TNR, *GEOR13, *GEORXX, *GEORM, *GEOR16;
  72. static bool gOnlyAI = false;
  73. void processCommand(const std::string &message);
  74. static void setScreenRes(int w, int h, int bpp, bool fullscreen);
  75. void dispose();
  76. void playIntro();
  77. static void listenForEvents();
  78. void init()
  79. {
  80. timeHandler tmh, pomtime;
  81. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  82. int rmask = 0xff000000;int gmask = 0x00ff0000;int bmask = 0x0000ff00;int amask = 0x000000ff;
  83. #else
  84. int rmask = 0x000000ff; int gmask = 0x0000ff00; int bmask = 0x00ff0000; int amask = 0xff000000;
  85. #endif
  86. CSDL_Ext::std32bppSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, 1, 32, rmask, gmask, bmask, amask);
  87. tlog0 << "\tInitializing minors: " << pomtime.getDif() << std::endl;
  88. TTF_Init();
  89. atexit(TTF_Quit);
  90. TNRB16 = TTF_OpenFont(DATA_DIR "/Fonts/tnrb.ttf",16);
  91. GEOR13 = TTF_OpenFont(DATA_DIR "/Fonts/georgia.ttf",13);
  92. GEOR16 = TTF_OpenFont(DATA_DIR "/Fonts/georgia.ttf",16);
  93. GEORXX = TTF_OpenFont(DATA_DIR "/Fonts/tnrb.ttf",22);
  94. GEORM = TTF_OpenFont(DATA_DIR "/Fonts/georgia.ttf",10);
  95. if(! (TNRB16 && GEOR16 && GEORXX && GEORM))
  96. {
  97. tlog1 << "One of the fonts couldn't be loaded!\n";
  98. exit(-1);
  99. }
  100. THC tlog0<<"\tInitializing fonts: "<<pomtime.getDif()<<std::endl;
  101. {
  102. //read system options
  103. CLoadFile settings(GVCMIDirs.UserPath + "/config/sysopts.bin");
  104. if(settings.sfile)
  105. {
  106. settings >> GDefaultOptions;
  107. }
  108. else //file not found (probably, may be also some kind of access problem
  109. {
  110. tlog2 << "Warning: Cannot read system options, default settings will be used.\n";
  111. //Try to create file
  112. tlog2 << "VCMI will try to save default system options...\n";
  113. GDefaultOptions.settingsChanged();
  114. }
  115. }
  116. THC tlog0<<"\tLoading default system settings: "<<pomtime.getDif()<<std::endl;
  117. //initializing audio
  118. // Note: because of interface button range, volume can only be a
  119. // multiple of 11, from 0 to 99.
  120. CGI->soundh = new CSoundHandler;
  121. CGI->soundh->init();
  122. CGI->soundh->setVolume(GDefaultOptions.soundVolume);
  123. CGI->musich = new CMusicHandler;
  124. //CGI->musich->init();
  125. //CGI->musich->setVolume(GDefaultOptions.musicVolume);
  126. tlog0<<"\tInitializing sound: "<<pomtime.getDif()<<std::endl;
  127. tlog0<<"Initializing screen, fonts and sound handling: "<<tmh.getDif()<<std::endl;
  128. initDLL(::console,logfile);
  129. CGI->setFromLib();
  130. CGI->soundh->initCreaturesSounds(CGI->creh->creatures);
  131. CGI->soundh->initSpellsSounds(CGI->spellh->spells);
  132. tlog0<<"Initializing VCMI_Lib: "<<tmh.getDif()<<std::endl;
  133. pomtime.getDif();
  134. CGI->curh = new CCursorHandler;
  135. CGI->curh->initCursor();
  136. CGI->curh->show();
  137. tlog0<<"Screen handler: "<<pomtime.getDif()<<std::endl;
  138. pomtime.getDif();
  139. graphics = new Graphics();
  140. graphics->loadHeroAnims();
  141. tlog0<<"\tMain graphics: "<<tmh.getDif()<<std::endl;
  142. tlog0<<"Initializing game graphics: "<<tmh.getDif()<<std::endl;
  143. CMessage::init();
  144. tlog0<<"Message handler: "<<tmh.getDif()<<std::endl;
  145. //CPG = new CPreGame(); //main menu and submenus
  146. //tlog0<<"Initialization CPreGame (together): "<<tmh.getDif()<<std::endl;
  147. }
  148. #ifndef __GNUC__
  149. int _tmain(int argc, _TCHAR* argv[])
  150. #else
  151. int main(int argc, char** argv)
  152. #endif
  153. {
  154. putenv("SDL_VIDEO_WINDOW_POS");
  155. putenv("SDL_VIDEO_CENTERED=1");
  156. tlog0 << "Starting... " << std::endl;
  157. timeHandler total, pomtime;
  158. std::cout.flags(std::ios::unitbuf);
  159. logfile = new std::ofstream("VCMI_Client_log.txt");
  160. console = new CConsoleHandler;
  161. *console->cb = boost::bind(&processCommand, _1);
  162. console->start();
  163. atexit(dispose);
  164. tlog0 <<"Creating console and logfile: "<<pomtime.getDif() << std::endl;
  165. conf.init();
  166. tlog0 <<"Loading settings: "<<pomtime.getDif() << std::endl;
  167. tlog0 << NAME << std::endl;
  168. srand ( time(NULL) );
  169. //CPG=NULL;
  170. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler itp.)
  171. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
  172. {
  173. tlog1<<"Something was wrong: "<< SDL_GetError() << std::endl;
  174. exit(-1);
  175. }
  176. atexit(SDL_Quit);
  177. setScreenRes(800,600,conf.cc.bpp,conf.cc.fullscreen);
  178. tlog0 <<"\tInitializing screen: "<<pomtime.getDif() << std::endl;
  179. // Initialize video
  180. CGI->videoh = new CVideoPlayer;
  181. tlog0<<"\tInitializing video: "<<pomtime.getDif()<<std::endl;
  182. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  183. boost::thread loading(init);
  184. playIntro();
  185. SDL_FillRect(screen,NULL,0);
  186. SDL_Flip(screen);
  187. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  188. loading.join();
  189. tlog0<<"Initialization of VCMI (together): "<<total.getDif()<<std::endl;
  190. CGI->musich->playMusic(musicBase::mainMenu, -1);
  191. new CGPreGame; //will set CGP pointer to itself
  192. hhh = new boost::thread(&CGPreGame::run, CGP);
  193. listenForEvents();
  194. return 0;
  195. }
  196. void processCommand(const std::string &message)
  197. {
  198. std::istringstream readed;
  199. readed.str(message);
  200. std::string cn; //command name
  201. readed >> cn;
  202. int3 src, dst;
  203. // int heronum;//TODO use me
  204. int3 dest;
  205. if(LOCPLINT && LOCPLINT->cingconsole)
  206. LOCPLINT->cingconsole->print(message);
  207. if(message==std::string("die, fool"))
  208. exit(EXIT_SUCCESS);
  209. else if(cn==std::string("activate"))
  210. {
  211. int what;
  212. readed >> what;
  213. switch (what)
  214. {
  215. case 0:
  216. GH.topInt()->activate();
  217. break;
  218. case 1:
  219. LOCPLINT->adventureInt->activate();
  220. break;
  221. case 2:
  222. LOCPLINT->castleInt->activate();
  223. break;
  224. }
  225. }
  226. else if(cn=="redraw")
  227. {
  228. GH.totalRedraw();
  229. }
  230. else if(cn=="screen")
  231. {
  232. tlog0 << "Screenbuf points to ";
  233. if(screenBuf == screen)
  234. tlog1 << "screen";
  235. else if(screenBuf == screen2)
  236. tlog1 << "screen2";
  237. else
  238. tlog1 << "?!?";
  239. tlog1 << std::endl;
  240. SDL_SaveBMP(screen, "Screen_c.bmp");
  241. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  242. }
  243. else if(cn=="save")
  244. {
  245. std::string fname;
  246. readed >> fname;
  247. client->save(fname);
  248. }
  249. //else if(cn=="list")
  250. //{
  251. // if(CPG)
  252. // for(int i = 0; i < CPG->ourScenSel->mapsel.ourGames.size(); i++)
  253. // tlog0 << i << ".\t" << CPG->ourScenSel->mapsel.ourGames[i]->filename << std::endl;
  254. //}
  255. else if(cn=="load")
  256. {
  257. // TODO: this code should end the running game and manage to call startGame instead
  258. std::string fname;
  259. readed >> fname;
  260. client->loadGame(fname);
  261. }
  262. //else if(cn=="ln")
  263. //{
  264. // int num;
  265. // readed >> num;
  266. // std::string &name = CPG->ourScenSel->mapsel.ourGames[num]->filename;
  267. // client->load(name.substr(0, name.size()-6));
  268. //}
  269. else if(cn=="resolution" || cn == "r")
  270. {
  271. if(LOCPLINT)
  272. {
  273. tlog1 << "Resolution can be set only before starting the game.\n";
  274. return;
  275. }
  276. std::map<std::pair<int,int>, config::GUIOptions >::iterator j;
  277. int i=1, hlp=1;
  278. tlog4 << "Available screen resolutions:\n";
  279. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end(); j++)
  280. tlog4 << i++ <<". " << j->first.first << " x " << j->first.second << std::endl;
  281. tlog4 << "Type number from 1 to " << i-1 << " to set appropriate resolution or 0 to cancel.\n";
  282. std::cin >> i;
  283. if(i < 0 || i > conf.guiOptions.size() || std::cin.bad() || std::cin.fail())
  284. {
  285. std::cin.clear();
  286. tlog1 << "Invalid resolution ID! Not a number between 0 and " << conf.guiOptions.size() << ". No settings changed.\n";
  287. }
  288. else if(!i)
  289. {
  290. return;
  291. }
  292. else
  293. {
  294. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end() && hlp++<i; j++); //move j to the i-th resolution info
  295. conf.cc.resx = j->first.first;
  296. conf.cc.resy = j->first.second;
  297. tlog0 << "Screen resolution set to " << conf.cc.resx << " x " << conf.cc.resy <<". It will be aplied when the game starts.\n";
  298. }
  299. }
  300. else if(message=="get txt")
  301. {
  302. boost::filesystem::create_directory("Extracted_txts");
  303. tlog0<<"Command accepted. Opening .lod file...\t";
  304. CLodHandler * txth = new CLodHandler;
  305. txth->init(std::string(DATA_DIR "/Data/H3bitmap.lod"),"");
  306. tlog0<<"done.\nScanning .lod file\n";
  307. int curp=0;
  308. std::string pattern = ".TXT", pom;
  309. for(int i=0;i<txth->entries.size(); i++)
  310. {
  311. pom = txth->entries[i].nameStr;
  312. if(boost::algorithm::find_last(pom,pattern))
  313. {
  314. txth->extractFile(std::string(DATA_DIR "/Extracted_txts/")+pom,pom);
  315. }
  316. if(i%8) continue;
  317. int p2 = ((float)i/(float)txth->entries.size())*(float)100;
  318. if(p2!=curp)
  319. {
  320. curp = p2;
  321. tlog0<<"\r"<<curp<<"%";
  322. }
  323. }
  324. tlog0<<"\rExtracting done :)\n";
  325. }
  326. else if(cn=="crash")
  327. {
  328. int *ptr = NULL;
  329. *ptr = 666;
  330. //disaster!
  331. }
  332. else if(cn == "onlyai")
  333. {
  334. gOnlyAI = true;
  335. }
  336. else if(client && client->serv && client->serv->connected) //send to server
  337. {
  338. PlayerMessage pm(LOCPLINT->playerID,message);
  339. *client->serv << &pm;
  340. }
  341. }
  342. //plays intro, ends when intro is over or button has been pressed (handles events)
  343. void playIntro()
  344. {
  345. if(CGI->videoh->openAndPlayVideo("3DOLOGO.SMK", 60, 40, screen, true))
  346. {
  347. CGI->videoh->openAndPlayVideo("AZVS.SMK", 60, 80, screen, true);
  348. }
  349. }
  350. void dispose()
  351. {
  352. delete logfile;
  353. if (console)
  354. delete console;
  355. }
  356. static void setScreenRes(int w, int h, int bpp, bool fullscreen)
  357. {
  358. // VCMI will only work with 3 or 4 bytes per pixel
  359. if (bpp < 24) bpp = 24;
  360. if (bpp > 32) bpp = 32;
  361. // Try to use the best screen depth for the display
  362. int suggestedBpp = SDL_VideoModeOK(w, h, bpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  363. if(suggestedBpp == 0)
  364. {
  365. tlog1 << "Error: SDL says that " << w << "x" << h << " resolution is not available!\n";
  366. return;
  367. }
  368. bool bufOnScreen = (screenBuf == screen);
  369. if(suggestedBpp != bpp)
  370. {
  371. tlog2 << "Warning: SDL says that " << bpp << "bpp is wrong and suggests " << suggestedBpp << std::endl;
  372. }
  373. if(screen) //screen has been already initialized
  374. SDL_QuitSubSystem(SDL_INIT_VIDEO);
  375. SDL_InitSubSystem(SDL_INIT_VIDEO);
  376. if((screen = SDL_SetVideoMode(w, h, suggestedBpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0))) == NULL)
  377. {
  378. tlog1 << "Requested screen resolution is not available (" << w << "x" << h << "x" << suggestedBpp << "bpp)\n";
  379. throw "Requested screen resolution is not available\n";
  380. }
  381. tlog0 << "New screen flags: " << screen->flags << std::endl;
  382. if(screen2)
  383. SDL_FreeSurface(screen2);
  384. screen2 = CSDL_Ext::copySurface(screen);
  385. SDL_EnableUNICODE(1);
  386. SDL_WM_SetCaption(NAME.c_str(),""); //set window title
  387. SDL_ShowCursor(SDL_DISABLE);
  388. #ifdef _WIN32
  389. SDL_SysWMinfo wm;
  390. SDL_VERSION(&wm.version);
  391. int getwm = SDL_GetWMInfo(&wm);
  392. if(getwm == 1)
  393. {
  394. int sw = GetSystemMetrics(SM_CXSCREEN),
  395. sh = GetSystemMetrics(SM_CYSCREEN);
  396. RECT curpos;
  397. GetWindowRect(wm.window,&curpos);
  398. int ourw = curpos.right - curpos.left,
  399. ourh = curpos.bottom - curpos.top;
  400. SetWindowPos(wm.window, 0, (sw - ourw)/2, (sh - ourh)/2, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
  401. }
  402. else
  403. {
  404. tlog3 << "Something went wrong, getwm=" << getwm << std::endl;
  405. tlog3 << "SDL says: " << SDL_GetError() << std::endl;
  406. tlog3 << "Window won't be centered.\n";
  407. }
  408. #endif
  409. //TODO: centering game window on other platforms (or does the environment do their job correctly there?)
  410. screenBuf = bufOnScreen ? screen : screen2;
  411. }
  412. static void listenForEvents()
  413. {
  414. while(1) //main SDL events loop
  415. {
  416. SDL_Event *ev = new SDL_Event();
  417. //tlog0 << "Waiting... ";
  418. int ret = SDL_WaitEvent(ev);
  419. //tlog0 << "got " << (int)ev->type;
  420. if (ret == 0 || (ev->type==SDL_QUIT) ||
  421. (ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4 && (ev->key.keysym.mod & KMOD_ALT)))
  422. {
  423. if (client)
  424. client->stop();
  425. if (hhh) {
  426. CGP->terminate = true;
  427. hhh->join();
  428. delete hhh;
  429. hhh = NULL;
  430. }
  431. delete console;
  432. console = NULL;
  433. SDL_Delay(750);
  434. SDL_Quit();
  435. tlog0 << "Ending...\n";
  436. break;
  437. }
  438. else if(LOCPLINT && ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4)
  439. {
  440. boost::unique_lock<boost::recursive_mutex> lock(*LOCPLINT->pim);
  441. bool full = !(screen->flags&SDL_FULLSCREEN);
  442. setScreenRes(conf.cc.resx,conf.cc.resy,conf.cc.bpp,full);
  443. GH.totalRedraw();
  444. delete ev;
  445. continue;
  446. }
  447. else if(ev->type == SDL_USEREVENT && ev->user.code == 1)
  448. {
  449. setScreenRes(conf.cc.resx,conf.cc.resy,conf.cc.bpp,conf.cc.fullscreen);
  450. delete ev;
  451. continue;
  452. }
  453. else if (ev->type == SDL_USEREVENT && ev->user.code == 2) {
  454. client->stop();
  455. delete ev;
  456. continue;
  457. }
  458. //tlog0 << " pushing ";
  459. eventsM.lock();
  460. events.push(ev);
  461. eventsM.unlock();
  462. //tlog0 << " done\n";
  463. }
  464. }
  465. void startGame(StartInfo * options)
  466. {
  467. if(gOnlyAI)
  468. {
  469. for (size_t i =0; i < options->playerInfos.size(); i++)
  470. {
  471. options->playerInfos[i].human = false;
  472. }
  473. }
  474. if(screen->w != conf.cc.resx || screen->h != conf.cc.resy)
  475. {
  476. //push special event to order event reading thread to change resolution
  477. SDL_Event ev;
  478. ev.type = SDL_USEREVENT;
  479. ev.user.code = 1;
  480. SDL_PushEvent(&ev);
  481. }
  482. CClient cl;
  483. if(options->mode == 0) //new game
  484. {
  485. cl.newGame(NULL, options);
  486. }
  487. else //load game
  488. {
  489. std::string fname = options->mapname;
  490. boost::algorithm::erase_last(fname,".vlgm1");
  491. cl.loadGame(fname);
  492. }
  493. client = &cl;
  494. CGI->musich->stopMusic();
  495. client->run();
  496. LOCPLINT->terminate_cond.waitUntil(true);
  497. client->endGame();
  498. client = NULL;
  499. }