Client.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. #include "StdInc.h"
  2. #include "Client.h"
  3. #include <SDL.h>
  4. #include "CMusicHandler.h"
  5. #include "../lib/mapping/CCampaignHandler.h"
  6. #include "../CCallback.h"
  7. #include "../lib/CConsoleHandler.h"
  8. #include "CGameInfo.h"
  9. #include "../lib/CGameState.h"
  10. #include "CPlayerInterface.h"
  11. #include "../lib/StartInfo.h"
  12. #include "../lib/BattleState.h"
  13. #include "../lib/CModHandler.h"
  14. #include "../lib/CArtHandler.h"
  15. #include "../lib/CGeneralTextHandler.h"
  16. #include "../lib/CHeroHandler.h"
  17. #include "../lib/CTownHandler.h"
  18. #include "../lib/CBuildingHandler.h"
  19. #include "../lib/spells/CSpellHandler.h"
  20. #include "../lib/serializer/CTypeList.h"
  21. #include "../lib/serializer/Connection.h"
  22. #include "../lib/serializer/CLoadIntegrityValidator.h"
  23. #ifndef VCMI_ANDROID
  24. #include "../lib/Interprocess.h"
  25. #endif
  26. #include "../lib/NetPacks.h"
  27. #include "../lib/VCMI_Lib.h"
  28. #include "../lib/VCMIDirs.h"
  29. #include "../lib/mapping/CMap.h"
  30. #include "../lib/JsonNode.h"
  31. #include "mapHandler.h"
  32. #include "../lib/CConfigHandler.h"
  33. #include "CPreGame.h"
  34. #include "battle/CBattleInterface.h"
  35. #include "../lib/CThreadHelper.h"
  36. #include "../lib/CScriptingModule.h"
  37. #include "../lib/registerTypes/RegisterTypes.h"
  38. #include "gui/CGuiHandler.h"
  39. #include "CMT.h"
  40. extern std::string NAME;
  41. #ifndef VCMI_ANDROID
  42. namespace intpr = boost::interprocess;
  43. #endif
  44. /*
  45. * Client.cpp, part of VCMI engine
  46. *
  47. * Authors: listed in file AUTHORS in main folder
  48. *
  49. * License: GNU General Public License v2.0 or later
  50. * Full text of license available in license.txt file, in main folder
  51. *
  52. */
  53. template <typename T> class CApplyOnCL;
  54. class CBaseForCLApply
  55. {
  56. public:
  57. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  58. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  59. virtual ~CBaseForCLApply(){}
  60. template<typename U> static CBaseForCLApply *getApplier(const U * t=nullptr)
  61. {
  62. return new CApplyOnCL<U>;
  63. }
  64. };
  65. template <typename T> class CApplyOnCL : public CBaseForCLApply
  66. {
  67. public:
  68. void applyOnClAfter(CClient *cl, void *pack) const override
  69. {
  70. T *ptr = static_cast<T*>(pack);
  71. ptr->applyCl(cl);
  72. }
  73. void applyOnClBefore(CClient *cl, void *pack) const override
  74. {
  75. T *ptr = static_cast<T*>(pack);
  76. ptr->applyFirstCl(cl);
  77. }
  78. };
  79. template <> class CApplyOnCL<CPack> : public CBaseForCLApply
  80. {
  81. public:
  82. void applyOnClAfter(CClient *cl, void *pack) const override
  83. {
  84. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  85. assert(0);
  86. }
  87. void applyOnClBefore(CClient *cl, void *pack) const override
  88. {
  89. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  90. assert(0);
  91. }
  92. };
  93. static CApplier<CBaseForCLApply> *applier = nullptr;
  94. void CClient::init()
  95. {
  96. hotSeat = false;
  97. connectionHandler = nullptr;
  98. pathInfo = nullptr;
  99. applier = new CApplier<CBaseForCLApply>;
  100. registerTypesClientPacks1(*applier);
  101. registerTypesClientPacks2(*applier);
  102. IObjectInterface::cb = this;
  103. serv = nullptr;
  104. gs = nullptr;
  105. erm = nullptr;
  106. terminate = false;
  107. }
  108. CClient::CClient(void)
  109. {
  110. init();
  111. }
  112. CClient::CClient(CConnection *con, StartInfo *si)
  113. {
  114. init();
  115. newGame(con,si);
  116. }
  117. CClient::~CClient(void)
  118. {
  119. delete applier;
  120. }
  121. void CClient::waitForMoveAndSend(PlayerColor color)
  122. {
  123. try
  124. {
  125. setThreadName("CClient::waitForMoveAndSend");
  126. assert(vstd::contains(battleints, color));
  127. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  128. if(ba.actionType != Battle::CANCEL)
  129. {
  130. logNetwork->traceStream() << "Send battle action to server: " << ba;
  131. MakeAction temp_action(ba);
  132. sendRequest(&temp_action, color);
  133. }
  134. return;
  135. }
  136. catch(boost::thread_interrupted&)
  137. {
  138. logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
  139. return;
  140. }
  141. catch(...)
  142. {
  143. handleException();
  144. return;
  145. }
  146. logNetwork->errorStream() << "We should not be here!";
  147. }
  148. void CClient::run()
  149. {
  150. setThreadName("CClient::run");
  151. try
  152. {
  153. while(!terminate)
  154. {
  155. CPack *pack = serv->retreivePack(); //get the package from the server
  156. if (terminate)
  157. {
  158. vstd::clear_pointer(pack);
  159. break;
  160. }
  161. handlePack(pack);
  162. }
  163. }
  164. //catch only asio exceptions
  165. catch (const boost::system::system_error& e)
  166. {
  167. logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
  168. logNetwork->errorStream() << e.what();
  169. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  170. {
  171. logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
  172. throw;
  173. }
  174. }
  175. }
  176. void CClient::save(const std::string & fname)
  177. {
  178. if(gs->curB)
  179. {
  180. logNetwork->errorStream() << "Game cannot be saved during battle!";
  181. return;
  182. }
  183. SaveGame save_game(fname);
  184. sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
  185. }
  186. void CClient::endGame(bool closeConnection /*= true*/)
  187. {
  188. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  189. for (auto& i : playerint)
  190. i.second->finish();
  191. // Game is ending
  192. // Tell the network thread to reach a stable state
  193. if (closeConnection)
  194. stopConnection();
  195. logNetwork->infoStream() << "Closed connection.";
  196. GH.curInt = nullptr;
  197. {
  198. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  199. logNetwork->infoStream() << "Ending current game!";
  200. if(GH.topInt())
  201. {
  202. GH.topInt()->deactivate();
  203. }
  204. GH.listInt.clear();
  205. GH.objsToBlit.clear();
  206. GH.statusbar = nullptr;
  207. logNetwork->infoStream() << "Removed GUI.";
  208. vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
  209. vstd::clear_pointer(gs);
  210. logNetwork->infoStream() << "Deleted mapHandler and gameState.";
  211. LOCPLINT = nullptr;
  212. }
  213. playerint.clear();
  214. battleints.clear();
  215. callbacks.clear();
  216. battleCallbacks.clear();
  217. CGKeys::reset();
  218. CGMagi::reset();
  219. CGObelisk::reset();
  220. logNetwork->infoStream() << "Deleted playerInts.";
  221. logNetwork->infoStream() << "Client stopped.";
  222. }
  223. #if 1
  224. void CClient::loadGame(const std::string & fname, const bool server, const std::vector<int>& humanplayerindices, const int loadNumPlayers, int player_, const std::string & ipaddr, const std::string & port)
  225. {
  226. PlayerColor player(player_); //intentional shadowing
  227. logNetwork->infoStream() << "Loading procedure started!";
  228. std::string realPort;
  229. if(settings["testing"]["enabled"].Bool())
  230. realPort = settings["testing"]["port"].String();
  231. else if(port.size())
  232. realPort = port;
  233. else
  234. realPort = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  235. CServerHandler sh;
  236. if(server)
  237. sh.startServer();
  238. else
  239. serv = sh.justConnectToServer(ipaddr, realPort);
  240. CStopWatch tmh;
  241. std::unique_ptr<CLoadFile> loader;
  242. try
  243. {
  244. boost::filesystem::path clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  245. boost::filesystem::path controlServerSaveName;
  246. if (CResourceHandler::get("local")->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
  247. {
  248. controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  249. }
  250. else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  251. {
  252. controlServerSaveName = boost::filesystem::path(clientSaveName).replace_extension(".vsgm1");
  253. CResourceHandler::get("local")->createResource(controlServerSaveName.string(), true);
  254. }
  255. if(clientSaveName.empty())
  256. throw std::runtime_error("Cannot open client part of " + fname);
  257. if(controlServerSaveName.empty() || !boost::filesystem::exists(controlServerSaveName))
  258. throw std::runtime_error("Cannot open server part of " + fname);
  259. {
  260. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName, MINIMAL_SERIALIZATION_VERSION);
  261. loadCommonState(checkingLoader);
  262. loader = checkingLoader.decay();
  263. }
  264. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  265. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  266. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  267. pathInfo = make_unique<CPathsInfo>(getMapSize());
  268. CGI->mh->init();
  269. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  270. }
  271. catch(std::exception &e)
  272. {
  273. logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
  274. throw; //obviously we cannot continue here
  275. }
  276. /*
  277. if(!server)
  278. player = PlayerColor(player_);
  279. */
  280. std::set<PlayerColor> clientPlayers;
  281. if(server)
  282. serv = sh.connectToServer();
  283. //*loader >> *this;
  284. if(server)
  285. {
  286. tmh.update();
  287. ui8 pom8;
  288. *serv << ui8(3) << ui8(loadNumPlayers); //load game; one client if single-player
  289. *serv << fname;
  290. *serv >> pom8;
  291. if(pom8)
  292. throw std::runtime_error("Server cannot open the savegame!");
  293. else
  294. logNetwork->infoStream() << "Server opened savegame properly.";
  295. }
  296. if(server)
  297. {
  298. for(auto & elem : gs->scenarioOps->playerInfos)
  299. {
  300. if(!std::count(humanplayerindices.begin(),humanplayerindices.end(),elem.first.getNum()) || elem.first==player)
  301. clientPlayers.insert(elem.first);
  302. }
  303. clientPlayers.insert(PlayerColor::NEUTRAL);
  304. }
  305. else
  306. {
  307. clientPlayers.insert(player);
  308. }
  309. std::cout << "CLIENTPLAYERS:\n";
  310. for(auto x : clientPlayers)
  311. std::cout << x << std::endl;
  312. std::cout << "ENDCLIENTPLAYERS\n";
  313. serialize(loader->serializer,0,clientPlayers);
  314. *serv << ui32(clientPlayers.size());
  315. for(auto & elem : clientPlayers)
  316. *serv << ui8(elem.getNum());
  317. serv->addStdVecItems(gs); /*why is this here?*/
  318. //*loader >> *this;
  319. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  320. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  321. //*serv << clientPlayers;
  322. serv->enableStackSendingByID();
  323. serv->disableSmartPointerSerialization();
  324. // logGlobal->traceStream() << "Objects:";
  325. // for(int i = 0; i < gs->map->objects.size(); i++)
  326. // {
  327. // auto o = gs->map->objects[i];
  328. // if(o)
  329. // logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
  330. // else
  331. // logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
  332. // }
  333. }
  334. #endif
  335. void CClient::newGame( CConnection *con, StartInfo *si )
  336. {
  337. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  338. if (con == nullptr)
  339. {
  340. CServerHandler sh;
  341. serv = sh.connectToServer();
  342. }
  343. else
  344. {
  345. serv = con;
  346. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  347. }
  348. CConnection &c = *serv;
  349. ////////////////////////////////////////////////////
  350. logNetwork->infoStream() <<"\tWill send info to server...";
  351. CStopWatch tmh;
  352. if(networkMode == SINGLE)
  353. {
  354. ui8 pom8;
  355. c << ui8(2) << ui8(1); //new game; one client
  356. c << *si;
  357. c >> pom8;
  358. if(pom8) throw std::runtime_error("Server cannot open the map!");
  359. }
  360. c >> si;
  361. logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
  362. c.enableStackSendingByID();
  363. c.disableSmartPointerSerialization();
  364. // Initialize game state
  365. gs = new CGameState();
  366. logNetwork->infoStream() <<"\tCreating gamestate: "<<tmh.getDiff();
  367. gs->scenarioOps = si;
  368. gs->init(si);
  369. logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
  370. // Now after possible random map gen, we know exact player count.
  371. // Inform server about how many players client handles
  372. std::set<PlayerColor> myPlayers;
  373. for(auto & elem : gs->scenarioOps->playerInfos)
  374. {
  375. if((networkMode == SINGLE) //single - one client has all player
  376. || (networkMode != SINGLE && serv->connectionID == elem.second.playerID) //multi - client has only "its players"
  377. || (networkMode == HOST && elem.second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
  378. {
  379. myPlayers.insert(elem.first); //add player
  380. }
  381. }
  382. if(networkMode != GUEST)
  383. myPlayers.insert(PlayerColor::NEUTRAL);
  384. c << myPlayers;
  385. // Init map handler
  386. if(gs->map)
  387. {
  388. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  389. CGI->mh->map = gs->map;
  390. logNetwork->infoStream() << "Creating mapHandler: " << tmh.getDiff();
  391. CGI->mh->init();
  392. pathInfo = make_unique<CPathsInfo>(getMapSize());
  393. logNetwork->infoStream() << "Initializing mapHandler (together): " << tmh.getDiff();
  394. }
  395. int humanPlayers = 0;
  396. for(auto & elem : gs->scenarioOps->playerInfos)//initializing interfaces for players
  397. {
  398. PlayerColor color = elem.first;
  399. gs->currentPlayer = color;
  400. if(!vstd::contains(myPlayers, color))
  401. continue;
  402. logNetwork->traceStream() << "Preparing interface for player " << color;
  403. if(si->mode != StartInfo::DUEL)
  404. {
  405. if(elem.second.playerID == PlayerSettings::PLAYER_AI)
  406. {
  407. auto AiToGive = aiNameForPlayer(elem.second, false);
  408. logNetwork->infoStream() << boost::format("Player %s will be lead by %s") % color % AiToGive;
  409. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  410. }
  411. else
  412. {
  413. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  414. humanPlayers++;
  415. }
  416. }
  417. else
  418. {
  419. std::string AItoGive = aiNameForPlayer(elem.second, true);
  420. installNewBattleInterface(CDynLibHandler::getNewBattleAI(AItoGive), color);
  421. }
  422. }
  423. if(si->mode == StartInfo::DUEL)
  424. {
  425. if(!gNoGUI)
  426. {
  427. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  428. auto p = std::make_shared<CPlayerInterface>(PlayerColor::NEUTRAL);
  429. p->observerInDuelMode = true;
  430. installNewPlayerInterface(p, boost::none);
  431. GH.curInt = p.get();
  432. }
  433. battleStarted(gs->curB);
  434. }
  435. else
  436. {
  437. loadNeutralBattleAI();
  438. }
  439. serv->addStdVecItems(gs);
  440. hotSeat = (humanPlayers > 1);
  441. // std::vector<FileInfo> scriptModules;
  442. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
  443. // for(FileInfo &m : scriptModules)
  444. // {
  445. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  446. // privilagedGameEventReceivers.push_back(nm);
  447. // privilagedBattleEventReceivers.push_back(nm);
  448. // nm->giveActionCB(this);
  449. // nm->giveInfoCB(this);
  450. // nm->init();
  451. //
  452. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  453. // }
  454. }
  455. void CClient::serialize(BinarySerializer & h, const int version)
  456. {
  457. assert(h.saving);
  458. h & hotSeat;
  459. {
  460. ui8 players = playerint.size();
  461. h & players;
  462. for(auto i = playerint.begin(); i != playerint.end(); i++)
  463. {
  464. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  465. assert(i->first == i->second->playerID);
  466. h & i->first & i->second->dllName & i->second->human;
  467. i->second->saveGame(h, version);
  468. }
  469. }
  470. }
  471. void CClient::serialize(BinaryDeserializer & h, const int version)
  472. {
  473. assert(!h.saving);
  474. h & hotSeat;
  475. {
  476. ui8 players = 0; //fix for uninitialized warning
  477. h & players;
  478. for(int i=0; i < players; i++)
  479. {
  480. std::string dllname;
  481. PlayerColor pid;
  482. bool isHuman = false;
  483. h & pid & dllname & isHuman;
  484. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  485. std::shared_ptr<CGameInterface> nInt;
  486. if(dllname.length())
  487. {
  488. if(pid == PlayerColor::NEUTRAL)
  489. {
  490. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  491. //TODO? consider serialization
  492. continue;
  493. }
  494. else
  495. {
  496. assert(!isHuman);
  497. nInt = CDynLibHandler::getNewAI(dllname);
  498. }
  499. }
  500. else
  501. {
  502. assert(isHuman);
  503. nInt = std::make_shared<CPlayerInterface>(pid);
  504. }
  505. nInt->dllName = dllname;
  506. nInt->human = isHuman;
  507. nInt->playerID = pid;
  508. installNewPlayerInterface(nInt, pid);
  509. nInt->loadGame(h, version); //another evil cast, check above
  510. }
  511. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  512. loadNeutralBattleAI();
  513. }
  514. }
  515. void CClient::serialize(BinarySerializer & h, const int version, const std::set<PlayerColor> & playerIDs)
  516. {
  517. assert(h.saving);
  518. h & hotSeat;
  519. {
  520. ui8 players = playerint.size();
  521. h & players;
  522. for(auto i = playerint.begin(); i != playerint.end(); i++)
  523. {
  524. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  525. assert(i->first == i->second->playerID);
  526. h & i->first & i->second->dllName & i->second->human;
  527. i->second->saveGame(h, version);
  528. }
  529. }
  530. }
  531. void CClient::serialize(BinaryDeserializer & h, const int version, const std::set<PlayerColor> & playerIDs)
  532. {
  533. assert(!h.saving);
  534. h & hotSeat;
  535. {
  536. ui8 players = 0; //fix for uninitialized warning
  537. h & players;
  538. for(int i=0; i < players; i++)
  539. {
  540. std::string dllname;
  541. PlayerColor pid;
  542. bool isHuman = false;
  543. h & pid & dllname & isHuman;
  544. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  545. std::shared_ptr<CGameInterface> nInt;
  546. if(dllname.length())
  547. {
  548. if(pid == PlayerColor::NEUTRAL)
  549. {
  550. if(playerIDs.count(pid))
  551. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  552. //TODO? consider serialization
  553. continue;
  554. }
  555. else
  556. {
  557. assert(!isHuman);
  558. nInt = CDynLibHandler::getNewAI(dllname);
  559. }
  560. }
  561. else
  562. {
  563. assert(isHuman);
  564. nInt = std::make_shared<CPlayerInterface>(pid);
  565. }
  566. nInt->dllName = dllname;
  567. nInt->human = isHuman;
  568. nInt->playerID = pid;
  569. if(playerIDs.count(pid))
  570. installNewPlayerInterface(nInt, pid);
  571. nInt->loadGame(h, version);
  572. }
  573. if(playerIDs.count(PlayerColor::NEUTRAL))
  574. loadNeutralBattleAI();
  575. }
  576. }
  577. void CClient::handlePack( CPack * pack )
  578. {
  579. if(pack == nullptr)
  580. {
  581. logNetwork->error("Dropping nullptr CPack! You should check whether client and server ABI matches.");
  582. return;
  583. }
  584. CBaseForCLApply *apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  585. if(apply)
  586. {
  587. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  588. apply->applyOnClBefore(this, pack);
  589. logNetwork->trace("\tMade first apply on cl");
  590. gs->apply(pack);
  591. logNetwork->trace("\tApplied on gs");
  592. apply->applyOnClAfter(this, pack);
  593. logNetwork->trace("\tMade second apply on cl");
  594. }
  595. else
  596. {
  597. logNetwork->error("Message %s cannot be applied, cannot find applier!", typeList.getTypeInfo(pack)->name());
  598. }
  599. delete pack;
  600. }
  601. void CClient::finishCampaign( std::shared_ptr<CCampaignState> camp )
  602. {
  603. }
  604. void CClient::proposeNextMission(std::shared_ptr<CCampaignState> camp)
  605. {
  606. GH.pushInt(new CBonusSelection(camp));
  607. }
  608. void CClient::stopConnection()
  609. {
  610. terminate = true;
  611. if (serv) //request closing connection
  612. {
  613. logNetwork->infoStream() << "Connection has been requested to be closed.";
  614. boost::unique_lock<boost::mutex>(*serv->wmx);
  615. CloseServer close_server;
  616. sendRequest(&close_server, PlayerColor::NEUTRAL);
  617. logNetwork->infoStream() << "Sent closing signal to the server";
  618. }
  619. if(connectionHandler)//end connection handler
  620. {
  621. if(connectionHandler->get_id() != boost::this_thread::get_id())
  622. connectionHandler->join();
  623. logNetwork->infoStream() << "Connection handler thread joined";
  624. delete connectionHandler;
  625. connectionHandler = nullptr;
  626. }
  627. if (serv) //and delete connection
  628. {
  629. serv->close();
  630. delete serv;
  631. serv = nullptr;
  632. logNetwork->warnStream() << "Our socket has been closed.";
  633. }
  634. }
  635. void CClient::battleStarted(const BattleInfo * info)
  636. {
  637. for(auto &battleCb : battleCallbacks)
  638. {
  639. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  640. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  641. {
  642. battleCb.second->setBattle(info);
  643. }
  644. }
  645. // for(ui8 side : info->sides)
  646. // if(battleCallbacks.count(side))
  647. // battleCallbacks[side]->setBattle(info);
  648. std::shared_ptr<CPlayerInterface> att, def;
  649. auto &leftSide = info->sides[0], &rightSide = info->sides[1];
  650. //If quick combat is not, do not prepare interfaces for battleint
  651. if(!settings["adventure"]["quickCombat"].Bool())
  652. {
  653. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  654. att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[leftSide.color] );
  655. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  656. def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[rightSide.color] );
  657. }
  658. if(!gNoGUI && (!!att || !!def || gs->scenarioOps->mode == StartInfo::DUEL))
  659. {
  660. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  661. auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
  662. Rect((screen->w - 800)/2,
  663. (screen->h - 600)/2, 800, 600), att, def);
  664. GH.pushInt(bi);
  665. }
  666. auto callBattleStart = [&](PlayerColor color, ui8 side){
  667. if(vstd::contains(battleints, color))
  668. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  669. };
  670. callBattleStart(leftSide.color, 0);
  671. callBattleStart(rightSide.color, 1);
  672. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  673. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide].color))
  674. {
  675. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
  676. }
  677. }
  678. void CClient::battleFinished()
  679. {
  680. for(auto & side : gs->curB->sides)
  681. if(battleCallbacks.count(side.color))
  682. battleCallbacks[side.color]->setBattle(nullptr);
  683. }
  684. void CClient::loadNeutralBattleAI()
  685. {
  686. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  687. }
  688. void CClient::commitPackage( CPackForClient *pack )
  689. {
  690. CommitPackage cp;
  691. cp.freePack = false;
  692. cp.packToCommit = pack;
  693. sendRequest(&cp, PlayerColor::NEUTRAL);
  694. }
  695. PlayerColor CClient::getLocalPlayer() const
  696. {
  697. if(LOCPLINT)
  698. return LOCPLINT->playerID;
  699. return getCurrentPlayer();
  700. }
  701. void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
  702. {
  703. setThreadName("CClient::commenceTacticPhaseForInt");
  704. try
  705. {
  706. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  707. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  708. {
  709. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  710. sendRequest(&ma, battleInt->playerID);
  711. }
  712. }
  713. catch(...)
  714. {
  715. handleException();
  716. }
  717. }
  718. void CClient::invalidatePaths()
  719. {
  720. // turn pathfinding info into invalid. It will be regenerated later
  721. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  722. pathInfo->hero = nullptr;
  723. }
  724. const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance *h)
  725. {
  726. assert(h);
  727. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  728. if (pathInfo->hero != h)
  729. {
  730. gs->calculatePaths(h, *pathInfo.get());
  731. }
  732. return pathInfo.get();
  733. }
  734. int CClient::sendRequest(const CPack *request, PlayerColor player)
  735. {
  736. static ui32 requestCounter = 0;
  737. ui32 requestID = requestCounter++;
  738. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  739. % typeid(*request).name() % requestID;
  740. waitingRequest.pushBack(requestID);
  741. serv->sendPackToServer(*request, player, requestID);
  742. if(vstd::contains(playerint, player))
  743. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  744. return requestID;
  745. }
  746. void CClient::campaignMapFinished( std::shared_ptr<CCampaignState> camp )
  747. {
  748. endGame(false);
  749. GH.curInt = CGPreGame::create();
  750. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  751. auto finisher = [=]()
  752. {
  753. if(camp->mapsRemaining.size())
  754. proposeNextMission(camp);
  755. else
  756. finishCampaign(camp);
  757. };
  758. if(epilogue.hasPrologEpilog)
  759. {
  760. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  761. }
  762. else
  763. {
  764. finisher();
  765. }
  766. }
  767. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color)
  768. {
  769. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  770. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  771. if(!color)
  772. privilagedGameEventReceivers.push_back(gameInterface);
  773. playerint[colorUsed] = gameInterface;
  774. logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed;
  775. auto cb = std::make_shared<CCallback>(gs, color, this);
  776. callbacks[colorUsed] = cb;
  777. battleCallbacks[colorUsed] = cb;
  778. gameInterface->init(cb);
  779. installNewBattleInterface(gameInterface, color, false);
  780. }
  781. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback /*= true*/)
  782. {
  783. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  784. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  785. if(!color)
  786. privilagedBattleEventReceivers.push_back(battleInterface);
  787. battleints[colorUsed] = battleInterface;
  788. if(needCallback)
  789. {
  790. logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color;
  791. auto cbc = std::make_shared<CBattleCallback>(gs, color, this);
  792. battleCallbacks[colorUsed] = cbc;
  793. battleInterface->init(cbc);
  794. }
  795. }
  796. std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
  797. {
  798. if(ps.name.size())
  799. {
  800. const boost::filesystem::path aiPath =
  801. VCMIDirs::get().libraryPath() / "AI" / VCMIDirs::get().libraryName(ps.name);
  802. if (boost::filesystem::exists(aiPath))
  803. return ps.name;
  804. }
  805. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  806. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  807. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  808. //TODO what about human players
  809. if(battleints.size() >= sensibleAILimit)
  810. return badAI;
  811. return goodAI;
  812. }
  813. bool CServerHandler::DO_NOT_START_SERVER = false;
  814. void CServerHandler::startServer()
  815. {
  816. if(DO_NOT_START_SERVER)
  817. return;
  818. th.update();
  819. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  820. if(verbose)
  821. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  822. }
  823. void CServerHandler::waitForServer()
  824. {
  825. if(DO_NOT_START_SERVER)
  826. return;
  827. if(!serverThread)
  828. startServer();
  829. th.update();
  830. #ifndef VCMI_ANDROID
  831. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  832. while(!shared->sr->ready)
  833. {
  834. shared->sr->cond.wait(slock);
  835. }
  836. #endif
  837. if(verbose)
  838. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  839. }
  840. CConnection * CServerHandler::connectToServer()
  841. {
  842. #ifndef VCMI_ANDROID
  843. if(!shared->sr->ready)
  844. waitForServer();
  845. #else
  846. waitForServer();
  847. #endif
  848. th.update(); //put breakpoint here to attach to server before it does something stupid
  849. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  850. if(verbose)
  851. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  852. return ret;
  853. }
  854. CServerHandler::CServerHandler(bool runServer /*= false*/)
  855. {
  856. serverThread = nullptr;
  857. shared = nullptr;
  858. if(settings["testing"]["enabled"].Bool())
  859. port = settings["testing"]["port"].String();
  860. else
  861. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  862. verbose = true;
  863. #ifndef VCMI_ANDROID
  864. 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
  865. try
  866. {
  867. shared = new SharedMem();
  868. }
  869. catch(...)
  870. {
  871. logNetwork->error("Cannot open interprocess memory.");
  872. handleException();
  873. throw;
  874. }
  875. #endif
  876. }
  877. CServerHandler::~CServerHandler()
  878. {
  879. delete shared;
  880. delete serverThread; //detaches, not kills thread
  881. }
  882. void CServerHandler::callServer()
  883. {
  884. setThreadName("CServerHandler::callServer");
  885. const std::string logName = (VCMIDirs::get().userCachePath() / "server_log.txt").string();
  886. const std::string comm = VCMIDirs::get().serverPath().string() + " --port=" + port + " > \"" + logName + '\"';
  887. int result = std::system(comm.c_str());
  888. if (result == 0)
  889. logNetwork->infoStream() << "Server closed correctly";
  890. else
  891. {
  892. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  893. logNetwork->errorStream() << "Check " << logName << " for more info";
  894. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  895. }
  896. }
  897. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  898. {
  899. std::string realPort;
  900. if(settings["testing"]["enabled"].Bool())
  901. realPort = settings["testing"]["port"].String();
  902. else if(port.size())
  903. realPort = port;
  904. else
  905. realPort = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  906. CConnection *ret = nullptr;
  907. while(!ret)
  908. {
  909. try
  910. {
  911. logNetwork->infoStream() << "Establishing connection...";
  912. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  913. realPort,
  914. NAME);
  915. }
  916. catch(...)
  917. {
  918. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  919. SDL_Delay(2000);
  920. }
  921. }
  922. return ret;
  923. }