Client.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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 "Global.h"
  11. #include "StdInc.h"
  12. #include "Client.h"
  13. #include "CGameInfo.h"
  14. #include "CPlayerInterface.h"
  15. #include "CServerHandler.h"
  16. #include "ClientNetPackVisitors.h"
  17. #include "adventureMap/AdventureMapInterface.h"
  18. #include "battle/BattleInterface.h"
  19. #include "gui/CGuiHandler.h"
  20. #include "gui/WindowHandler.h"
  21. #include "mapView/mapHandler.h"
  22. #include "../CCallback.h"
  23. #include "../lib/CConfigHandler.h"
  24. #include "../lib/gameState/CGameState.h"
  25. #include "../lib/CPlayerState.h"
  26. #include "../lib/CThreadHelper.h"
  27. #include "../lib/VCMIDirs.h"
  28. #include "../lib/UnlockGuard.h"
  29. #include "../lib/battle/BattleInfo.h"
  30. #include "../lib/serializer/BinaryDeserializer.h"
  31. #include "../lib/mapping/CMapService.h"
  32. #include "../lib/pathfinder/CGPathNode.h"
  33. #include "../lib/filesystem/Filesystem.h"
  34. #include "../lib/registerTypes/RegisterTypesClientPacks.h"
  35. #include "../lib/serializer/Connection.h"
  36. #include <memory>
  37. #include <vcmi/events/EventBus.h>
  38. #if SCRIPTING_ENABLED
  39. #include "../lib/ScriptHandler.h"
  40. #endif
  41. #ifdef VCMI_ANDROID
  42. #include "lib/CAndroidVMHelper.h"
  43. #ifndef SINGLE_PROCESS_APP
  44. std::atomic_bool androidTestServerReadyFlag;
  45. #endif
  46. #endif
  47. ThreadSafeVector<int> CClient::waitingRequest;
  48. template<typename T> class CApplyOnCL;
  49. class CBaseForCLApply
  50. {
  51. public:
  52. virtual void applyOnClAfter(CClient * cl, void * pack) const =0;
  53. virtual void applyOnClBefore(CClient * cl, void * pack) const =0;
  54. virtual ~CBaseForCLApply(){}
  55. template<typename U> static CBaseForCLApply * getApplier(const U * t = nullptr)
  56. {
  57. return new CApplyOnCL<U>();
  58. }
  59. };
  60. template<typename T> class CApplyOnCL : public CBaseForCLApply
  61. {
  62. public:
  63. void applyOnClAfter(CClient * cl, void * pack) const override
  64. {
  65. T * ptr = static_cast<T *>(pack);
  66. ApplyClientNetPackVisitor visitor(*cl, *cl->gameState());
  67. ptr->visit(visitor);
  68. }
  69. void applyOnClBefore(CClient * cl, void * pack) const override
  70. {
  71. T * ptr = static_cast<T *>(pack);
  72. ApplyFirstClientNetPackVisitor visitor(*cl, *cl->gameState());
  73. ptr->visit(visitor);
  74. }
  75. };
  76. template<> class CApplyOnCL<CPack>: public CBaseForCLApply
  77. {
  78. public:
  79. void applyOnClAfter(CClient * cl, void * pack) const override
  80. {
  81. logGlobal->error("Cannot apply on CL plain CPack!");
  82. assert(0);
  83. }
  84. void applyOnClBefore(CClient * cl, void * pack) const override
  85. {
  86. logGlobal->error("Cannot apply on CL plain CPack!");
  87. assert(0);
  88. }
  89. };
  90. CPlayerEnvironment::CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_)
  91. : player(player_),
  92. cl(cl_),
  93. mainCallback(mainCallback_)
  94. {
  95. }
  96. const Services * CPlayerEnvironment::services() const
  97. {
  98. return VLC;
  99. }
  100. vstd::CLoggerBase * CPlayerEnvironment::logger() const
  101. {
  102. return logGlobal;
  103. }
  104. events::EventBus * CPlayerEnvironment::eventBus() const
  105. {
  106. return cl->eventBus();//always get actual value
  107. }
  108. const CPlayerEnvironment::BattleCb * CPlayerEnvironment::battle(const BattleID & battleID) const
  109. {
  110. return mainCallback->getBattle(battleID).get();
  111. }
  112. const CPlayerEnvironment::GameCb * CPlayerEnvironment::game() const
  113. {
  114. return mainCallback.get();
  115. }
  116. CClient::CClient()
  117. {
  118. waitingRequest.clear();
  119. applier = std::make_shared<CApplier<CBaseForCLApply>>();
  120. registerTypesClientPacks(*applier);
  121. gs = nullptr;
  122. }
  123. CClient::~CClient() = default;
  124. const Services * CClient::services() const
  125. {
  126. return VLC; //todo: this should be CGI
  127. }
  128. const CClient::BattleCb * CClient::battle(const BattleID & battleID) const
  129. {
  130. return nullptr; //todo?
  131. }
  132. const CClient::GameCb * CClient::game() const
  133. {
  134. return this;
  135. }
  136. vstd::CLoggerBase * CClient::logger() const
  137. {
  138. return logGlobal;
  139. }
  140. events::EventBus * CClient::eventBus() const
  141. {
  142. return clientEventBus.get();
  143. }
  144. void CClient::newGame(CGameState * initializedGameState)
  145. {
  146. CSH->th->update();
  147. CMapService mapService;
  148. assert(initializedGameState);
  149. gs = initializedGameState;
  150. gs->preInit(VLC, this);
  151. logNetwork->trace("\tCreating gamestate: %i", CSH->th->getDiff());
  152. if(!initializedGameState)
  153. {
  154. Load::ProgressAccumulator progressTracking;
  155. gs->init(&mapService, CSH->si.get(), progressTracking, settings["general"]["saveRandomMaps"].Bool());
  156. }
  157. logNetwork->trace("Initializing GameState (together): %d ms", CSH->th->getDiff());
  158. initMapHandler();
  159. reinitScripting();
  160. initPlayerEnvironments();
  161. initPlayerInterfaces();
  162. }
  163. void CClient::loadGame(CGameState * initializedGameState)
  164. {
  165. logNetwork->info("Loading procedure started!");
  166. logNetwork->info("Game state was transferred over network, loading.");
  167. gs = initializedGameState;
  168. gs->preInit(VLC, this);
  169. gs->updateOnLoad(CSH->si.get());
  170. logNetwork->info("Game loaded, initialize interfaces.");
  171. initMapHandler();
  172. reinitScripting();
  173. initPlayerEnvironments();
  174. // Loading of client state - disabled for now
  175. // Since client no longer writes or loads its own state and instead receives it from server
  176. // client state serializer will serialize its own copies of all pointers, e.g. heroes/towns/objects
  177. // and on deserialize will create its own copies (instead of using copies from state received from server)
  178. // Potential solutions:
  179. // 1) Use server gamestate to deserialize pointers, so any pointer to same object will point to server instance and not our copy
  180. // 2) Remove all serialization of pointers with instance ID's and restore them on load (including AI deserializer code)
  181. // 3) Completely remove client savegame and send all information, like hero paths and sleeping status to server (either in form of hero properties or as some generic "client options" message
  182. #ifdef BROKEN_CLIENT_STATE_SERIALIZATION_HAS_BEEN_FIXED
  183. // try to deserialize client data including sleepingHeroes
  184. try
  185. {
  186. boost::filesystem::path clientSaveName = *CResourceHandler::get()->getResourceName(ResourcePath(CSH->si->mapname, EResType::CLIENT_SAVEGAME));
  187. if(clientSaveName.empty())
  188. throw std::runtime_error("Cannot open client part of " + CSH->si->mapname);
  189. std::unique_ptr<CLoadFile> loader (new CLoadFile(clientSaveName));
  190. serialize(loader->serializer, loader->serializer.fileVersion);
  191. logNetwork->info("Client data loaded.");
  192. }
  193. catch(std::exception & e)
  194. {
  195. logGlobal->info("Cannot load client data for game %s. Error: %s", CSH->si->mapname, e.what());
  196. }
  197. #endif
  198. initPlayerInterfaces();
  199. }
  200. void CClient::serialize(BinarySerializer & h, const int version)
  201. {
  202. assert(h.saving);
  203. ui8 players = static_cast<ui8>(playerint.size());
  204. h & players;
  205. for(auto i = playerint.begin(); i != playerint.end(); i++)
  206. {
  207. logGlobal->trace("Saving player %s interface", i->first);
  208. assert(i->first == i->second->playerID);
  209. h & i->first;
  210. h & i->second->dllName;
  211. h & i->second->human;
  212. i->second->saveGame(h, version);
  213. }
  214. #if SCRIPTING_ENABLED
  215. if(version >= 800)
  216. {
  217. JsonNode scriptsState;
  218. clientScripts->serializeState(h.saving, scriptsState);
  219. h & scriptsState;
  220. }
  221. #endif
  222. }
  223. void CClient::serialize(BinaryDeserializer & h, const int version)
  224. {
  225. assert(!h.saving);
  226. ui8 players = 0;
  227. h & players;
  228. for(int i = 0; i < players; i++)
  229. {
  230. std::string dllname;
  231. PlayerColor pid;
  232. bool isHuman = false;
  233. auto prevInt = LOCPLINT;
  234. h & pid;
  235. h & dllname;
  236. h & isHuman;
  237. assert(dllname.length() == 0 || !isHuman);
  238. if(pid == PlayerColor::NEUTRAL)
  239. {
  240. logGlobal->trace("Neutral battle interfaces are not serialized.");
  241. continue;
  242. }
  243. logGlobal->trace("Loading player %s interface", pid);
  244. std::shared_ptr<CGameInterface> nInt;
  245. if(dllname.length())
  246. nInt = CDynLibHandler::getNewAI(dllname);
  247. else
  248. nInt = std::make_shared<CPlayerInterface>(pid);
  249. nInt->dllName = dllname;
  250. nInt->human = isHuman;
  251. nInt->playerID = pid;
  252. bool shouldResetInterface = true;
  253. // Client no longer handle this player at all
  254. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), pid))
  255. {
  256. logGlobal->trace("Player %s is not belong to this client. Destroying interface", pid);
  257. }
  258. else if(isHuman && !vstd::contains(CSH->getHumanColors(), pid))
  259. {
  260. logGlobal->trace("Player %s is no longer controlled by human. Destroying interface", pid);
  261. }
  262. else if(!isHuman && vstd::contains(CSH->getHumanColors(), pid))
  263. {
  264. logGlobal->trace("Player %s is no longer controlled by AI. Destroying interface", pid);
  265. }
  266. else
  267. {
  268. installNewPlayerInterface(nInt, pid);
  269. shouldResetInterface = false;
  270. }
  271. // loadGame needs to be called after initGameInterface to load paths correctly
  272. // initGameInterface is called in installNewPlayerInterface
  273. nInt->loadGame(h, version);
  274. if (shouldResetInterface)
  275. {
  276. nInt.reset();
  277. LOCPLINT = prevInt;
  278. }
  279. }
  280. #if SCRIPTING_ENABLED
  281. {
  282. JsonNode scriptsState;
  283. h & scriptsState;
  284. clientScripts->serializeState(h.saving, scriptsState);
  285. }
  286. #endif
  287. logNetwork->trace("Loaded client part of save %d ms", CSH->th->getDiff());
  288. }
  289. void CClient::save(const std::string & fname)
  290. {
  291. if(!gs->currentBattles.empty())
  292. {
  293. logNetwork->error("Game cannot be saved during battle!");
  294. return;
  295. }
  296. SaveGame save_game(fname);
  297. sendRequest(&save_game, PlayerColor::NEUTRAL);
  298. }
  299. void CClient::endGame()
  300. {
  301. #if SCRIPTING_ENABLED
  302. clientScripts.reset();
  303. #endif
  304. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  305. for(auto & i : playerint)
  306. i.second->finish();
  307. GH.curInt = nullptr;
  308. {
  309. logNetwork->info("Ending current game!");
  310. removeGUI();
  311. CGI->mh.reset();
  312. vstd::clear_pointer(gs);
  313. logNetwork->info("Deleted mapHandler and gameState.");
  314. }
  315. CPlayerInterface::battleInt.reset();
  316. playerint.clear();
  317. battleints.clear();
  318. battleCallbacks.clear();
  319. playerEnvironments.clear();
  320. logNetwork->info("Deleted playerInts.");
  321. logNetwork->info("Client stopped.");
  322. }
  323. void CClient::initMapHandler()
  324. {
  325. // TODO: CMapHandler initialization can probably go somewhere else
  326. // It's can't be before initialization of interfaces
  327. // During loading CPlayerInterface from serialized state it's depend on MH
  328. if(!settings["session"]["headless"].Bool())
  329. {
  330. CGI->mh = std::make_shared<CMapHandler>(gs->map);
  331. logNetwork->trace("Creating mapHandler: %d ms", CSH->th->getDiff());
  332. }
  333. pathCache.clear();
  334. }
  335. void CClient::initPlayerEnvironments()
  336. {
  337. playerEnvironments.clear();
  338. auto allPlayers = CSH->getAllClientPlayers(CSH->c->connectionID);
  339. bool hasHumanPlayer = false;
  340. for(auto & color : allPlayers)
  341. {
  342. logNetwork->info("Preparing environment for player %s", color.toString());
  343. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gs, color, this));
  344. if(!hasHumanPlayer && gs->players[color].isHuman())
  345. hasHumanPlayer = true;
  346. }
  347. if(!hasHumanPlayer)
  348. {
  349. Settings session = settings.write["session"];
  350. session["spectate"].Bool() = true;
  351. session["spectate-skip-battle-result"].Bool() = true;
  352. session["spectate-ignore-hero"].Bool() = true;
  353. }
  354. if(settings["session"]["spectate"].Bool())
  355. {
  356. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, std::nullopt, this));
  357. }
  358. }
  359. void CClient::initPlayerInterfaces()
  360. {
  361. for(auto & playerInfo : gs->scenarioOps->playerInfos)
  362. {
  363. PlayerColor color = playerInfo.first;
  364. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), color))
  365. continue;
  366. if(!vstd::contains(playerint, color))
  367. {
  368. logNetwork->info("Preparing interface for player %s", color.toString());
  369. if(playerInfo.second.isControlledByAI())
  370. {
  371. bool alliedToHuman = false;
  372. for(auto & allyInfo : gs->scenarioOps->playerInfos)
  373. if (gs->getPlayerTeam(allyInfo.first) == gs->getPlayerTeam(playerInfo.first) && allyInfo.second.isControlledByHuman())
  374. alliedToHuman = true;
  375. auto AiToGive = aiNameForPlayer(playerInfo.second, false, alliedToHuman);
  376. logNetwork->info("Player %s will be lead by %s", color.toString(), AiToGive);
  377. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  378. }
  379. else
  380. {
  381. logNetwork->info("Player %s will be lead by human", color.toString());
  382. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  383. }
  384. }
  385. }
  386. if(settings["session"]["spectate"].Bool())
  387. {
  388. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  389. }
  390. if(CSH->getAllClientPlayers(CSH->c->connectionID).count(PlayerColor::NEUTRAL))
  391. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  392. logNetwork->trace("Initialized player interfaces %d ms", CSH->th->getDiff());
  393. }
  394. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI, bool alliedToHuman)
  395. {
  396. if(ps.name.size())
  397. {
  398. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  399. if(boost::filesystem::exists(aiPath))
  400. return ps.name;
  401. }
  402. return aiNameForPlayer(battleAI, alliedToHuman);
  403. }
  404. std::string CClient::aiNameForPlayer(bool battleAI, bool alliedToHuman)
  405. {
  406. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  407. std::string goodAdventureAI = alliedToHuman ? settings["server"]["alliedAI"].String() : settings["server"]["playerAI"].String();
  408. std::string goodBattleAI = settings["server"]["neutralAI"].String();
  409. std::string goodAI = battleAI ? goodBattleAI : goodAdventureAI;
  410. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  411. //TODO what about human players
  412. if(battleints.size() >= sensibleAILimit)
  413. return badAI;
  414. return goodAI;
  415. }
  416. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb)
  417. {
  418. playerint[color] = gameInterface;
  419. logGlobal->trace("\tInitializing the interface for player %s", color.toString());
  420. auto cb = std::make_shared<CCallback>(gs, color, this);
  421. battleCallbacks[color] = cb;
  422. gameInterface->initGameInterface(playerEnvironments.at(color), cb);
  423. installNewBattleInterface(gameInterface, color, battlecb);
  424. }
  425. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback)
  426. {
  427. battleints[color] = battleInterface;
  428. if(needCallback)
  429. {
  430. logGlobal->trace("\tInitializing the battle interface for player %s", color.toString());
  431. auto cbc = std::make_shared<CBattleCallback>(color, this);
  432. battleCallbacks[color] = cbc;
  433. battleInterface->initBattleInterface(playerEnvironments.at(color), cbc);
  434. }
  435. }
  436. void CClient::handlePack(CPack * pack)
  437. {
  438. CBaseForCLApply * apply = applier->getApplier(CTypeList::getInstance().getTypeID(pack)); //find the applier
  439. if(apply)
  440. {
  441. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  442. apply->applyOnClBefore(this, pack);
  443. logNetwork->trace("\tMade first apply on cl: %s", typeid(pack).name());
  444. gs->apply(pack);
  445. logNetwork->trace("\tApplied on gs: %s", typeid(pack).name());
  446. apply->applyOnClAfter(this, pack);
  447. logNetwork->trace("\tMade second apply on cl: %s", typeid(pack).name());
  448. }
  449. else
  450. {
  451. logNetwork->error("Message %s cannot be applied, cannot find applier!", typeid(pack).name());
  452. }
  453. delete pack;
  454. }
  455. int CClient::sendRequest(const CPackForServer * request, PlayerColor player)
  456. {
  457. static ui32 requestCounter = 0;
  458. ui32 requestID = requestCounter++;
  459. logNetwork->trace("Sending a request \"%s\". It'll have an ID=%d.", typeid(*request).name(), requestID);
  460. waitingRequest.pushBack(requestID);
  461. request->requestID = requestID;
  462. request->player = player;
  463. CSH->c->sendPack(request);
  464. if(vstd::contains(playerint, player))
  465. playerint[player]->requestSent(request, requestID);
  466. return requestID;
  467. }
  468. void CClient::battleStarted(const BattleInfo * info)
  469. {
  470. std::shared_ptr<CPlayerInterface> att;
  471. std::shared_ptr<CPlayerInterface> def;
  472. auto & leftSide = info->sides[0];
  473. auto & rightSide = info->sides[1];
  474. for(auto & battleCb : battleCallbacks)
  475. {
  476. if(!battleCb.first.isValidPlayer() || battleCb.first == leftSide.color || battleCb.first == rightSide.color)
  477. battleCb.second->onBattleStarted(info);
  478. }
  479. //If quick combat is not, do not prepare interfaces for battleint
  480. auto callBattleStart = [&](PlayerColor color, ui8 side)
  481. {
  482. if(vstd::contains(battleints, color))
  483. battleints[color]->battleStart(info->battleID, leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side, info->replayAllowed);
  484. };
  485. callBattleStart(leftSide.color, 0);
  486. callBattleStart(rightSide.color, 1);
  487. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  488. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  489. callBattleStart(PlayerColor::SPECTATOR, 1);
  490. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  491. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  492. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  493. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  494. //Remove player interfaces for auto battle (quickCombat option)
  495. if(att && att->isAutoFightOn)
  496. {
  497. if (att->cb->getBattle(info->battleID)->battleGetTacticDist())
  498. {
  499. auto side = att->cb->getBattle(info->battleID)->playerToSide(att->playerID);
  500. auto action = BattleAction::makeEndOFTacticPhase(*side);
  501. att->cb->battleMakeTacticAction(info->battleID, action);
  502. }
  503. att.reset();
  504. def.reset();
  505. }
  506. if(!settings["session"]["headless"].Bool())
  507. {
  508. if(att || def)
  509. {
  510. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(info->getBattleID(), leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def);
  511. }
  512. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  513. {
  514. //TODO: This certainly need improvement
  515. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  516. spectratorInt->cb->onBattleStarted(info);
  517. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(info->getBattleID(), leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def, spectratorInt);
  518. }
  519. }
  520. if(info->tacticDistance)
  521. {
  522. auto tacticianColor = info->sides[info->tacticsSide].color;
  523. if (vstd::contains(battleints, tacticianColor))
  524. battleints[tacticianColor]->yourTacticPhase(info->battleID, info->tacticDistance);
  525. }
  526. }
  527. void CClient::battleFinished(const BattleID & battleID)
  528. {
  529. for(auto & side : gs->getBattle(battleID)->sides)
  530. if(battleCallbacks.count(side.color))
  531. battleCallbacks[side.color]->onBattleEnded(battleID);
  532. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  533. battleCallbacks[PlayerColor::SPECTATOR]->onBattleEnded(battleID);
  534. }
  535. void CClient::startPlayerBattleAction(const BattleID & battleID, PlayerColor color)
  536. {
  537. if (battleints.count(color) == 0)
  538. return; // not our combat in MP
  539. auto battleint = battleints.at(color);
  540. if (!battleint->human)
  541. {
  542. // we want to avoid locking gamestate and causing UI to freeze while AI is making turn
  543. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  544. battleint->activeStack(battleID, gs->getBattle(battleID)->battleGetStackByID(gs->getBattle(battleID)->activeStack, false));
  545. }
  546. else
  547. {
  548. battleint->activeStack(battleID, gs->getBattle(battleID)->battleGetStackByID(gs->getBattle(battleID)->activeStack, false));
  549. }
  550. }
  551. void CClient::invalidatePaths()
  552. {
  553. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  554. pathCache.clear();
  555. }
  556. std::shared_ptr<const CPathsInfo> CClient::getPathsInfo(const CGHeroInstance * h)
  557. {
  558. assert(h);
  559. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  560. auto iter = pathCache.find(h);
  561. if(iter == std::end(pathCache))
  562. {
  563. auto paths = std::make_shared<CPathsInfo>(getMapSize(), h);
  564. gs->calculatePaths(h, *paths.get());
  565. pathCache[h] = paths;
  566. return paths;
  567. }
  568. else
  569. {
  570. return iter->second;
  571. }
  572. }
  573. #if SCRIPTING_ENABLED
  574. scripting::Pool * CClient::getGlobalContextPool() const
  575. {
  576. return clientScripts.get();
  577. }
  578. #endif
  579. void CClient::reinitScripting()
  580. {
  581. clientEventBus = std::make_unique<events::EventBus>();
  582. #if SCRIPTING_ENABLED
  583. clientScripts.reset(new scripting::PoolImpl(this));
  584. #endif
  585. }
  586. void CClient::removeGUI() const
  587. {
  588. // CClient::endGame
  589. GH.curInt = nullptr;
  590. GH.windows().clear();
  591. adventureInt.reset();
  592. logGlobal->info("Removed GUI.");
  593. LOCPLINT = nullptr;
  594. }
  595. #ifdef VCMI_ANDROID
  596. #ifndef SINGLE_PROCESS_APP
  597. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerClosed(JNIEnv * env, jclass cls)
  598. {
  599. logNetwork->info("Received server closed signal");
  600. if (CSH) {
  601. CSH->campaignServerRestartLock.setn(false);
  602. }
  603. }
  604. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerReady(JNIEnv * env, jclass cls)
  605. {
  606. logNetwork->info("Received server ready signal");
  607. androidTestServerReadyFlag.store(true);
  608. }
  609. #endif
  610. extern "C" JNIEXPORT jboolean JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jclass cls)
  611. {
  612. logGlobal->info("Received emergency save game request");
  613. if(!LOCPLINT || !LOCPLINT->cb)
  614. {
  615. return false;
  616. }
  617. LOCPLINT->cb->save("Saves/_Android_Autosave");
  618. return true;
  619. }
  620. #endif