Client.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. #include "../hch/CCampaignHandler.h"
  2. #include "../CCallback.h"
  3. #include "../CConsoleHandler.h"
  4. #include "CGameInfo.h"
  5. #include "../lib/CGameState.h"
  6. #include "CPlayerInterface.h"
  7. #include "../StartInfo.h"
  8. #include "../hch/CArtHandler.h"
  9. #include "../hch/CDefObjInfoHandler.h"
  10. #include "../hch/CGeneralTextHandler.h"
  11. #include "../hch/CHeroHandler.h"
  12. #include "../hch/CTownHandler.h"
  13. #include "../hch/CObjectHandler.h"
  14. #include "../hch/CBuildingHandler.h"
  15. #include "../hch/CSpellHandler.h"
  16. #include "../lib/Connection.h"
  17. #include "../lib/Interprocess.h"
  18. #include "../lib/NetPacks.h"
  19. #include "../lib/VCMI_Lib.h"
  20. #include "../lib/map.h"
  21. #include "mapHandler.h"
  22. #include "CConfigHandler.h"
  23. #include "Client.h"
  24. #include "GUIBase.h"
  25. #include <boost/bind.hpp>
  26. #include <boost/foreach.hpp>
  27. #include <boost/thread.hpp>
  28. #include <boost/thread/shared_mutex.hpp>
  29. #include <sstream>
  30. #include "CPreGame.h"
  31. #undef DLL_EXPORT
  32. #define DLL_EXPORT
  33. #include "../lib/RegisterTypes.cpp"
  34. extern std::string NAME;
  35. namespace intpr = boost::interprocess;
  36. /*
  37. * Client.cpp, part of VCMI engine
  38. *
  39. * Authors: listed in file AUTHORS in main folder
  40. *
  41. * License: GNU General Public License v2.0 or later
  42. * Full text of license available in license.txt file, in main folder
  43. *
  44. */
  45. class CBaseForCLApply
  46. {
  47. public:
  48. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  49. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  50. virtual ~CBaseForCLApply(){}
  51. };
  52. template <typename T> class CApplyOnCL : public CBaseForCLApply
  53. {
  54. public:
  55. void applyOnClAfter(CClient *cl, void *pack) const
  56. {
  57. T *ptr = static_cast<T*>(pack);
  58. ptr->applyCl(cl);
  59. }
  60. void applyOnClBefore(CClient *cl, void *pack) const
  61. {
  62. T *ptr = static_cast<T*>(pack);
  63. ptr->applyFirstCl(cl);
  64. }
  65. };
  66. class CCLApplier
  67. {
  68. public:
  69. std::map<ui16,CBaseForCLApply*> apps;
  70. CCLApplier()
  71. {
  72. registerTypes2(*this);
  73. }
  74. ~CCLApplier()
  75. {
  76. std::map<ui16,CBaseForCLApply*>::iterator iter;
  77. for(iter = apps.begin(); iter != apps.end(); iter++)
  78. delete iter->second;
  79. }
  80. template<typename T> void registerType(const T * t=NULL)
  81. {
  82. ui16 ID = typeList.registerType(t);
  83. apps[ID] = new CApplyOnCL<T>;
  84. }
  85. } *applier = NULL;
  86. void CClient::init()
  87. {
  88. hotSeat = false;
  89. connectionHandler = NULL;
  90. pathInfo = NULL;
  91. applier = new CCLApplier;
  92. IObjectInterface::cb = this;
  93. serv = NULL;
  94. gs = NULL;
  95. cb = NULL;
  96. terminate = false;
  97. boost::interprocess::shared_memory_object::remove("vcmi_memory"); //if the application has previously crashed, the memory may not have been removed. to avoid problems - try to destroy it
  98. try
  99. {
  100. shared = new SharedMem();
  101. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  102. }
  103. CClient::CClient(void)
  104. :waitingRequest(false)
  105. {
  106. init();
  107. }
  108. CClient::CClient(CConnection *con, StartInfo *si)
  109. :waitingRequest(false)
  110. {
  111. init();
  112. newGame(con,si);
  113. }
  114. CClient::~CClient(void)
  115. {
  116. delete pathInfo;
  117. delete applier;
  118. delete shared;
  119. }
  120. void CClient::waitForMoveAndSend(int color)
  121. {
  122. try
  123. {
  124. BattleAction ba = playerint[color]->activeStack(gs->curB->activeStack);
  125. *serv << &MakeAction(ba);
  126. return;
  127. }HANDLE_EXCEPTION
  128. tlog1 << "We should not be here!" << std::endl;
  129. }
  130. void CClient::run()
  131. {
  132. try
  133. {
  134. CPack *pack = NULL;
  135. while(!terminate)
  136. {
  137. pack = retreivePack(); //get the package from the server
  138. if (terminate)
  139. {
  140. delete pack;
  141. pack = NULL;
  142. break;
  143. }
  144. handlePack(pack);
  145. pack = NULL;
  146. }
  147. }
  148. catch (const std::exception& e)
  149. {
  150. tlog3 << "Lost connection to server, ending listening thread!\n";
  151. tlog1 << e.what() << std::endl;
  152. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  153. {
  154. tlog1 << "Something wrong, lost connection while game is still ongoing...\n";
  155. throw;
  156. }
  157. }
  158. }
  159. void CClient::save(const std::string & fname)
  160. {
  161. if(gs->curB)
  162. {
  163. tlog1 << "Game cannot be saved during battle!\n";
  164. return;
  165. }
  166. *serv << &SaveGame(fname);
  167. }
  168. #include <fstream>
  169. void initVillagesCapitols(Mapa * map)
  170. {
  171. std::ifstream ifs(DATA_DIR "/config/townsDefs.txt");
  172. int ccc;
  173. ifs>>ccc;
  174. for(int i=0;i<ccc*2;i++)
  175. {
  176. CGDefInfo *n;
  177. if(i<ccc)
  178. {
  179. n = CGI->state->villages[i];
  180. map->defy.push_back(CGI->state->forts[i]);
  181. }
  182. else
  183. n = CGI->state->capitols[i%ccc];
  184. ifs >> n->name;
  185. if(!n)
  186. tlog1 << "*HUGE* Warning - missing town def for " << i << std::endl;
  187. else
  188. map->defy.push_back(n);
  189. }
  190. }
  191. void CClient::endGame( bool closeConnection /*= true*/ )
  192. {
  193. // Game is ending
  194. // Tell the network thread to reach a stable state
  195. GH.curInt = NULL;
  196. LOCPLINT->terminate_cond.setn(true);
  197. LOCPLINT->pim->lock();
  198. tlog0 << "\n\nEnding current game!" << std::endl;
  199. if(GH.topInt())
  200. GH.topInt()->deactivate();
  201. GH.listInt.clear();
  202. GH.objsToBlit.clear();
  203. GH.statusbar = NULL;
  204. tlog0 << "Removed GUI." << std::endl;
  205. delete CGI->mh;
  206. CGI->mh = NULL;
  207. delete CGI->state;
  208. CGI->state = NULL;
  209. tlog0 << "Deleted mapHandler and gameState." << std::endl;
  210. LOCPLINT = NULL;
  211. while (!playerint.empty())
  212. {
  213. delete playerint.begin()->second;
  214. playerint.erase(playerint.begin());
  215. }
  216. BOOST_FOREACH(CCallback *cb, callbacks)
  217. {
  218. delete cb;
  219. }
  220. tlog0 << "Deleted playerInts." << std::endl;
  221. if(closeConnection)
  222. stopConnection();
  223. tlog0 << "Client stopped." << std::endl;
  224. }
  225. void CClient::loadGame( const std::string & fname )
  226. {
  227. tlog0 <<"\n\nLoading procedure started!\n\n";
  228. timeHandler tmh;
  229. char portc[10];
  230. SDL_itoa(conf.cc.port,portc,10);
  231. runServer(portc); //create new server
  232. tlog0 <<"Restarting server: "<<tmh.getDif()<<std::endl;
  233. {
  234. ui32 ver;
  235. char sig[8];
  236. CMapHeader dum;
  237. CGI->mh = new CMapHandler();
  238. StartInfo *si;
  239. CLoadFile lf(fname + ".vlgm1");
  240. lf >> sig >> dum >> si;
  241. tlog0 <<"Reading save signature: "<<tmh.getDif()<<std::endl;
  242. lf >> *VLC;
  243. CGI->setFromLib();
  244. tlog0 <<"Reading handlers: "<<tmh.getDif()<<std::endl;
  245. lf >> gs;
  246. tlog0 <<"Reading gamestate: "<<tmh.getDif()<<std::endl;
  247. CGI->state = gs;
  248. CGI->mh->map = gs->map;
  249. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  250. CGI->mh->init();
  251. initVillagesCapitols(gs->map);
  252. tlog0 <<"Initing maphandler: "<<tmh.getDif()<<std::endl;
  253. }
  254. waitForServer();
  255. tlog0 <<"Waiting for server: "<<tmh.getDif()<<std::endl;
  256. serv = new CConnection(conf.cc.server,portc,NAME);
  257. serv->addStdVecItems(gs);
  258. tlog0 <<"Setting up connection: "<<tmh.getDif()<<std::endl;
  259. ui8 pom8;
  260. *serv << ui8(3) << ui8(1); //load game; one client
  261. *serv << fname;
  262. *serv >> pom8;
  263. if(pom8)
  264. throw "Server cannot open the savegame!";
  265. else
  266. tlog0 << "Server opened savegame properly.\n";
  267. *serv << ui8(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  268. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  269. it != gs->scenarioOps->playerInfos.end(); ++it)
  270. {
  271. *serv << ui8(it->first); //players
  272. }
  273. *serv << ui8(255); // neutrals
  274. tlog0 <<"Sent info to server: "<<tmh.getDif()<<std::endl;
  275. {
  276. CLoadFile lf(fname + ".vcgm1");
  277. lf >> *this;
  278. }
  279. }
  280. int CClient::getCurrentPlayer()
  281. {
  282. return gs->currentPlayer;
  283. }
  284. int CClient::getSelectedHero()
  285. {
  286. if(const CGHeroInstance *selHero = IGameCallback::getSelectedHero(getCurrentPlayer()))
  287. return selHero->id;
  288. else
  289. return -1;
  290. }
  291. void CClient::newGame( CConnection *con, StartInfo *si )
  292. {
  293. if (con == NULL)
  294. {
  295. timeHandler pomtime;
  296. char portc[10];
  297. SDL_itoa(conf.cc.port,portc,10);
  298. CClient::runServer(portc);
  299. tlog0<<"Preparing shared memory and starting server: "<<pomtime.getDif()<<std::endl;
  300. pomtime.getDif();//reset timers
  301. //wait until server is ready
  302. tlog0<<"Waiting for server... ";
  303. waitForServer();
  304. tlog0 << pomtime.getDif()<<std::endl;
  305. while(!con)
  306. {
  307. try
  308. {
  309. tlog0 << "Establishing connection...\n";
  310. con = new CConnection(conf.cc.server,portc,NAME);
  311. }
  312. catch(...)
  313. {
  314. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" <<std::endl;
  315. SDL_Delay(2000);
  316. }
  317. }
  318. THC tlog0<<"\tConnecting to the server: "<<pomtime.getDif()<<std::endl;
  319. }
  320. timeHandler tmh;
  321. CGI->state = new CGameState();
  322. tlog0 <<"\tGamestate: "<<tmh.getDif()<<std::endl;
  323. serv = con;
  324. CConnection &c(*con);
  325. ////////////////////////////////////////////////////
  326. ui8 pom8;
  327. c << ui8(2) << ui8(1); //new game; one client
  328. c << *si;
  329. c >> pom8;
  330. if(pom8)
  331. throw "Server cannot open the map!";
  332. else
  333. tlog0 << "Server opened map properly.\n";
  334. c << ui8(si->playerInfos.size()+1); //number of players + neutral
  335. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  336. it != si->playerInfos.end(); ++it)
  337. {
  338. c << ui8(it->first); //players
  339. }
  340. c << ui8(255); // neutrals
  341. ui32 seed, sum;
  342. delete si;
  343. c >> si >> sum >> seed;
  344. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
  345. tlog0 << "\tUsing random seed: "<<seed << std::endl;
  346. gs = CGI->state;
  347. gs->scenarioOps = si;
  348. gs->init(si, sum, seed);
  349. CGI->mh = new CMapHandler();
  350. tlog0 <<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
  351. CGI->mh->map = gs->map;
  352. tlog0 <<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
  353. CGI->mh->init();
  354. initVillagesCapitols(gs->map);
  355. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  356. tlog0 <<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
  357. int humanPlayers = 0;
  358. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  359. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  360. {
  361. ui8 color = it->first;
  362. CCallback *cb = new CCallback(gs,color,this);
  363. if(!it->second.human)
  364. {
  365. playerint[color] = static_cast<CGameInterface*>(CAIHandler::getNewAI(cb,conf.cc.defaultAI));
  366. }
  367. else
  368. {
  369. playerint[color] = new CPlayerInterface(color);
  370. humanPlayers++;
  371. }
  372. gs->currentPlayer = color;
  373. playerint[color]->init(cb);
  374. }
  375. serv->addStdVecItems(CGI->state);
  376. hotSeat = (humanPlayers > 1);
  377. playerint[255] = CAIHandler::getNewAI(cb,conf.cc.defaultAI);
  378. playerint[255]->init(new CCallback(gs,255,this));
  379. }
  380. void CClient::runServer(const char * portc)
  381. {
  382. static std::string comm = std::string(BIN_DIR PATH_SEPARATOR SERVER_NAME " ") + portc + " > server_log.txt"; //needs to be static, if not - will be probably destroyed before new thread reads it
  383. boost::thread servthr(boost::bind(system,comm.c_str())); //runs server executable; //TODO: will it work on non-windows platforms?
  384. }
  385. void CClient::waitForServer()
  386. {
  387. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  388. while(!shared->sr->ready)
  389. {
  390. shared->sr->cond.wait(slock);
  391. }
  392. }
  393. template <typename Handler>
  394. void CClient::serialize( Handler &h, const int version )
  395. {
  396. h & hotSeat;
  397. if(h.saving)
  398. {
  399. ui8 players = playerint.size();
  400. h & players;
  401. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  402. {
  403. h & i->first & i->second->dllName;
  404. i->second->serialize(h,version);
  405. }
  406. }
  407. else
  408. {
  409. ui8 players;
  410. h & players;
  411. for(int i=0; i < players; i++)
  412. {
  413. std::string dllname;
  414. ui8 pid;
  415. h & pid & dllname;
  416. CCallback *callback = new CCallback(gs,pid,this);
  417. callbacks.insert(callback);
  418. CGameInterface *nInt = NULL;
  419. if(dllname.length())
  420. nInt = CAIHandler::getNewAI(callback,dllname);
  421. else
  422. nInt = new CPlayerInterface(pid);
  423. playerint[pid] = nInt;
  424. nInt->init(callback);
  425. nInt->serialize(h, version);
  426. }
  427. }
  428. }
  429. CPack * CClient::retreivePack()
  430. {
  431. CPack *ret = NULL;
  432. boost::unique_lock<boost::mutex> lock(*serv->rmx);
  433. tlog5 << "Listening... ";
  434. *serv >> ret;
  435. tlog5 << "\treceived server message of type " << typeid(*ret).name() << std::endl;
  436. return ret;
  437. }
  438. void CClient::handlePack( CPack * pack )
  439. {
  440. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  441. if(apply)
  442. {
  443. apply->applyOnClBefore(this,pack);
  444. tlog5 << "\tMade first apply on cl\n";
  445. gs->apply(pack);
  446. tlog5 << "\tApplied on gs\n";
  447. apply->applyOnClAfter(this,pack);
  448. tlog5 << "\tMade second apply on cl\n";
  449. }
  450. else
  451. {
  452. tlog1 << "Message cannot be applied, cannot find applier!\n";
  453. }
  454. delete pack;
  455. }
  456. void CClient::updatePaths()
  457. {
  458. const CGHeroInstance *h = getHero(getSelectedHero());
  459. if (h)//if we have selected hero...
  460. gs->calculatePaths(h, *pathInfo);
  461. }
  462. void CClient::finishCampaign( CCampaignState * camp )
  463. {
  464. }
  465. void CClient::proposeNextMission( CCampaignState * camp )
  466. {
  467. GH.pushInt(new CBonusSelection(camp));
  468. GH.curInt = CGP;
  469. }
  470. void CClient::stopConnection()
  471. {
  472. terminate = true;
  473. if (serv)
  474. {
  475. tlog0 << "Connection has been requested to be closed.\n";
  476. boost::unique_lock<boost::mutex>(*serv->wmx);
  477. *serv << &CloseServer();
  478. tlog0 << "Sent closing signal to the server\n";
  479. serv->close();
  480. delete serv;
  481. serv = NULL;
  482. tlog3 << "Our socket has been closed." << std::endl;
  483. }
  484. if(connectionHandler)
  485. {
  486. if(connectionHandler->get_id() != boost::this_thread::get_id())
  487. connectionHandler->join();
  488. tlog0 << "Connection handler thread joined" << std::endl;
  489. delete connectionHandler;
  490. connectionHandler = NULL;
  491. }
  492. }
  493. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  494. template void CClient::serialize( COSer<CSaveFile> &h, const int version );