Client.cpp 21 KB

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