Client.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. #include "StdInc.h"
  2. #include "CMusicHandler.h"
  3. #include "../lib/mapping/CCampaignHandler.h"
  4. #include "../CCallback.h"
  5. #include "../lib/CConsoleHandler.h"
  6. #include "CGameInfo.h"
  7. #include "../lib/CGameState.h"
  8. #include "CPlayerInterface.h"
  9. #include "../lib/StartInfo.h"
  10. #include "../lib/BattleState.h"
  11. #include "../lib/CModHandler.h"
  12. #include "../lib/CArtHandler.h"
  13. #include "../lib/CDefObjInfoHandler.h"
  14. #include "../lib/CGeneralTextHandler.h"
  15. #include "../lib/CHeroHandler.h"
  16. #include "../lib/CTownHandler.h"
  17. #include "../lib/CObjectHandler.h"
  18. #include "../lib/CBuildingHandler.h"
  19. #include "../lib/CSpellHandler.h"
  20. #include "../lib/Connection.h"
  21. #include "../lib/Interprocess.h"
  22. #include "../lib/NetPacks.h"
  23. #include "../lib/VCMI_Lib.h"
  24. #include "../lib/VCMIDirs.h"
  25. #include "../lib/mapping/CMap.h"
  26. #include "../lib/JsonNode.h"
  27. #include "mapHandler.h"
  28. #include "../lib/CConfigHandler.h"
  29. #include "Client.h"
  30. #include "CPreGame.h"
  31. #include "battle/CBattleInterface.h"
  32. #include "../lib/CThreadHelper.h"
  33. #include "../lib/CScriptingModule.h"
  34. #include "../lib/RegisterTypes.h"
  35. #include "gui/CGuiHandler.h"
  36. extern std::string NAME;
  37. namespace intpr = boost::interprocess;
  38. /*
  39. * Client.cpp, part of VCMI engine
  40. *
  41. * Authors: listed in file AUTHORS in main folder
  42. *
  43. * License: GNU General Public License v2.0 or later
  44. * Full text of license available in license.txt file, in main folder
  45. *
  46. */
  47. template <typename T> class CApplyOnCL;
  48. class CBaseForCLApply
  49. {
  50. public:
  51. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  52. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  53. virtual ~CBaseForCLApply(){}
  54. template<typename U> static CBaseForCLApply *getApplier(const U * t=NULL)
  55. {
  56. return new CApplyOnCL<U>;
  57. }
  58. };
  59. template <typename T> class CApplyOnCL : public CBaseForCLApply
  60. {
  61. public:
  62. void applyOnClAfter(CClient *cl, void *pack) const
  63. {
  64. T *ptr = static_cast<T*>(pack);
  65. ptr->applyCl(cl);
  66. }
  67. void applyOnClBefore(CClient *cl, void *pack) const
  68. {
  69. T *ptr = static_cast<T*>(pack);
  70. ptr->applyFirstCl(cl);
  71. }
  72. };
  73. static CApplier<CBaseForCLApply> *applier = nullptr;
  74. void CClient::init()
  75. {
  76. hotSeat = false;
  77. connectionHandler = nullptr;
  78. pathInfo = nullptr;
  79. applier = new CApplier<CBaseForCLApply>;
  80. registerTypes2(*applier);
  81. IObjectInterface::cb = this;
  82. serv = nullptr;
  83. gs = nullptr;
  84. cb = nullptr;
  85. erm = nullptr;
  86. terminate = false;
  87. }
  88. CClient::CClient(void)
  89. {
  90. init();
  91. }
  92. CClient::CClient(CConnection *con, StartInfo *si)
  93. {
  94. init();
  95. newGame(con,si);
  96. }
  97. CClient::~CClient(void)
  98. {
  99. delete applier;
  100. }
  101. void CClient::waitForMoveAndSend(PlayerColor color)
  102. {
  103. try
  104. {
  105. setThreadName("CClient::waitForMoveAndSend");
  106. assert(vstd::contains(battleints, color));
  107. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  108. MakeAction temp_action(ba);
  109. sendRequest(&temp_action, color);
  110. return;
  111. }
  112. catch(boost::thread_interrupted&)
  113. {
  114. logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
  115. return;
  116. }
  117. HANDLE_EXCEPTION
  118. logNetwork->errorStream() << "We should not be here!";
  119. }
  120. void CClient::run()
  121. {
  122. setThreadName("CClient::run");
  123. try
  124. {
  125. CPack *pack = NULL;
  126. while(!terminate)
  127. {
  128. pack = serv->retreivePack(); //get the package from the server
  129. if (terminate)
  130. {
  131. delete pack;
  132. pack = NULL;
  133. break;
  134. }
  135. handlePack(pack);
  136. pack = NULL;
  137. }
  138. }
  139. //catch only asio exceptions
  140. catch (const boost::system::system_error& e)
  141. {
  142. logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
  143. logNetwork->errorStream() << e.what();
  144. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  145. {
  146. logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
  147. throw;
  148. }
  149. }
  150. }
  151. void CClient::save(const std::string & fname)
  152. {
  153. if(gs->curB)
  154. {
  155. logNetwork->errorStream() << "Game cannot be saved during battle!";
  156. return;
  157. }
  158. SaveGame save_game(fname);
  159. sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
  160. }
  161. void CClient::endGame( bool closeConnection /*= true*/ )
  162. {
  163. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  164. BOOST_FOREACH(auto i, playerint)
  165. i.second->finish();
  166. // Game is ending
  167. // Tell the network thread to reach a stable state
  168. if(closeConnection)
  169. stopConnection();
  170. logNetwork->infoStream() << "Closed connection.";
  171. GH.curInt = NULL;
  172. LOCPLINT->terminate_cond.setn(true);
  173. {
  174. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  175. logNetwork->infoStream() << "Ending current game!";
  176. if(GH.topInt())
  177. GH.topInt()->deactivate();
  178. GH.listInt.clear();
  179. GH.objsToBlit.clear();
  180. GH.statusbar = NULL;
  181. logNetwork->infoStream() << "Removed GUI.";
  182. vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
  183. vstd::clear_pointer(gs);
  184. logNetwork->infoStream() << "Deleted mapHandler and gameState.";
  185. LOCPLINT = NULL;
  186. }
  187. while (!playerint.empty())
  188. {
  189. CGameInterface *pint = playerint.begin()->second;
  190. playerint.erase(playerint.begin());
  191. delete pint;
  192. }
  193. callbacks.clear();
  194. logNetwork->infoStream() << "Deleted playerInts.";
  195. logNetwork->infoStream() << "Client stopped.";
  196. }
  197. void CClient::loadGame( const std::string & fname )
  198. {
  199. logNetwork->infoStream() <<"Loading procedure started!";
  200. CServerHandler sh;
  201. sh.startServer();
  202. CStopWatch tmh;
  203. try
  204. {
  205. std::string clientSaveName = CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  206. std::string controlServerSaveName;
  207. if (CResourceHandler::get()->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
  208. {
  209. controlServerSaveName = CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  210. }
  211. else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  212. {
  213. controlServerSaveName = clientSaveName.substr(0, clientSaveName.find_last_of(".")) + ".vsgm1";
  214. CResourceHandler::get()->createResource(controlServerSaveName, true);
  215. }
  216. if(clientSaveName.empty())
  217. throw std::runtime_error("Cannot open client part of " + fname);
  218. if(controlServerSaveName.empty())
  219. throw std::runtime_error("Cannot open server part of " + fname);
  220. unique_ptr<CLoadFile> loader;
  221. {
  222. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName);
  223. loadCommonState(checkingLoader);
  224. loader = checkingLoader.decay();
  225. }
  226. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  227. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  228. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  229. pathInfo = make_unique<CPathsInfo>(getMapSize());
  230. CGI->mh->init();
  231. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  232. *loader >> *this;
  233. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  234. }
  235. catch(std::exception &e)
  236. {
  237. logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
  238. throw; //obviously we cannot continue here
  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 std::runtime_error("Server cannot open the savegame!");
  249. else
  250. logNetwork->infoStream() << "Server opened savegame properly.";
  251. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  252. for(auto it = gs->scenarioOps->playerInfos.begin();
  253. it != gs->scenarioOps->playerInfos.end(); ++it)
  254. {
  255. *serv << ui8(it->first.getNum()); //players
  256. }
  257. *serv << ui8(PlayerColor::NEUTRAL.getNum());
  258. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  259. serv->enableStackSendingByID();
  260. serv->disableSmartPointerSerialization();
  261. }
  262. void CClient::newGame( CConnection *con, StartInfo *si )
  263. {
  264. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  265. if (con == NULL)
  266. {
  267. CServerHandler sh;
  268. serv = sh.connectToServer();
  269. }
  270. else
  271. {
  272. serv = con;
  273. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  274. }
  275. CConnection &c = *serv;
  276. ////////////////////////////////////////////////////
  277. logNetwork->infoStream() <<"\tWill send info to server...";
  278. CStopWatch tmh;
  279. if(networkMode == SINGLE)
  280. {
  281. ui8 pom8;
  282. c << ui8(2) << ui8(1); //new game; one client
  283. c << *si;
  284. c >> pom8;
  285. if(pom8)
  286. throw std::runtime_error("Server cannot open the map!");
  287. else
  288. logNetwork->infoStream() << "Server opened map properly.";
  289. }
  290. c >> si;
  291. logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
  292. c.enableStackSendingByID();
  293. c.disableSmartPointerSerialization();
  294. // Initialize game state
  295. gs = new CGameState();
  296. logNetwork->infoStream() <<"\tCreating gamestate: "<<tmh.getDiff();
  297. gs->scenarioOps = si;
  298. gs->init(si);
  299. logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
  300. // Now after possible random map gen, we know exact player count.
  301. // Inform server about how many players client handles
  302. std::set<PlayerColor> myPlayers;
  303. for(auto it = gs->scenarioOps->playerInfos.begin(); it != gs->scenarioOps->playerInfos.end(); ++it)
  304. {
  305. if((networkMode == SINGLE) //single - one client has all player
  306. || (networkMode != SINGLE && serv->connectionID == it->second.playerID) //multi - client has only "its players"
  307. || (networkMode == HOST && it->second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
  308. {
  309. myPlayers.insert(it->first); //add player
  310. }
  311. }
  312. if(networkMode != GUEST)
  313. myPlayers.insert(PlayerColor::NEUTRAL);
  314. c << myPlayers;
  315. // Init map handler
  316. if(gs->map)
  317. {
  318. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  319. CGI->mh->map = gs->map;
  320. logNetwork->infoStream() <<"Creating mapHandler: "<<tmh.getDiff();
  321. CGI->mh->init();
  322. pathInfo = make_unique<CPathsInfo>(getMapSize());
  323. logNetwork->infoStream() <<"Initializing mapHandler (together): "<<tmh.getDiff();
  324. }
  325. int humanPlayers = 0;
  326. int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  327. for(auto it = gs->scenarioOps->playerInfos.begin();
  328. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  329. {
  330. PlayerColor color = it->first;
  331. gs->currentPlayer = color;
  332. if(!vstd::contains(myPlayers, color))
  333. continue;
  334. logNetwork->traceStream() << "Preparing interface for player " << color;
  335. if(si->mode != StartInfo::DUEL)
  336. {
  337. auto cb = make_shared<CCallback>(gs,color,this);
  338. if(it->second.playerID == PlayerSettings::PLAYER_AI)
  339. {
  340. std::string AItoGive = settings["server"]["playerAI"].String();
  341. if(!sensibleAILimit)
  342. AItoGive = "EmptyAI";
  343. else
  344. sensibleAILimit--;
  345. playerint[color] = static_cast<CGameInterface*>(CDynLibHandler::getNewAI(AItoGive));
  346. logNetwork->infoStream() << "Player " << static_cast<int>(color.getNum()) << " will be lead by " << AItoGive;
  347. }
  348. else
  349. {
  350. playerint[color] = new CPlayerInterface(color);
  351. humanPlayers++;
  352. }
  353. battleints[color] = playerint[color];
  354. logNetwork->traceStream() << "\tInitializing the interface";
  355. playerint[color]->init(cb.get());
  356. battleCallbacks[color] = callbacks[color] = cb;
  357. }
  358. else
  359. {
  360. auto cbc = make_shared<CBattleCallback>(gs, color, this);
  361. battleCallbacks[color] = cbc;
  362. if(color == PlayerColor(0))
  363. battleints[color] = CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String());
  364. else
  365. battleints[color] = CDynLibHandler::getNewBattleAI("StupidAI");
  366. battleints[color]->init(cbc.get());
  367. }
  368. }
  369. if(si->mode == StartInfo::DUEL)
  370. {
  371. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  372. CPlayerInterface *p = new CPlayerInterface(PlayerColor::NEUTRAL); //TODO: check if neutral really works -- was -1, but CPlayerInterface seems to cooperate with this value not too well
  373. p->observerInDuelMode = true;
  374. battleints[PlayerColor::UNFLAGGABLE] = playerint[PlayerColor::UNFLAGGABLE] = p;
  375. privilagedBattleEventReceivers.push_back(p);
  376. GH.curInt = p;
  377. auto cb = make_shared<CCallback>(gs, boost::optional<PlayerColor>(), this);
  378. battleCallbacks[PlayerColor::NEUTRAL] = callbacks[PlayerColor::NEUTRAL] = cb;
  379. p->init(cb.get());
  380. battleStarted(gs->curB);
  381. }
  382. else
  383. {
  384. loadNeutralBattleAI();
  385. }
  386. serv->addStdVecItems(gs);
  387. hotSeat = (humanPlayers > 1);
  388. // std::vector<FileInfo> scriptModules;
  389. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
  390. // BOOST_FOREACH(FileInfo &m, scriptModules)
  391. // {
  392. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  393. // privilagedGameEventReceivers.push_back(nm);
  394. // privilagedBattleEventReceivers.push_back(nm);
  395. // nm->giveActionCB(this);
  396. // nm->giveInfoCB(this);
  397. // nm->init();
  398. //
  399. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  400. // }
  401. }
  402. template <typename Handler>
  403. void CClient::serialize( Handler &h, const int version )
  404. {
  405. h & hotSeat;
  406. if(h.saving)
  407. {
  408. ui8 players = playerint.size();
  409. h & players;
  410. for(auto i = playerint.begin(); i != playerint.end(); i++)
  411. {
  412. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  413. assert(i->first == i->second->playerID);
  414. h & i->first & i->second->dllName & i->second->human;
  415. i->second->saveGame(dynamic_cast<COSer<CSaveFile>&>(h), version);
  416. //evil cast that i still like better than sfinae-magic. If I had a "static if"...
  417. }
  418. }
  419. else
  420. {
  421. ui8 players = 0; //fix for uninitialized warning
  422. h & players;
  423. for(int i=0; i < players; i++)
  424. {
  425. std::string dllname;
  426. PlayerColor pid;
  427. bool isHuman = false;
  428. h & pid & dllname & isHuman;
  429. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  430. CGameInterface *nInt = nullptr;
  431. if(dllname.length())
  432. {
  433. if(pid == PlayerColor::NEUTRAL)
  434. {
  435. //CBattleCallback * cbc = new CBattleCallback(gs, pid, this);//FIXME: unused?
  436. CBattleGameInterface *cbgi = CDynLibHandler::getNewBattleAI(dllname);
  437. battleints[pid] = cbgi;
  438. cbgi->init(cb);
  439. //TODO? consider serialization
  440. continue;
  441. }
  442. else
  443. {
  444. assert(!isHuman);
  445. nInt = CDynLibHandler::getNewAI(dllname);
  446. }
  447. }
  448. else
  449. {
  450. assert(isHuman);
  451. nInt = new CPlayerInterface(pid);
  452. }
  453. nInt->dllName = dllname;
  454. nInt->human = isHuman;
  455. nInt->playerID = pid;
  456. battleCallbacks[pid] = callbacks[pid] = make_shared<CCallback>(gs,pid,this);
  457. battleints[pid] = playerint[pid] = nInt;
  458. nInt->init(callbacks[pid].get());
  459. nInt->loadGame(dynamic_cast<CISer<CLoadFile>&>(h), version); //another evil cast, check above
  460. }
  461. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  462. loadNeutralBattleAI();
  463. }
  464. }
  465. void CClient::handlePack( CPack * pack )
  466. {
  467. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  468. if(apply)
  469. {
  470. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  471. apply->applyOnClBefore(this,pack);
  472. logNetwork->traceStream() << "\tMade first apply on cl";
  473. gs->apply(pack);
  474. logNetwork->traceStream() << "\tApplied on gs";
  475. apply->applyOnClAfter(this,pack);
  476. logNetwork->traceStream() << "\tMade second apply on cl";
  477. }
  478. else
  479. {
  480. logNetwork->errorStream() << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack);
  481. }
  482. delete pack;
  483. }
  484. void CClient::updatePaths()
  485. {
  486. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  487. const CGHeroInstance *h = getSelectedHero();
  488. if (h)//if we have selected hero...
  489. calculatePaths(h);
  490. }
  491. void CClient::finishCampaign( shared_ptr<CCampaignState> camp )
  492. {
  493. }
  494. void CClient::proposeNextMission(shared_ptr<CCampaignState> camp)
  495. {
  496. GH.pushInt(new CBonusSelection(camp));
  497. }
  498. void CClient::stopConnection()
  499. {
  500. terminate = true;
  501. if (serv) //request closing connection
  502. {
  503. logNetwork->infoStream() << "Connection has been requested to be closed.";
  504. boost::unique_lock<boost::mutex>(*serv->wmx);
  505. CloseServer close_server;
  506. sendRequest(&close_server, PlayerColor::NEUTRAL);
  507. logNetwork->infoStream() << "Sent closing signal to the server";
  508. }
  509. if(connectionHandler)//end connection handler
  510. {
  511. if(connectionHandler->get_id() != boost::this_thread::get_id())
  512. connectionHandler->join();
  513. logNetwork->infoStream() << "Connection handler thread joined";
  514. delete connectionHandler;
  515. connectionHandler = NULL;
  516. }
  517. if (serv) //and delete connection
  518. {
  519. serv->close();
  520. delete serv;
  521. serv = NULL;
  522. logNetwork->warnStream() << "Our socket has been closed.";
  523. }
  524. }
  525. void CClient::battleStarted(const BattleInfo * info)
  526. {
  527. BOOST_FOREACH(auto &battleCb, battleCallbacks)
  528. {
  529. if(vstd::contains(info->sides, battleCb.first) || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  530. battleCb.second->setBattle(info);
  531. }
  532. // BOOST_FOREACH(ui8 side, info->sides)
  533. // if(battleCallbacks.count(side))
  534. // battleCallbacks[side]->setBattle(info);
  535. CPlayerInterface * att, * def;
  536. if(vstd::contains(playerint, info->sides[0]) && playerint[info->sides[0]]->human)
  537. att = static_cast<CPlayerInterface*>( playerint[info->sides[0]] );
  538. else
  539. att = NULL;
  540. if(vstd::contains(playerint, info->sides[1]) && playerint[info->sides[1]]->human)
  541. def = static_cast<CPlayerInterface*>( playerint[info->sides[1]] );
  542. else
  543. def = NULL;
  544. if(att || def || gs->scenarioOps->mode == StartInfo::DUEL)
  545. {
  546. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  547. new CBattleInterface(info->belligerents[0], info->belligerents[1], info->heroes[0], info->heroes[1],
  548. Rect((screen->w - 800)/2,
  549. (screen->h - 600)/2, 800, 600), att, def);
  550. }
  551. if(vstd::contains(battleints,info->sides[0]))
  552. battleints[info->sides[0]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  553. if(vstd::contains(battleints,info->sides[1]))
  554. battleints[info->sides[1]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  555. if(vstd::contains(battleints,PlayerColor::UNFLAGGABLE))
  556. battleints[PlayerColor::UNFLAGGABLE]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  557. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide]))
  558. {
  559. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide]]);
  560. }
  561. }
  562. void CClient::battleFinished()
  563. {
  564. BOOST_FOREACH(PlayerColor side, gs->curB->sides)
  565. if(battleCallbacks.count(side))
  566. battleCallbacks[side]->setBattle(nullptr);
  567. }
  568. void CClient::loadNeutralBattleAI()
  569. {
  570. battleints[PlayerColor::NEUTRAL] = CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String());
  571. auto cbc = make_shared<CBattleCallback>(gs, PlayerColor::NEUTRAL, this);
  572. battleCallbacks[PlayerColor::NEUTRAL] = cbc;
  573. battleints[PlayerColor::NEUTRAL]->init(cbc.get());
  574. }
  575. void CClient::commitPackage( CPackForClient *pack )
  576. {
  577. CommitPackage cp;
  578. cp.freePack = false;
  579. cp.packToCommit = pack;
  580. sendRequest(&cp, PlayerColor::NEUTRAL);
  581. }
  582. PlayerColor CClient::getLocalPlayer() const
  583. {
  584. if(LOCPLINT)
  585. return LOCPLINT->playerID;
  586. return getCurrentPlayer();
  587. }
  588. void CClient::calculatePaths(const CGHeroInstance *h)
  589. {
  590. assert(h);
  591. boost::unique_lock<boost::mutex> pathLock(pathMx);
  592. gs->calculatePaths(h, *pathInfo);
  593. }
  594. void CClient::commenceTacticPhaseForInt(CBattleGameInterface *battleInt)
  595. {
  596. setThreadName("CClient::commenceTacticPhaseForInt");
  597. try
  598. {
  599. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  600. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  601. {
  602. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  603. sendRequest(&ma, battleInt->playerID);
  604. }
  605. } HANDLE_EXCEPTION
  606. }
  607. void CClient::invalidatePaths(const CGHeroInstance *h /*= NULL*/)
  608. {
  609. if(!h || pathInfo->hero == h)
  610. pathInfo->isValid = false;
  611. }
  612. int CClient::sendRequest(const CPack *request, PlayerColor player)
  613. {
  614. static ui32 requestCounter = 0;
  615. ui32 requestID = requestCounter++;
  616. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  617. % typeid(*request).name() % requestID;
  618. waitingRequest.pushBack(requestID);
  619. serv->sendPackToServer(*request, player, requestID);
  620. if(vstd::contains(playerint, player))
  621. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  622. return requestID;
  623. }
  624. void CClient::campaignMapFinished( shared_ptr<CCampaignState> camp )
  625. {
  626. endGame(false);
  627. LOCPLINT = nullptr; //TODO free res
  628. GH.curInt = CGPreGame::create();
  629. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  630. auto finisher = [&]()
  631. {
  632. if(camp->mapsRemaining.size())
  633. proposeNextMission(camp);
  634. else
  635. finishCampaign(camp);
  636. };
  637. if(epilogue.hasPrologEpilog)
  638. {
  639. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  640. }
  641. else
  642. {
  643. finisher();
  644. }
  645. }
  646. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  647. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  648. void CServerHandler::startServer()
  649. {
  650. th.update();
  651. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  652. if(verbose)
  653. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  654. }
  655. void CServerHandler::waitForServer()
  656. {
  657. if(!serverThread)
  658. startServer();
  659. th.update();
  660. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  661. while(!shared->sr->ready)
  662. {
  663. shared->sr->cond.wait(slock);
  664. }
  665. if(verbose)
  666. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  667. }
  668. CConnection * CServerHandler::connectToServer()
  669. {
  670. if(!shared->sr->ready)
  671. waitForServer();
  672. th.update(); //put breakpoint here to attach to server before it does something stupid
  673. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  674. if(verbose)
  675. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  676. return ret;
  677. }
  678. CServerHandler::CServerHandler(bool runServer /*= false*/)
  679. {
  680. serverThread = NULL;
  681. shared = NULL;
  682. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  683. verbose = true;
  684. 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
  685. try
  686. {
  687. shared = new SharedMem();
  688. } HANDLE_EXCEPTIONC(logNetwork->errorStream() << "Cannot open interprocess memory: ";)
  689. }
  690. CServerHandler::~CServerHandler()
  691. {
  692. delete shared;
  693. delete serverThread; //detaches, not kills thread
  694. }
  695. void CServerHandler::callServer()
  696. {
  697. setThreadName("CServerHandler::callServer");
  698. std::string logName = VCMIDirs::get().localPath() + "/server_log.txt";
  699. std::string comm = VCMIDirs::get().serverPath() + " " + port + " > " + logName;
  700. int result = std::system(comm.c_str());
  701. if (result == 0)
  702. logNetwork->infoStream() << "Server closed correctly";
  703. else
  704. {
  705. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  706. logNetwork->errorStream() << "Check " << logName << " for more info";
  707. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  708. }
  709. }
  710. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  711. {
  712. CConnection *ret = NULL;
  713. while(!ret)
  714. {
  715. try
  716. {
  717. logNetwork->infoStream() << "Establishing connection...";
  718. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  719. port.size() ? port : boost::lexical_cast<std::string>(settings["server"]["port"].Float()),
  720. NAME);
  721. }
  722. catch(...)
  723. {
  724. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  725. SDL_Delay(2000);
  726. }
  727. }
  728. return ret;
  729. }