Client.cpp 21 KB

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