Client.cpp 33 KB

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