Client.cpp 32 KB

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