Client.cpp 21 KB

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