Client.cpp 21 KB

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