Client.cpp 17 KB

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