Client.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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/Connection.h"
  31. #include "../lib/mapping/CMapService.h"
  32. #include "../lib/pathfinder/CGPathNode.h"
  33. #include "../lib/filesystem/Filesystem.h"
  34. #include <memory>
  35. #include <vcmi/events/EventBus.h>
  36. #if SCRIPTING_ENABLED
  37. #include "../lib/ScriptHandler.h"
  38. #endif
  39. #ifdef VCMI_ANDROID
  40. #include "lib/CAndroidVMHelper.h"
  41. #endif
  42. ThreadSafeVector<int> CClient::waitingRequest;
  43. CPlayerEnvironment::CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_)
  44. : player(player_),
  45. cl(cl_),
  46. mainCallback(mainCallback_)
  47. {
  48. }
  49. const Services * CPlayerEnvironment::services() const
  50. {
  51. return VLC;
  52. }
  53. vstd::CLoggerBase * CPlayerEnvironment::logger() const
  54. {
  55. return logGlobal;
  56. }
  57. events::EventBus * CPlayerEnvironment::eventBus() const
  58. {
  59. return cl->eventBus();//always get actual value
  60. }
  61. const CPlayerEnvironment::BattleCb * CPlayerEnvironment::battle(const BattleID & battleID) const
  62. {
  63. return mainCallback->getBattle(battleID).get();
  64. }
  65. const CPlayerEnvironment::GameCb * CPlayerEnvironment::game() const
  66. {
  67. return mainCallback.get();
  68. }
  69. CClient::CClient()
  70. {
  71. waitingRequest.clear();
  72. gs = nullptr;
  73. }
  74. CClient::~CClient() = default;
  75. const Services * CClient::services() const
  76. {
  77. return VLC; //todo: this should be CGI
  78. }
  79. const CClient::BattleCb * CClient::battle(const BattleID & battleID) const
  80. {
  81. return nullptr; //todo?
  82. }
  83. const CClient::GameCb * CClient::game() const
  84. {
  85. return this;
  86. }
  87. vstd::CLoggerBase * CClient::logger() const
  88. {
  89. return logGlobal;
  90. }
  91. events::EventBus * CClient::eventBus() const
  92. {
  93. return clientEventBus.get();
  94. }
  95. void CClient::newGame(CGameState * initializedGameState)
  96. {
  97. CSH->th->update();
  98. CMapService mapService;
  99. assert(initializedGameState);
  100. gs = initializedGameState;
  101. gs->preInit(VLC, this);
  102. logNetwork->trace("\tCreating gamestate: %i", CSH->th->getDiff());
  103. if(!initializedGameState)
  104. {
  105. Load::ProgressAccumulator progressTracking;
  106. gs->init(&mapService, CSH->si.get(), progressTracking, settings["general"]["saveRandomMaps"].Bool());
  107. }
  108. logNetwork->trace("Initializing GameState (together): %d ms", CSH->th->getDiff());
  109. initMapHandler();
  110. reinitScripting();
  111. initPlayerEnvironments();
  112. initPlayerInterfaces();
  113. }
  114. void CClient::loadGame(CGameState * initializedGameState)
  115. {
  116. logNetwork->info("Loading procedure started!");
  117. logNetwork->info("Game state was transferred over network, loading.");
  118. gs = initializedGameState;
  119. gs->preInit(VLC, this);
  120. gs->updateOnLoad(CSH->si.get());
  121. logNetwork->info("Game loaded, initialize interfaces.");
  122. initMapHandler();
  123. reinitScripting();
  124. initPlayerEnvironments();
  125. initPlayerInterfaces();
  126. }
  127. void CClient::save(const std::string & fname)
  128. {
  129. if(!gs->currentBattles.empty())
  130. {
  131. logNetwork->error("Game cannot be saved during battle!");
  132. return;
  133. }
  134. SaveGame save_game(fname);
  135. sendRequest(&save_game, PlayerColor::NEUTRAL);
  136. }
  137. void CClient::endNetwork()
  138. {
  139. if (CGI->mh)
  140. CGI->mh->endNetwork();
  141. if (CPlayerInterface::battleInt)
  142. CPlayerInterface::battleInt->endNetwork();
  143. for(auto & i : playerint)
  144. {
  145. auto interface = std::dynamic_pointer_cast<CPlayerInterface>(i.second);
  146. if (interface)
  147. interface->endNetwork();
  148. }
  149. }
  150. void CClient::endGame()
  151. {
  152. #if SCRIPTING_ENABLED
  153. clientScripts.reset();
  154. #endif
  155. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  156. for(auto & i : playerint)
  157. i.second->finish();
  158. GH.curInt = nullptr;
  159. {
  160. logNetwork->info("Ending current game!");
  161. removeGUI();
  162. CGI->mh.reset();
  163. vstd::clear_pointer(gs);
  164. logNetwork->info("Deleted mapHandler and gameState.");
  165. }
  166. CPlayerInterface::battleInt.reset();
  167. playerint.clear();
  168. battleints.clear();
  169. battleCallbacks.clear();
  170. playerEnvironments.clear();
  171. logNetwork->info("Deleted playerInts.");
  172. logNetwork->info("Client stopped.");
  173. }
  174. void CClient::initMapHandler()
  175. {
  176. // TODO: CMapHandler initialization can probably go somewhere else
  177. // It's can't be before initialization of interfaces
  178. // During loading CPlayerInterface from serialized state it's depend on MH
  179. if(!settings["session"]["headless"].Bool())
  180. {
  181. CGI->mh = std::make_shared<CMapHandler>(gs->map);
  182. logNetwork->trace("Creating mapHandler: %d ms", CSH->th->getDiff());
  183. }
  184. pathCache.clear();
  185. }
  186. void CClient::initPlayerEnvironments()
  187. {
  188. playerEnvironments.clear();
  189. auto allPlayers = CSH->getAllClientPlayers(CSH->logicConnection->connectionID);
  190. bool hasHumanPlayer = false;
  191. for(auto & color : allPlayers)
  192. {
  193. logNetwork->info("Preparing environment for player %s", color.toString());
  194. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gs, color, this));
  195. if(!hasHumanPlayer && gs->players[color].isHuman())
  196. hasHumanPlayer = true;
  197. }
  198. if(!hasHumanPlayer && !settings["session"]["headless"].Bool())
  199. {
  200. Settings session = settings.write["session"];
  201. session["spectate"].Bool() = true;
  202. session["spectate-skip-battle-result"].Bool() = true;
  203. session["spectate-ignore-hero"].Bool() = true;
  204. }
  205. if(settings["session"]["spectate"].Bool())
  206. {
  207. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, std::nullopt, this));
  208. }
  209. }
  210. void CClient::initPlayerInterfaces()
  211. {
  212. for(auto & playerInfo : gs->scenarioOps->playerInfos)
  213. {
  214. PlayerColor color = playerInfo.first;
  215. if(!vstd::contains(CSH->getAllClientPlayers(CSH->logicConnection->connectionID), color))
  216. continue;
  217. if(!vstd::contains(playerint, color))
  218. {
  219. logNetwork->info("Preparing interface for player %s", color.toString());
  220. if(playerInfo.second.isControlledByAI() || settings["session"]["onlyai"].Bool())
  221. {
  222. bool alliedToHuman = false;
  223. for(auto & allyInfo : gs->scenarioOps->playerInfos)
  224. if (gs->getPlayerTeam(allyInfo.first) == gs->getPlayerTeam(playerInfo.first) && allyInfo.second.isControlledByHuman())
  225. alliedToHuman = true;
  226. auto AiToGive = aiNameForPlayer(playerInfo.second, false, alliedToHuman);
  227. logNetwork->info("Player %s will be lead by %s", color.toString(), AiToGive);
  228. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  229. }
  230. else
  231. {
  232. logNetwork->info("Player %s will be lead by human", color.toString());
  233. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  234. }
  235. }
  236. }
  237. if(settings["session"]["spectate"].Bool())
  238. {
  239. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  240. }
  241. if(CSH->getAllClientPlayers(CSH->logicConnection->connectionID).count(PlayerColor::NEUTRAL))
  242. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  243. logNetwork->trace("Initialized player interfaces %d ms", CSH->th->getDiff());
  244. }
  245. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI, bool alliedToHuman) const
  246. {
  247. if(ps.name.size())
  248. {
  249. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  250. if(boost::filesystem::exists(aiPath))
  251. return ps.name;
  252. }
  253. return aiNameForPlayer(battleAI, alliedToHuman);
  254. }
  255. std::string CClient::aiNameForPlayer(bool battleAI, bool alliedToHuman) const
  256. {
  257. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  258. std::string goodAdventureAI = alliedToHuman ? settings["server"]["alliedAI"].String() : settings["server"]["playerAI"].String();
  259. std::string goodBattleAI = settings["server"]["neutralAI"].String();
  260. std::string goodAI = battleAI ? goodBattleAI : goodAdventureAI;
  261. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  262. //TODO what about human players
  263. if(battleints.size() >= sensibleAILimit)
  264. return badAI;
  265. return goodAI;
  266. }
  267. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb)
  268. {
  269. playerint[color] = gameInterface;
  270. logGlobal->trace("\tInitializing the interface for player %s", color.toString());
  271. auto cb = std::make_shared<CCallback>(gs, color, this);
  272. battleCallbacks[color] = cb;
  273. gameInterface->initGameInterface(playerEnvironments.at(color), cb);
  274. installNewBattleInterface(gameInterface, color, battlecb);
  275. }
  276. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback)
  277. {
  278. battleints[color] = battleInterface;
  279. if(needCallback)
  280. {
  281. logGlobal->trace("\tInitializing the battle interface for player %s", color.toString());
  282. auto cbc = std::make_shared<CBattleCallback>(color, this);
  283. battleCallbacks[color] = cbc;
  284. battleInterface->initBattleInterface(playerEnvironments.at(color), cbc);
  285. }
  286. }
  287. void CClient::handlePack(CPackForClient * pack)
  288. {
  289. ApplyClientNetPackVisitor afterVisitor(*this, *gameState());
  290. ApplyFirstClientNetPackVisitor beforeVisitor(*this, *gameState());
  291. pack->visit(beforeVisitor);
  292. logNetwork->trace("\tMade first apply on cl: %s", typeid(*pack).name());
  293. {
  294. boost::unique_lock lock(CGameState::mutex);
  295. gs->apply(pack);
  296. }
  297. logNetwork->trace("\tApplied on gs: %s", typeid(*pack).name());
  298. pack->visit(afterVisitor);
  299. logNetwork->trace("\tMade second apply on cl: %s", typeid(*pack).name());
  300. delete pack;
  301. }
  302. int CClient::sendRequest(const CPackForServer * request, PlayerColor player)
  303. {
  304. static ui32 requestCounter = 1;
  305. ui32 requestID = requestCounter++;
  306. logNetwork->trace("Sending a request \"%s\". It'll have an ID=%d.", typeid(*request).name(), requestID);
  307. waitingRequest.pushBack(requestID);
  308. request->requestID = requestID;
  309. request->player = player;
  310. CSH->logicConnection->sendPack(request);
  311. if(vstd::contains(playerint, player))
  312. playerint[player]->requestSent(request, requestID);
  313. return requestID;
  314. }
  315. void CClient::battleStarted(const BattleInfo * info)
  316. {
  317. std::shared_ptr<CPlayerInterface> att;
  318. std::shared_ptr<CPlayerInterface> def;
  319. const auto & leftSide = info->getSide(BattleSide::LEFT_SIDE);
  320. const auto & rightSide = info->getSide(BattleSide::RIGHT_SIDE);
  321. for(auto & battleCb : battleCallbacks)
  322. {
  323. if(!battleCb.first.isValidPlayer() || battleCb.first == leftSide.color || battleCb.first == rightSide.color)
  324. battleCb.second->onBattleStarted(info);
  325. }
  326. //If quick combat is not, do not prepare interfaces for battleint
  327. auto callBattleStart = [&](PlayerColor color, BattleSide side)
  328. {
  329. if(vstd::contains(battleints, color))
  330. battleints[color]->battleStart(info->battleID, leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side, info->replayAllowed);
  331. };
  332. callBattleStart(leftSide.color, BattleSide::LEFT_SIDE);
  333. callBattleStart(rightSide.color, BattleSide::RIGHT_SIDE);
  334. callBattleStart(PlayerColor::UNFLAGGABLE, BattleSide::RIGHT_SIDE);
  335. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  336. callBattleStart(PlayerColor::SPECTATOR, BattleSide::RIGHT_SIDE);
  337. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  338. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  339. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  340. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  341. //Remove player interfaces for auto battle (quickCombat option)
  342. if((att && att->isAutoFightOn) || (def && def->isAutoFightOn))
  343. {
  344. auto endTacticPhaseIfEligible = [info](const CPlayerInterface * interface)
  345. {
  346. if (interface->cb->getBattle(info->battleID)->battleGetTacticDist())
  347. {
  348. auto side = interface->cb->getBattle(info->battleID)->playerToSide(interface->playerID);
  349. if(interface->playerID == info->getSide(info->tacticsSide).color)
  350. {
  351. auto action = BattleAction::makeEndOFTacticPhase(side);
  352. interface->cb->battleMakeTacticAction(info->battleID, action);
  353. }
  354. }
  355. };
  356. if(att && att->isAutoFightOn)
  357. endTacticPhaseIfEligible(att.get());
  358. else // def && def->isAutoFightOn
  359. endTacticPhaseIfEligible(def.get());
  360. att.reset();
  361. def.reset();
  362. }
  363. if(!settings["session"]["headless"].Bool())
  364. {
  365. if(att || def)
  366. {
  367. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(info->getBattleID(), leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def);
  368. }
  369. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  370. {
  371. //TODO: This certainly need improvement
  372. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  373. spectratorInt->cb->onBattleStarted(info);
  374. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(info->getBattleID(), leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def, spectratorInt);
  375. }
  376. }
  377. if(info->tacticDistance)
  378. {
  379. auto tacticianColor = info->getSide(info->tacticsSide).color;
  380. if (vstd::contains(battleints, tacticianColor))
  381. battleints[tacticianColor]->yourTacticPhase(info->battleID, info->tacticDistance);
  382. }
  383. }
  384. void CClient::battleFinished(const BattleID & battleID)
  385. {
  386. for(auto side : { BattleSide::ATTACKER, BattleSide::DEFENDER })
  387. {
  388. if(battleCallbacks.count(gs->getBattle(battleID)->getSide(side).color))
  389. battleCallbacks[gs->getBattle(battleID)->getSide(side).color]->onBattleEnded(battleID);
  390. }
  391. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  392. battleCallbacks[PlayerColor::SPECTATOR]->onBattleEnded(battleID);
  393. }
  394. void CClient::startPlayerBattleAction(const BattleID & battleID, PlayerColor color)
  395. {
  396. if (battleints.count(color) == 0)
  397. return; // not our combat in MP
  398. auto battleint = battleints.at(color);
  399. if (!battleint->human)
  400. {
  401. // we want to avoid locking gamestate and causing UI to freeze while AI is making turn
  402. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  403. battleint->activeStack(battleID, gs->getBattle(battleID)->battleGetStackByID(gs->getBattle(battleID)->activeStack, false));
  404. }
  405. else
  406. {
  407. battleint->activeStack(battleID, gs->getBattle(battleID)->battleGetStackByID(gs->getBattle(battleID)->activeStack, false));
  408. }
  409. }
  410. void CClient::invalidatePaths()
  411. {
  412. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  413. pathCache.clear();
  414. }
  415. vstd::RNG & CClient::getRandomGenerator()
  416. {
  417. // Client should use CRandomGenerator::getDefault() for UI logic
  418. // Gamestate should never call this method on client!
  419. throw std::runtime_error("Illegal access to random number generator from client code!");
  420. }
  421. std::shared_ptr<const CPathsInfo> CClient::getPathsInfo(const CGHeroInstance * h)
  422. {
  423. assert(h);
  424. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  425. auto iter = pathCache.find(h);
  426. if(iter == std::end(pathCache))
  427. {
  428. auto paths = std::make_shared<CPathsInfo>(getMapSize(), h);
  429. gs->calculatePaths(h, *paths.get());
  430. pathCache[h] = paths;
  431. return paths;
  432. }
  433. else
  434. {
  435. return iter->second;
  436. }
  437. }
  438. #if SCRIPTING_ENABLED
  439. scripting::Pool * CClient::getGlobalContextPool() const
  440. {
  441. return clientScripts.get();
  442. }
  443. #endif
  444. void CClient::reinitScripting()
  445. {
  446. clientEventBus = std::make_unique<events::EventBus>();
  447. #if SCRIPTING_ENABLED
  448. clientScripts.reset(new scripting::PoolImpl(this));
  449. #endif
  450. }
  451. void CClient::removeGUI() const
  452. {
  453. // CClient::endGame
  454. GH.curInt = nullptr;
  455. GH.windows().clear();
  456. adventureInt.reset();
  457. logGlobal->info("Removed GUI.");
  458. LOCPLINT = nullptr;
  459. }
  460. #ifdef VCMI_ANDROID
  461. extern "C" JNIEXPORT jboolean JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jclass cls)
  462. {
  463. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  464. logGlobal->info("Received emergency save game request");
  465. if(!LOCPLINT || !LOCPLINT->cb)
  466. {
  467. logGlobal->info("... but no active player interface found!");
  468. return false;
  469. }
  470. if (!CSH || !CSH->logicConnection)
  471. {
  472. logGlobal->info("... but no active connection found!");
  473. return false;
  474. }
  475. LOCPLINT->cb->save("Saves/_Android_Autosave");
  476. return true;
  477. }
  478. #endif