Client.cpp 16 KB

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