Client.cpp 17 KB

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