Client.cpp 21 KB

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