Client.cpp 22 KB

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