Client.cpp 21 KB

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