Client.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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 "CMusicHandler.h"
  13. #include "../lib/mapping/CCampaignHandler.h"
  14. #include "../CCallback.h"
  15. #include "adventureMap/CAdvMapInt.h"
  16. #include "adventureMap/mapHandler.h"
  17. #include "../lib/CConsoleHandler.h"
  18. #include "CGameInfo.h"
  19. #include "../lib/CGameState.h"
  20. #include "CPlayerInterface.h"
  21. #include "../lib/StartInfo.h"
  22. #include "../lib/battle/BattleInfo.h"
  23. #include "../lib/CModHandler.h"
  24. #include "../lib/CArtHandler.h"
  25. #include "../lib/CGeneralTextHandler.h"
  26. #include "../lib/CHeroHandler.h"
  27. #include "../lib/CTownHandler.h"
  28. #include "../lib/CBuildingHandler.h"
  29. #include "../lib/spells/CSpellHandler.h"
  30. #include "../lib/serializer/CTypeList.h"
  31. #include "../lib/serializer/Connection.h"
  32. #include "../lib/serializer/CLoadIntegrityValidator.h"
  33. #include "../lib/NetPacks.h"
  34. #include "ClientNetPackVisitors.h"
  35. #include "../lib/VCMI_Lib.h"
  36. #include "../lib/VCMIDirs.h"
  37. #include "../lib/mapping/CMap.h"
  38. #include "../lib/mapping/CMapService.h"
  39. #include "../lib/JsonNode.h"
  40. #include "../lib/CConfigHandler.h"
  41. #include "mainmenu/CMainMenu.h"
  42. #include "mainmenu/CCampaignScreen.h"
  43. #include "lobby/CBonusSelection.h"
  44. #include "battle/BattleInterface.h"
  45. #include "../lib/CThreadHelper.h"
  46. #include "../lib/registerTypes/RegisterTypes.h"
  47. #include "gui/CGuiHandler.h"
  48. #include "CServerHandler.h"
  49. #include "../lib/ScriptHandler.h"
  50. #include <vcmi/events/EventBus.h>
  51. #ifdef VCMI_ANDROID
  52. #include "lib/CAndroidVMHelper.h"
  53. #endif
  54. #ifdef VCMI_ANDROID
  55. std::atomic_bool androidTestServerReadyFlag;
  56. #endif
  57. ThreadSafeVector<int> CClient::waitingRequest;
  58. template<typename T> class CApplyOnCL;
  59. class CBaseForCLApply
  60. {
  61. public:
  62. virtual void applyOnClAfter(CClient * cl, void * pack) const =0;
  63. virtual void applyOnClBefore(CClient * cl, void * pack) const =0;
  64. virtual ~CBaseForCLApply(){}
  65. template<typename U> static CBaseForCLApply * getApplier(const U * t = nullptr)
  66. {
  67. return new CApplyOnCL<U>();
  68. }
  69. };
  70. template<typename T> class CApplyOnCL : public CBaseForCLApply
  71. {
  72. public:
  73. void applyOnClAfter(CClient * cl, void * pack) const override
  74. {
  75. T * ptr = static_cast<T *>(pack);
  76. ApplyClientNetPackVisitor visitor(*cl, *cl->gameState());
  77. ptr->visit(visitor);
  78. }
  79. void applyOnClBefore(CClient * cl, void * pack) const override
  80. {
  81. T * ptr = static_cast<T *>(pack);
  82. ApplyFirstClientNetPackVisitor visitor(*cl, *cl->gameState());
  83. ptr->visit(visitor);
  84. }
  85. };
  86. template<> class CApplyOnCL<CPack>: public CBaseForCLApply
  87. {
  88. public:
  89. void applyOnClAfter(CClient * cl, void * pack) const override
  90. {
  91. logGlobal->error("Cannot apply on CL plain CPack!");
  92. assert(0);
  93. }
  94. void applyOnClBefore(CClient * cl, void * pack) const override
  95. {
  96. logGlobal->error("Cannot apply on CL plain CPack!");
  97. assert(0);
  98. }
  99. };
  100. CPlayerEnvironment::CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_)
  101. : player(player_),
  102. cl(cl_),
  103. mainCallback(mainCallback_)
  104. {
  105. }
  106. const Services * CPlayerEnvironment::services() const
  107. {
  108. return VLC;
  109. }
  110. vstd::CLoggerBase * CPlayerEnvironment::logger() const
  111. {
  112. return logGlobal;
  113. }
  114. events::EventBus * CPlayerEnvironment::eventBus() const
  115. {
  116. return cl->eventBus();//always get actual value
  117. }
  118. const CPlayerEnvironment::BattleCb * CPlayerEnvironment::battle() const
  119. {
  120. return mainCallback.get();
  121. }
  122. const CPlayerEnvironment::GameCb * CPlayerEnvironment::game() const
  123. {
  124. return mainCallback.get();
  125. }
  126. CClient::CClient()
  127. {
  128. waitingRequest.clear();
  129. applier = std::make_shared<CApplier<CBaseForCLApply>>();
  130. registerTypesClientPacks1(*applier);
  131. registerTypesClientPacks2(*applier);
  132. IObjectInterface::cb = this;
  133. gs = nullptr;
  134. }
  135. CClient::~CClient()
  136. {
  137. IObjectInterface::cb = nullptr;
  138. }
  139. const Services * CClient::services() const
  140. {
  141. return VLC; //todo: this should be CGI
  142. }
  143. const CClient::BattleCb * CClient::battle() const
  144. {
  145. return this;
  146. }
  147. const CClient::GameCb * CClient::game() const
  148. {
  149. return this;
  150. }
  151. vstd::CLoggerBase * CClient::logger() const
  152. {
  153. return logGlobal;
  154. }
  155. events::EventBus * CClient::eventBus() const
  156. {
  157. return clientEventBus.get();
  158. }
  159. void CClient::newGame(CGameState * initializedGameState)
  160. {
  161. CSH->th->update();
  162. CMapService mapService;
  163. gs = initializedGameState ? initializedGameState : new CGameState();
  164. gs->preInit(VLC);
  165. logNetwork->trace("\tCreating gamestate: %i", CSH->th->getDiff());
  166. if(!initializedGameState)
  167. gs->init(&mapService, CSH->si.get(), settings["general"]["saveRandomMaps"].Bool());
  168. logNetwork->trace("Initializing GameState (together): %d ms", CSH->th->getDiff());
  169. initMapHandler();
  170. reinitScripting();
  171. initPlayerEnvironments();
  172. initPlayerInterfaces();
  173. }
  174. void CClient::loadGame(CGameState * initializedGameState)
  175. {
  176. logNetwork->info("Loading procedure started!");
  177. std::unique_ptr<CLoadFile> loader;
  178. if(initializedGameState)
  179. {
  180. logNetwork->info("Game state was transferred over network, loading.");
  181. gs = initializedGameState;
  182. }
  183. else
  184. {
  185. try
  186. {
  187. boost::filesystem::path clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(CSH->si->mapname, EResType::CLIENT_SAVEGAME));
  188. boost::filesystem::path controlServerSaveName;
  189. if(CResourceHandler::get("local")->existsResource(ResourceID(CSH->si->mapname, EResType::SERVER_SAVEGAME)))
  190. {
  191. controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(CSH->si->mapname, EResType::SERVER_SAVEGAME));
  192. }
  193. else // create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  194. {
  195. controlServerSaveName = boost::filesystem::path(clientSaveName).replace_extension(".vsgm1");
  196. CResourceHandler::get("local")->createResource(controlServerSaveName.string(), true);
  197. }
  198. if(clientSaveName.empty())
  199. throw std::runtime_error("Cannot open client part of " + CSH->si->mapname);
  200. if(controlServerSaveName.empty() || !boost::filesystem::exists(controlServerSaveName))
  201. throw std::runtime_error("Cannot open server part of " + CSH->si->mapname);
  202. {
  203. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName, MINIMAL_SERIALIZATION_VERSION);
  204. loadCommonState(checkingLoader);
  205. loader = checkingLoader.decay();
  206. }
  207. }
  208. catch(std::exception & e)
  209. {
  210. logGlobal->error("Cannot load game %s. Error: %s", CSH->si->mapname, e.what());
  211. throw; //obviously we cannot continue here
  212. }
  213. logNetwork->trace("Loaded common part of save %d ms", CSH->th->getDiff());
  214. }
  215. gs->preInit(VLC);
  216. gs->updateOnLoad(CSH->si.get());
  217. logNetwork->info("Game loaded, initialize interfaces.");
  218. initMapHandler();
  219. reinitScripting();
  220. initPlayerEnvironments();
  221. if(loader)
  222. serialize(loader->serializer, loader->serializer.fileVersion);
  223. initPlayerInterfaces();
  224. }
  225. void CClient::serialize(BinarySerializer & h, const int version)
  226. {
  227. assert(h.saving);
  228. ui8 players = static_cast<ui8>(playerint.size());
  229. h & players;
  230. for(auto i = playerint.begin(); i != playerint.end(); i++)
  231. {
  232. logGlobal->trace("Saving player %s interface", i->first);
  233. assert(i->first == i->second->playerID);
  234. h & i->first;
  235. h & i->second->dllName;
  236. h & i->second->human;
  237. i->second->saveGame(h, version);
  238. }
  239. #if SCRIPTING_ENABLED
  240. if(version >= 800)
  241. {
  242. JsonNode scriptsState;
  243. clientScripts->serializeState(h.saving, scriptsState);
  244. h & scriptsState;
  245. }
  246. #endif
  247. }
  248. void CClient::serialize(BinaryDeserializer & h, const int version)
  249. {
  250. assert(!h.saving);
  251. ui8 players = 0;
  252. h & players;
  253. for(int i = 0; i < players; i++)
  254. {
  255. std::string dllname;
  256. PlayerColor pid;
  257. bool isHuman = false;
  258. auto prevInt = LOCPLINT;
  259. h & pid;
  260. h & dllname;
  261. h & isHuman;
  262. assert(dllname.length() == 0 || !isHuman);
  263. if(pid == PlayerColor::NEUTRAL)
  264. {
  265. logGlobal->trace("Neutral battle interfaces are not serialized.");
  266. continue;
  267. }
  268. logGlobal->trace("Loading player %s interface", pid);
  269. std::shared_ptr<CGameInterface> nInt;
  270. if(dllname.length())
  271. nInt = CDynLibHandler::getNewAI(dllname);
  272. else
  273. nInt = std::make_shared<CPlayerInterface>(pid);
  274. nInt->dllName = dllname;
  275. nInt->human = isHuman;
  276. nInt->playerID = pid;
  277. nInt->loadGame(h, version);
  278. // Client no longer handle this player at all
  279. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), pid))
  280. {
  281. logGlobal->trace("Player %s is not belong to this client. Destroying interface", pid);
  282. }
  283. else if(isHuman && !vstd::contains(CSH->getHumanColors(), pid))
  284. {
  285. logGlobal->trace("Player %s is no longer controlled by human. Destroying interface", pid);
  286. }
  287. else if(!isHuman && vstd::contains(CSH->getHumanColors(), pid))
  288. {
  289. logGlobal->trace("Player %s is no longer controlled by AI. Destroying interface", pid);
  290. }
  291. else
  292. {
  293. installNewPlayerInterface(nInt, pid);
  294. continue;
  295. }
  296. nInt.reset();
  297. LOCPLINT = prevInt;
  298. }
  299. #if SCRIPTING_ENABLED
  300. {
  301. JsonNode scriptsState;
  302. h & scriptsState;
  303. clientScripts->serializeState(h.saving, scriptsState);
  304. }
  305. #endif
  306. logNetwork->trace("Loaded client part of save %d ms", CSH->th->getDiff());
  307. }
  308. void CClient::save(const std::string & fname)
  309. {
  310. if(gs->curB)
  311. {
  312. logNetwork->error("Game cannot be saved during battle!");
  313. return;
  314. }
  315. SaveGame save_game(fname);
  316. sendRequest(&save_game, PlayerColor::NEUTRAL);
  317. }
  318. void CClient::endGame()
  319. {
  320. #if SCRIPTING_ENABLED
  321. clientScripts.reset();
  322. #endif
  323. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  324. for(auto & i : playerint)
  325. i.second->finish();
  326. GH.curInt = nullptr;
  327. {
  328. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  329. logNetwork->info("Ending current game!");
  330. removeGUI();
  331. vstd::clear_pointer(const_cast<CGameInfo *>(CGI)->mh);
  332. vstd::clear_pointer(gs);
  333. logNetwork->info("Deleted mapHandler and gameState.");
  334. }
  335. playerint.clear();
  336. battleints.clear();
  337. battleCallbacks.clear();
  338. playerEnvironments.clear();
  339. logNetwork->info("Deleted playerInts.");
  340. logNetwork->info("Client stopped.");
  341. }
  342. void CClient::initMapHandler()
  343. {
  344. // TODO: CMapHandler initialization can probably go somewhere else
  345. // It's can't be before initialization of interfaces
  346. // During loading CPlayerInterface from serialized state it's depend on MH
  347. if(!settings["session"]["headless"].Bool())
  348. {
  349. const_cast<CGameInfo *>(CGI)->mh = new CMapHandler();
  350. CGI->mh->map = gs->map;
  351. logNetwork->trace("Creating mapHandler: %d ms", CSH->th->getDiff());
  352. CGI->mh->init();
  353. logNetwork->trace("Initializing mapHandler (together): %d ms", CSH->th->getDiff());
  354. }
  355. pathCache.clear();
  356. }
  357. void CClient::initPlayerEnvironments()
  358. {
  359. playerEnvironments.clear();
  360. auto allPlayers = CSH->getAllClientPlayers(CSH->c->connectionID);
  361. for(auto & color : allPlayers)
  362. {
  363. logNetwork->info("Preparing environment for player %s", color.getStr());
  364. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gs, color, this));
  365. }
  366. if(settings["session"]["spectate"].Bool())
  367. {
  368. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, boost::none, this));
  369. }
  370. }
  371. void CClient::initPlayerInterfaces()
  372. {
  373. for(auto & elem : gs->scenarioOps->playerInfos)
  374. {
  375. PlayerColor color = elem.first;
  376. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), color))
  377. continue;
  378. if(!vstd::contains(playerint, color))
  379. {
  380. logNetwork->info("Preparing interface for player %s", color.getStr());
  381. if(elem.second.isControlledByAI())
  382. {
  383. auto AiToGive = aiNameForPlayer(elem.second, false);
  384. logNetwork->info("Player %s will be lead by %s", color.getStr(), AiToGive);
  385. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  386. }
  387. else
  388. {
  389. logNetwork->info("Player %s will be lead by human", color.getStr());
  390. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  391. }
  392. }
  393. }
  394. if(settings["session"]["spectate"].Bool())
  395. {
  396. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  397. }
  398. if(CSH->getAllClientPlayers(CSH->c->connectionID).count(PlayerColor::NEUTRAL))
  399. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  400. logNetwork->trace("Initialized player interfaces %d ms", CSH->th->getDiff());
  401. }
  402. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI)
  403. {
  404. if(ps.name.size())
  405. {
  406. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  407. if(boost::filesystem::exists(aiPath))
  408. return ps.name;
  409. }
  410. return aiNameForPlayer(battleAI);
  411. }
  412. std::string CClient::aiNameForPlayer(bool battleAI)
  413. {
  414. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  415. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  416. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  417. //TODO what about human players
  418. if(battleints.size() >= sensibleAILimit)
  419. return badAI;
  420. return goodAI;
  421. }
  422. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb)
  423. {
  424. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  425. playerint[color] = gameInterface;
  426. logGlobal->trace("\tInitializing the interface for player %s", color.getStr());
  427. auto cb = std::make_shared<CCallback>(gs, color, this);
  428. battleCallbacks[color] = cb;
  429. gameInterface->initGameInterface(playerEnvironments.at(color), cb);
  430. installNewBattleInterface(gameInterface, color, battlecb);
  431. }
  432. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback)
  433. {
  434. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  435. battleints[color] = battleInterface;
  436. if(needCallback)
  437. {
  438. logGlobal->trace("\tInitializing the battle interface for player %s", color.getStr());
  439. auto cbc = std::make_shared<CBattleCallback>(color, this);
  440. battleCallbacks[color] = cbc;
  441. battleInterface->initBattleInterface(playerEnvironments.at(color), cbc);
  442. }
  443. }
  444. void CClient::handlePack(CPack * pack)
  445. {
  446. CBaseForCLApply * apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  447. if(apply)
  448. {
  449. boost::unique_lock<boost::recursive_mutex> guiLock(*CPlayerInterface::pim);
  450. apply->applyOnClBefore(this, pack);
  451. logNetwork->trace("\tMade first apply on cl: %s", typeList.getTypeInfo(pack)->name());
  452. gs->apply(pack);
  453. logNetwork->trace("\tApplied on gs: %s", typeList.getTypeInfo(pack)->name());
  454. apply->applyOnClAfter(this, pack);
  455. logNetwork->trace("\tMade second apply on cl: %s", typeList.getTypeInfo(pack)->name());
  456. }
  457. else
  458. {
  459. logNetwork->error("Message %s cannot be applied, cannot find applier!", typeList.getTypeInfo(pack)->name());
  460. }
  461. delete pack;
  462. }
  463. int CClient::sendRequest(const CPackForServer * request, PlayerColor player)
  464. {
  465. static ui32 requestCounter = 0;
  466. ui32 requestID = requestCounter++;
  467. logNetwork->trace("Sending a request \"%s\". It'll have an ID=%d.", typeid(*request).name(), requestID);
  468. waitingRequest.pushBack(requestID);
  469. request->requestID = requestID;
  470. request->player = player;
  471. CSH->c->sendPack(request);
  472. if(vstd::contains(playerint, player))
  473. playerint[player]->requestSent(request, requestID);
  474. return requestID;
  475. }
  476. void CClient::battleStarted(const BattleInfo * info)
  477. {
  478. setBattle(info);
  479. for(auto & battleCb : battleCallbacks)
  480. {
  481. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  482. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  483. {
  484. battleCb.second->setBattle(info);
  485. }
  486. }
  487. std::shared_ptr<CPlayerInterface> att, def;
  488. auto & leftSide = info->sides[0], & rightSide = info->sides[1];
  489. //If quick combat is not, do not prepare interfaces for battleint
  490. if(!settings["adventure"]["quickCombat"].Bool())
  491. {
  492. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  493. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  494. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  495. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  496. }
  497. if(!settings["session"]["headless"].Bool())
  498. {
  499. if(!!att || !!def)
  500. {
  501. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  502. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def);
  503. }
  504. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  505. {
  506. //TODO: This certainly need improvement
  507. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  508. spectratorInt->cb->setBattle(info);
  509. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  510. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def, spectratorInt);
  511. }
  512. }
  513. auto callBattleStart = [&](PlayerColor color, ui8 side)
  514. {
  515. if(vstd::contains(battleints, color))
  516. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  517. };
  518. callBattleStart(leftSide.color, 0);
  519. callBattleStart(rightSide.color, 1);
  520. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  521. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  522. callBattleStart(PlayerColor::SPECTATOR, 1);
  523. if(info->tacticDistance && vstd::contains(battleints, info->sides[info->tacticsSide].color))
  524. {
  525. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
  526. }
  527. }
  528. void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
  529. {
  530. setThreadName("CClient::commenceTacticPhaseForInt");
  531. try
  532. {
  533. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  534. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  535. {
  536. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID).get()));
  537. sendRequest(&ma, battleInt->playerID);
  538. }
  539. }
  540. catch(...)
  541. {
  542. handleException();
  543. }
  544. }
  545. void CClient::battleFinished()
  546. {
  547. stopAllBattleActions();
  548. for(auto & side : gs->curB->sides)
  549. if(battleCallbacks.count(side.color))
  550. battleCallbacks[side.color]->setBattle(nullptr);
  551. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  552. battleCallbacks[PlayerColor::SPECTATOR]->setBattle(nullptr);
  553. setBattle(nullptr);
  554. }
  555. void CClient::startPlayerBattleAction(PlayerColor color)
  556. {
  557. stopPlayerBattleAction(color);
  558. if(vstd::contains(battleints, color))
  559. {
  560. auto thread = std::make_shared<boost::thread>(std::bind(&CClient::waitForMoveAndSend, this, color));
  561. playerActionThreads[color] = thread;
  562. }
  563. }
  564. void CClient::stopPlayerBattleAction(PlayerColor color)
  565. {
  566. if(vstd::contains(playerActionThreads, color))
  567. {
  568. auto thread = playerActionThreads.at(color);
  569. if(thread->joinable())
  570. {
  571. thread->interrupt();
  572. thread->join();
  573. }
  574. playerActionThreads.erase(color);
  575. }
  576. }
  577. void CClient::stopAllBattleActions()
  578. {
  579. while(!playerActionThreads.empty())
  580. stopPlayerBattleAction(playerActionThreads.begin()->first);
  581. }
  582. void CClient::waitForMoveAndSend(PlayerColor color)
  583. {
  584. try
  585. {
  586. setThreadName("CClient::waitForMoveAndSend");
  587. assert(vstd::contains(battleints, color));
  588. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  589. if(ba.actionType != EActionType::CANCEL)
  590. {
  591. logNetwork->trace("Send battle action to server: %s", ba.toString());
  592. MakeAction temp_action(ba);
  593. sendRequest(&temp_action, color);
  594. }
  595. }
  596. catch(boost::thread_interrupted &)
  597. {
  598. logNetwork->debug("Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?");
  599. }
  600. catch(...)
  601. {
  602. handleException();
  603. }
  604. }
  605. void CClient::invalidatePaths()
  606. {
  607. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  608. pathCache.clear();
  609. }
  610. std::shared_ptr<const CPathsInfo> CClient::getPathsInfo(const CGHeroInstance * h)
  611. {
  612. assert(h);
  613. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  614. auto iter = pathCache.find(h);
  615. if(iter == std::end(pathCache))
  616. {
  617. std::shared_ptr<CPathsInfo> paths = std::make_shared<CPathsInfo>(getMapSize(), h);
  618. gs->calculatePaths(h, *paths.get());
  619. pathCache[h] = paths;
  620. return paths;
  621. }
  622. else
  623. {
  624. return iter->second;
  625. }
  626. }
  627. PlayerColor CClient::getLocalPlayer() const
  628. {
  629. if(LOCPLINT)
  630. return LOCPLINT->playerID;
  631. return getCurrentPlayer();
  632. }
  633. #if SCRIPTING_ENABLED
  634. scripting::Pool * CClient::getGlobalContextPool() const
  635. {
  636. return clientScripts.get();
  637. }
  638. scripting::Pool * CClient::getContextPool() const
  639. {
  640. return clientScripts.get();
  641. }
  642. #endif
  643. void CClient::reinitScripting()
  644. {
  645. clientEventBus = std::make_unique<events::EventBus>();
  646. #if SCRIPTING_ENABLED
  647. clientScripts.reset(new scripting::PoolImpl(this));
  648. #endif
  649. }
  650. void CClient::removeGUI()
  651. {
  652. // CClient::endGame
  653. GH.curInt = nullptr;
  654. if(GH.topInt())
  655. GH.topInt()->deactivate();
  656. adventureInt.reset();
  657. GH.listInt.clear();
  658. GH.objsToBlit.clear();
  659. GH.statusbar.reset();
  660. logGlobal->info("Removed GUI.");
  661. LOCPLINT = nullptr;
  662. }
  663. #ifdef VCMI_ANDROID
  664. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerClosed(JNIEnv * env, jclass cls)
  665. {
  666. logNetwork->info("Received server closed signal");
  667. if (CSH) {
  668. CSH->campaignServerRestartLock.setn(false);
  669. }
  670. }
  671. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerReady(JNIEnv * env, jclass cls)
  672. {
  673. logNetwork->info("Received server ready signal");
  674. androidTestServerReadyFlag.store(true);
  675. }
  676. extern "C" JNIEXPORT jboolean JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jclass cls)
  677. {
  678. logGlobal->info("Received emergency save game request");
  679. if(!LOCPLINT || !LOCPLINT->cb)
  680. {
  681. return false;
  682. }
  683. LOCPLINT->cb->save("Saves/_Android_Autosave");
  684. return true;
  685. }
  686. #endif