CMT.cpp 14 KB

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