Client.cpp 21 KB

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