CPlayerInterface.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  1. /*
  2. * CPlayerInterface.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 "CPlayerInterface.h"
  12. #include <vcmi/Artifact.h>
  13. #include "CGameInfo.h"
  14. #include "CMT.h"
  15. #include "CMusicHandler.h"
  16. #include "CServerHandler.h"
  17. #include "HeroMovementController.h"
  18. #include "PlayerLocalState.h"
  19. #include "adventureMap/AdventureMapInterface.h"
  20. #include "adventureMap/CInGameConsole.h"
  21. #include "adventureMap/CList.h"
  22. #include "battle/BattleEffectsController.h"
  23. #include "battle/BattleFieldController.h"
  24. #include "battle/BattleInterface.h"
  25. #include "battle/BattleInterfaceClasses.h"
  26. #include "battle/BattleWindow.h"
  27. #include "eventsSDL/InputHandler.h"
  28. #include "eventsSDL/NotificationHandler.h"
  29. #include "gui/CGuiHandler.h"
  30. #include "gui/CursorHandler.h"
  31. #include "gui/WindowHandler.h"
  32. #include "mainmenu/CMainMenu.h"
  33. #include "mainmenu/CHighScoreScreen.h"
  34. #include "mapView/mapHandler.h"
  35. #include "render/CAnimation.h"
  36. #include "render/IImage.h"
  37. #include "widgets/Buttons.h"
  38. #include "widgets/CComponent.h"
  39. #include "widgets/CGarrisonInt.h"
  40. #include "windows/CAltarWindow.h"
  41. #include "windows/CCastleInterface.h"
  42. #include "windows/CCreatureWindow.h"
  43. #include "windows/CHeroWindow.h"
  44. #include "windows/CKingdomInterface.h"
  45. #include "windows/CPuzzleWindow.h"
  46. #include "windows/CQuestLog.h"
  47. #include "windows/CSpellWindow.h"
  48. #include "windows/CTradeWindow.h"
  49. #include "windows/CTutorialWindow.h"
  50. #include "windows/GUIClasses.h"
  51. #include "windows/InfoWindows.h"
  52. #include "../CCallback.h"
  53. #include "../lib/CArtHandler.h"
  54. #include "../lib/CConfigHandler.h"
  55. #include "../lib/CGeneralTextHandler.h"
  56. #include "../lib/CHeroHandler.h"
  57. #include "../lib/CPlayerState.h"
  58. #include "../lib/CStack.h"
  59. #include "../lib/CStopWatch.h"
  60. #include "../lib/CThreadHelper.h"
  61. #include "../lib/CTownHandler.h"
  62. #include "../lib/CondSh.h"
  63. #include "../lib/GameConstants.h"
  64. #include "../lib/JsonNode.h"
  65. #include "../lib/RoadHandler.h"
  66. #include "../lib/StartInfo.h"
  67. #include "../lib/TerrainHandler.h"
  68. #include "../lib/TextOperations.h"
  69. #include "../lib/UnlockGuard.h"
  70. #include "../lib/VCMIDirs.h"
  71. #include "../lib/bonuses/CBonusSystemNode.h"
  72. #include "../lib/bonuses/Limiters.h"
  73. #include "../lib/bonuses/Propagators.h"
  74. #include "../lib/bonuses/Updaters.h"
  75. #include "../lib/gameState/CGameState.h"
  76. #include "../lib/mapObjects/CGTownInstance.h"
  77. #include "../lib/mapObjects/MiscObjects.h"
  78. #include "../lib/mapObjects/ObjectTemplate.h"
  79. #include "../lib/mapping/CMapHeader.h"
  80. #include "../lib/networkPacks/PacksForClient.h"
  81. #include "../lib/networkPacks/PacksForClientBattle.h"
  82. #include "../lib/networkPacks/PacksForServer.h"
  83. #include "../lib/pathfinder/CGPathNode.h"
  84. #include "../lib/serializer/BinaryDeserializer.h"
  85. #include "../lib/serializer/BinarySerializer.h"
  86. #include "../lib/serializer/CTypeList.h"
  87. #include "../lib/spells/CSpellHandler.h"
  88. // The macro below is used to mark functions that are called by client when game state changes.
  89. // They all assume that interface mutex is locked.
  90. #define EVENT_HANDLER_CALLED_BY_CLIENT
  91. #define BATTLE_EVENT_POSSIBLE_RETURN if (LOCPLINT != this) return; if (isAutoFightOn && !battleInt) return
  92. CPlayerInterface * LOCPLINT;
  93. std::shared_ptr<BattleInterface> CPlayerInterface::battleInt;
  94. struct HeroObjectRetriever
  95. {
  96. const CGHeroInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  97. {
  98. return h;
  99. }
  100. const CGHeroInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  101. {
  102. return nullptr;
  103. }
  104. };
  105. CPlayerInterface::CPlayerInterface(PlayerColor Player):
  106. localState(std::make_unique<PlayerLocalState>(*this)),
  107. movementController(std::make_unique<HeroMovementController>())
  108. {
  109. logGlobal->trace("\tHuman player interface for player %s being constructed", Player.toString());
  110. GH.defActionsDef = 0;
  111. LOCPLINT = this;
  112. playerID=Player;
  113. human=true;
  114. battleInt = nullptr;
  115. castleInt = nullptr;
  116. makingTurn = false;
  117. showingDialog = new CondSh<bool>(false);
  118. cingconsole = new CInGameConsole();
  119. firstCall = 1; //if loading will be overwritten in serialize
  120. autosaveCount = 0;
  121. isAutoFightOn = false;
  122. ignoreEvents = false;
  123. numOfMovedArts = 0;
  124. }
  125. CPlayerInterface::~CPlayerInterface()
  126. {
  127. logGlobal->trace("\tHuman player interface for player %s being destructed", playerID.toString());
  128. delete showingDialog;
  129. delete cingconsole;
  130. if (LOCPLINT == this)
  131. LOCPLINT = nullptr;
  132. }
  133. void CPlayerInterface::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  134. {
  135. cb = CB;
  136. env = ENV;
  137. CCS->musich->loadTerrainMusicThemes();
  138. initializeHeroTownList();
  139. adventureInt.reset(new AdventureMapInterface());
  140. }
  141. void CPlayerInterface::playerEndsTurn(PlayerColor player)
  142. {
  143. EVENT_HANDLER_CALLED_BY_CLIENT;
  144. if (player == playerID)
  145. {
  146. makingTurn = false;
  147. // remove all active dialogs that do not expect query answer
  148. for (;;)
  149. {
  150. auto adventureWindow = GH.windows().topWindow<AdventureMapInterface>();
  151. auto infoWindow = GH.windows().topWindow<CInfoWindow>();
  152. if(adventureWindow != nullptr)
  153. break;
  154. if(infoWindow && infoWindow->ID != QueryID::NONE)
  155. break;
  156. if (infoWindow)
  157. infoWindow->close();
  158. else
  159. GH.windows().popWindows(1);
  160. }
  161. // remove all pending dialogs that do not expect query answer
  162. vstd::erase_if(dialogs, [](const std::shared_ptr<CInfoWindow> & window){
  163. return window->ID == QueryID::NONE;
  164. });
  165. }
  166. }
  167. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  168. {
  169. if(GH.windows().findWindows<AdventureMapInterface>().empty())
  170. {
  171. // after map load - remove all active windows and replace them with adventure map
  172. GH.windows().clear();
  173. GH.windows().pushWindow(adventureInt);
  174. }
  175. EVENT_HANDLER_CALLED_BY_CLIENT;
  176. if (player != playerID && LOCPLINT == this)
  177. {
  178. waitWhileDialog();
  179. bool isHuman = cb->getStartInfo()->playerInfos.count(player) && cb->getStartInfo()->playerInfos.at(player).isControlledByHuman();
  180. if (makingTurn == false)
  181. adventureInt->onEnemyTurnStarted(player, isHuman);
  182. }
  183. }
  184. void CPlayerInterface::performAutosave()
  185. {
  186. int frequency = static_cast<int>(settings["general"]["saveFrequency"].Integer());
  187. if(frequency > 0 && cb->getDate() % frequency == 0)
  188. {
  189. bool usePrefix = settings["general"]["useSavePrefix"].Bool();
  190. std::string prefix = std::string();
  191. if(usePrefix)
  192. {
  193. prefix = settings["general"]["savePrefix"].String();
  194. if(prefix.empty())
  195. {
  196. std::string name = cb->getMapHeader()->name.toString();
  197. int txtlen = TextOperations::getUnicodeCharactersCount(name);
  198. TextOperations::trimRightUnicode(name, std::max(0, txtlen - 15));
  199. std::string forbiddenChars("\\/:?\"<>| ");
  200. std::replace_if(name.begin(), name.end(), [&](char c) { return std::string::npos != forbiddenChars.find(c); }, '_' );
  201. prefix = name + "_" + cb->getStartInfo()->startTimeIso8601 + "/";
  202. }
  203. }
  204. autosaveCount++;
  205. int autosaveCountLimit = settings["general"]["autosaveCountLimit"].Integer();
  206. if(autosaveCountLimit > 0)
  207. {
  208. cb->save("Saves/Autosave/" + prefix + std::to_string(autosaveCount));
  209. autosaveCount %= autosaveCountLimit;
  210. }
  211. else
  212. {
  213. std::string stringifiedDate = std::to_string(cb->getDate(Date::MONTH))
  214. + std::to_string(cb->getDate(Date::WEEK))
  215. + std::to_string(cb->getDate(Date::DAY_OF_WEEK));
  216. cb->save("Saves/Autosave/" + prefix + stringifiedDate);
  217. }
  218. }
  219. }
  220. void CPlayerInterface::gamePause(bool pause)
  221. {
  222. cb->gamePause(pause);
  223. }
  224. void CPlayerInterface::yourTurn(QueryID queryID)
  225. {
  226. CTutorialWindow::openWindowFirstTime(TutorialMode::TOUCH_ADVENTUREMAP);
  227. EVENT_HANDLER_CALLED_BY_CLIENT;
  228. {
  229. LOCPLINT = this;
  230. GH.curInt = this;
  231. NotificationHandler::notify("Your turn");
  232. if(settings["general"]["startTurnAutosave"].Bool())
  233. {
  234. performAutosave();
  235. }
  236. if (CSH->howManyPlayerInterfaces() > 1) //hot seat message
  237. {
  238. adventureInt->onHotseatWaitStarted(playerID);
  239. makingTurn = true;
  240. std::string msg = CGI->generaltexth->allTexts[13];
  241. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  242. std::vector<std::shared_ptr<CComponent>> cmp;
  243. cmp.push_back(std::make_shared<CComponent>(ComponentType::FLAG, playerID));
  244. showInfoDialog(msg, cmp);
  245. }
  246. else
  247. {
  248. makingTurn = true;
  249. adventureInt->onPlayerTurnStarted(playerID);
  250. }
  251. }
  252. acceptTurn(queryID);
  253. }
  254. void CPlayerInterface::acceptTurn(QueryID queryID)
  255. {
  256. if (settings["session"]["autoSkip"].Bool())
  257. {
  258. while(auto iw = GH.windows().topWindow<CInfoWindow>())
  259. iw->close();
  260. }
  261. if(CSH->howManyPlayerInterfaces() > 1)
  262. {
  263. waitWhileDialog(); // wait for player to accept turn in hot-seat mode
  264. adventureInt->onPlayerTurnStarted(playerID);
  265. }
  266. // warn player if he has no town
  267. if (cb->howManyTowns() == 0)
  268. {
  269. auto playerColor = *cb->getPlayerID();
  270. std::vector<Component> components;
  271. components.emplace_back(ComponentType::FLAG, playerColor);
  272. MetaString text;
  273. const auto & optDaysWithoutCastle = cb->getPlayerState(playerColor)->daysWithoutCastle;
  274. if(optDaysWithoutCastle)
  275. {
  276. auto daysWithoutCastle = optDaysWithoutCastle.value();
  277. if (daysWithoutCastle < 6)
  278. {
  279. text.appendLocalString(EMetaText::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  280. text.replaceName(playerColor);
  281. text.replaceNumber(7 - daysWithoutCastle);
  282. }
  283. else if (daysWithoutCastle == 6)
  284. {
  285. text.appendLocalString(EMetaText::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  286. text.replaceName(playerColor);
  287. }
  288. showInfoDialogAndWait(components, text);
  289. }
  290. else
  291. logGlobal->warn("Player has no towns, but daysWithoutCastle is not set");
  292. }
  293. cb->selectionMade(0, queryID);
  294. movementController->onPlayerTurnStarted();
  295. }
  296. void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose)
  297. {
  298. EVENT_HANDLER_CALLED_BY_CLIENT;
  299. waitWhileDialog();
  300. if(LOCPLINT != this)
  301. return;
  302. //FIXME: read once and store
  303. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-ignore-hero"].Bool())
  304. return;
  305. const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
  306. if (!hero)
  307. return;
  308. movementController->onTryMoveHero(hero, details);
  309. }
  310. void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
  311. {
  312. EVENT_HANDLER_CALLED_BY_CLIENT;
  313. LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->getNameTranslated() % playerID);
  314. // if hero is not in town garrison
  315. if (vstd::contains(localState->getWanderingHeroes(), hero))
  316. localState->removeWanderingHero(hero);
  317. adventureInt->onHeroChanged(hero);
  318. localState->erasePath(hero);
  319. }
  320. void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  321. {
  322. EVENT_HANDLER_CALLED_BY_CLIENT;
  323. if(start && visitedObj)
  324. {
  325. if(visitedObj->getVisitSound())
  326. CCS->soundh->playSound(visitedObj->getVisitSound().value());
  327. }
  328. }
  329. void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
  330. {
  331. EVENT_HANDLER_CALLED_BY_CLIENT;
  332. localState->addWanderingHero(hero);
  333. adventureInt->onHeroChanged(hero);
  334. }
  335. void CPlayerInterface::openTownWindow(const CGTownInstance * town)
  336. {
  337. if(castleInt)
  338. castleInt->close();
  339. castleInt = nullptr;
  340. auto newCastleInt = std::make_shared<CCastleInterface>(town);
  341. GH.windows().pushWindow(newCastleInt);
  342. }
  343. void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val)
  344. {
  345. EVENT_HANDLER_CALLED_BY_CLIENT;
  346. if (which == PrimarySkill::EXPERIENCE)
  347. {
  348. for (auto ctw : GH.windows().findWindows<CAltarWindow>())
  349. ctw->updateExpToLevel();
  350. }
  351. else
  352. adventureInt->onHeroChanged(hero);
  353. }
  354. void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  355. {
  356. EVENT_HANDLER_CALLED_BY_CLIENT;
  357. for (auto cuw : GH.windows().findWindows<CUniversityWindow>())
  358. cuw->redraw();
  359. }
  360. void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
  361. {
  362. EVENT_HANDLER_CALLED_BY_CLIENT;
  363. adventureInt->onHeroChanged(hero);
  364. if (makingTurn && hero->tempOwner == playerID)
  365. adventureInt->onHeroChanged(hero);
  366. }
  367. void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
  368. {
  369. EVENT_HANDLER_CALLED_BY_CLIENT;
  370. if (makingTurn && hero->tempOwner == playerID)
  371. adventureInt->onHeroChanged(hero);
  372. }
  373. void CPlayerInterface::receivedResource()
  374. {
  375. EVENT_HANDLER_CALLED_BY_CLIENT;
  376. for (auto mw : GH.windows().findWindows<CMarketplaceWindow>())
  377. mw->resourceChanged();
  378. GH.windows().totalRedraw();
  379. }
  380. void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
  381. {
  382. EVENT_HANDLER_CALLED_BY_CLIENT;
  383. waitWhileDialog();
  384. CCS->soundh->playSound(soundBase::heroNewLevel);
  385. GH.windows().createAndPushWindow<CLevelWindow>(hero, pskill, skills, [=](ui32 selection)
  386. {
  387. cb->selectionMade(selection, queryID);
  388. });
  389. }
  390. void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  391. {
  392. EVENT_HANDLER_CALLED_BY_CLIENT;
  393. waitWhileDialog();
  394. CCS->soundh->playSound(soundBase::heroNewLevel);
  395. GH.windows().createAndPushWindow<CStackWindow>(commander, skills, [=](ui32 selection)
  396. {
  397. cb->selectionMade(selection, queryID);
  398. });
  399. }
  400. void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
  401. {
  402. EVENT_HANDLER_CALLED_BY_CLIENT;
  403. if(town->garrisonHero) //wandering hero moved to the garrison
  404. {
  405. // This method also gets called on hero recruitment -> garrisoned hero is already in garrison
  406. if(town->garrisonHero->tempOwner == playerID && vstd::contains(localState->getWanderingHeroes(), town->garrisonHero))
  407. localState->removeWanderingHero(town->garrisonHero);
  408. }
  409. if(town->visitingHero) //hero leaves garrison
  410. {
  411. // This method also gets called on hero recruitment -> wandering heroes already contains new hero
  412. if(town->visitingHero->tempOwner == playerID && !vstd::contains(localState->getWanderingHeroes(), town->visitingHero))
  413. localState->addWanderingHero(town->visitingHero);
  414. }
  415. adventureInt->onHeroChanged(nullptr);
  416. adventureInt->onTownChanged(town);
  417. for (auto cgh : GH.windows().findWindows<IGarrisonHolder>())
  418. if (cgh->holdsGarrison(town))
  419. cgh->updateGarrisons();
  420. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  421. ki->townChanged(town);
  422. // Perform totalRedraw to update hero list on adventure map, if any dialogs are open
  423. GH.windows().totalRedraw();
  424. }
  425. void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  426. {
  427. EVENT_HANDLER_CALLED_BY_CLIENT;
  428. if (hero->tempOwner != playerID )
  429. return;
  430. waitWhileDialog();
  431. openTownWindow(town);
  432. }
  433. void CPlayerInterface::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  434. {
  435. std::vector<const CArmedInstance *> instances;
  436. if(auto obj = dynamic_cast<const CArmedInstance *>(cb->getObjInstance(id1)))
  437. instances.push_back(obj);
  438. if(id2 != ObjectInstanceID() && id2 != id1)
  439. {
  440. if(auto obj = dynamic_cast<const CArmedInstance *>(cb->getObjInstance(id2)))
  441. instances.push_back(obj);
  442. }
  443. garrisonsChanged(instances);
  444. }
  445. void CPlayerInterface::garrisonsChanged(std::vector<const CArmedInstance *> objs)
  446. {
  447. for (auto object : objs)
  448. {
  449. auto * hero = dynamic_cast<const CGHeroInstance*>(object);
  450. auto * town = dynamic_cast<const CGTownInstance*>(object);
  451. if (town)
  452. adventureInt->onTownChanged(town);
  453. if (hero)
  454. {
  455. adventureInt->onHeroChanged(hero);
  456. if(hero->inTownGarrison && hero->visitedTown != town)
  457. adventureInt->onTownChanged(hero->visitedTown);
  458. }
  459. }
  460. for (auto cgh : GH.windows().findWindows<IGarrisonHolder>())
  461. if (cgh->holdsGarrisons(objs))
  462. cgh->updateGarrisons();
  463. GH.windows().totalRedraw();
  464. }
  465. void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
  466. {
  467. EVENT_HANDLER_CALLED_BY_CLIENT;
  468. adventureInt->onTownChanged(town);
  469. if (castleInt)
  470. {
  471. castleInt->townlist->updateElement(town);
  472. if (castleInt->town == town)
  473. {
  474. switch(what)
  475. {
  476. case 1:
  477. CCS->soundh->playSound(soundBase::newBuilding);
  478. castleInt->addBuilding(buildingID);
  479. break;
  480. case 2:
  481. castleInt->removeBuilding(buildingID);
  482. break;
  483. }
  484. }
  485. // Perform totalRedraw in order to force redraw of updated town list icon from adventure map
  486. GH.windows().totalRedraw();
  487. }
  488. for (auto cgh : GH.windows().findWindows<ITownHolder>())
  489. cgh->buildChanged();
  490. }
  491. void CPlayerInterface::battleStartBefore(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  492. {
  493. movementController->onBattleStarted();
  494. //Don't wait for dialogs when we are non-active hot-seat player
  495. if (LOCPLINT == this)
  496. waitForAllDialogs();
  497. }
  498. void CPlayerInterface::battleStart(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side, bool replayAllowed)
  499. {
  500. EVENT_HANDLER_CALLED_BY_CLIENT;
  501. bool useQuickCombat = settings["adventure"]["quickCombat"].Bool();
  502. bool forceQuickCombat = settings["adventure"]["forceQuickCombat"].Bool();
  503. if ((replayAllowed && useQuickCombat) || forceQuickCombat)
  504. {
  505. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  506. AutocombatPreferences autocombatPreferences = AutocombatPreferences();
  507. autocombatPreferences.enableSpellsUsage = settings["battle"]["enableAutocombatSpells"].Bool();
  508. autofightingAI->initBattleInterface(env, cb, autocombatPreferences);
  509. autofightingAI->battleStart(battleID, army1, army2, tile, hero1, hero2, side, false);
  510. isAutoFightOn = true;
  511. cb->registerBattleInterface(autofightingAI);
  512. }
  513. //Don't wait for dialogs when we are non-active hot-seat player
  514. if (LOCPLINT == this)
  515. waitForAllDialogs();
  516. BATTLE_EVENT_POSSIBLE_RETURN;
  517. }
  518. void CPlayerInterface::battleUnitsChanged(const BattleID & battleID, const std::vector<UnitChanges> & units)
  519. {
  520. EVENT_HANDLER_CALLED_BY_CLIENT;
  521. BATTLE_EVENT_POSSIBLE_RETURN;
  522. for(auto & info : units)
  523. {
  524. switch(info.operation)
  525. {
  526. case UnitChanges::EOperation::RESET_STATE:
  527. {
  528. const CStack * stack = cb->getBattle(battleID)->battleGetStackByID(info.id );
  529. if(!stack)
  530. {
  531. logGlobal->error("Invalid unit ID %d", info.id);
  532. continue;
  533. }
  534. battleInt->stackReset(stack);
  535. }
  536. break;
  537. case UnitChanges::EOperation::REMOVE:
  538. battleInt->stackRemoved(info.id);
  539. break;
  540. case UnitChanges::EOperation::ADD:
  541. {
  542. const CStack * unit = cb->getBattle(battleID)->battleGetStackByID(info.id);
  543. if(!unit)
  544. {
  545. logGlobal->error("Invalid unit ID %d", info.id);
  546. continue;
  547. }
  548. battleInt->stackAdded(unit);
  549. }
  550. break;
  551. default:
  552. logGlobal->error("Unknown unit operation %d", (int)info.operation);
  553. break;
  554. }
  555. }
  556. }
  557. void CPlayerInterface::battleObstaclesChanged(const BattleID & battleID, const std::vector<ObstacleChanges> & obstacles)
  558. {
  559. EVENT_HANDLER_CALLED_BY_CLIENT;
  560. BATTLE_EVENT_POSSIBLE_RETURN;
  561. std::vector<std::shared_ptr<const CObstacleInstance>> newObstacles;
  562. std::vector<ObstacleChanges> removedObstacles;
  563. for(auto & change : obstacles)
  564. {
  565. if(change.operation == BattleChanges::EOperation::ADD)
  566. {
  567. auto instance = cb->getBattle(battleID)->battleGetObstacleByID(change.id);
  568. if(instance)
  569. newObstacles.push_back(instance);
  570. else
  571. logNetwork->error("Invalid obstacle instance %d", change.id);
  572. }
  573. if(change.operation == BattleChanges::EOperation::REMOVE)
  574. removedObstacles.push_back(change); //Obstacles are already removed, so, show animation based on json struct
  575. }
  576. if (!newObstacles.empty())
  577. battleInt->obstaclePlaced(newObstacles);
  578. if (!removedObstacles.empty())
  579. battleInt->obstacleRemoved(removedObstacles);
  580. battleInt->fieldController->redrawBackgroundWithHexes();
  581. }
  582. void CPlayerInterface::battleCatapultAttacked(const BattleID & battleID, const CatapultAttack & ca)
  583. {
  584. EVENT_HANDLER_CALLED_BY_CLIENT;
  585. BATTLE_EVENT_POSSIBLE_RETURN;
  586. battleInt->stackIsCatapulting(ca);
  587. }
  588. void CPlayerInterface::battleNewRound(const BattleID & battleID) //called at the beginning of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
  589. {
  590. EVENT_HANDLER_CALLED_BY_CLIENT;
  591. BATTLE_EVENT_POSSIBLE_RETURN;
  592. battleInt->newRound();
  593. }
  594. void CPlayerInterface::actionStarted(const BattleID & battleID, const BattleAction &action)
  595. {
  596. EVENT_HANDLER_CALLED_BY_CLIENT;
  597. BATTLE_EVENT_POSSIBLE_RETURN;
  598. battleInt->startAction(action);
  599. }
  600. void CPlayerInterface::actionFinished(const BattleID & battleID, const BattleAction &action)
  601. {
  602. EVENT_HANDLER_CALLED_BY_CLIENT;
  603. BATTLE_EVENT_POSSIBLE_RETURN;
  604. battleInt->endAction(action);
  605. }
  606. void CPlayerInterface::activeStack(const BattleID & battleID, const CStack * stack) //called when it's turn of that stack
  607. {
  608. EVENT_HANDLER_CALLED_BY_CLIENT;
  609. logGlobal->trace("Awaiting command for %s", stack->nodeName());
  610. assert(!cb->getBattle(battleID)->battleIsFinished());
  611. if (cb->getBattle(battleID)->battleIsFinished())
  612. {
  613. logGlobal->error("Received CPlayerInterface::activeStack after battle is finished!");
  614. cb->battleMakeUnitAction(battleID, BattleAction::makeDefend(stack));
  615. return ;
  616. }
  617. if (autofightingAI)
  618. {
  619. if (isAutoFightOn)
  620. {
  621. //FIXME: we want client rendering to proceed while AI is making actions
  622. // so unlock mutex while AI is busy since this might take quite a while, especially if hero has many spells
  623. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  624. autofightingAI->activeStack(battleID, stack);
  625. return;
  626. }
  627. cb->unregisterBattleInterface(autofightingAI);
  628. autofightingAI.reset();
  629. }
  630. assert(battleInt);
  631. if(!battleInt)
  632. {
  633. // probably battle is finished already
  634. cb->battleMakeUnitAction(battleID, BattleAction::makeDefend(stack));
  635. }
  636. battleInt->stackActivated(stack);
  637. }
  638. void CPlayerInterface::battleEnd(const BattleID & battleID, const BattleResult *br, QueryID queryID)
  639. {
  640. EVENT_HANDLER_CALLED_BY_CLIENT;
  641. if(isAutoFightOn || autofightingAI)
  642. {
  643. isAutoFightOn = false;
  644. cb->unregisterBattleInterface(autofightingAI);
  645. autofightingAI.reset();
  646. if(!battleInt)
  647. {
  648. bool allowManualReplay = queryID != QueryID::NONE;
  649. auto wnd = std::make_shared<BattleResultWindow>(*br, *this, allowManualReplay);
  650. if (allowManualReplay)
  651. {
  652. wnd->resultCallback = [=](ui32 selection)
  653. {
  654. cb->selectionMade(selection, queryID);
  655. };
  656. }
  657. GH.windows().pushWindow(wnd);
  658. // #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
  659. // Otherwise NewTurn causes freeze.
  660. waitWhileDialog();
  661. return;
  662. }
  663. }
  664. BATTLE_EVENT_POSSIBLE_RETURN;
  665. battleInt->battleFinished(*br, queryID);
  666. }
  667. void CPlayerInterface::battleLogMessage(const BattleID & battleID, const std::vector<MetaString> & lines)
  668. {
  669. EVENT_HANDLER_CALLED_BY_CLIENT;
  670. BATTLE_EVENT_POSSIBLE_RETURN;
  671. battleInt->displayBattleLog(lines);
  672. }
  673. void CPlayerInterface::battleStackMoved(const BattleID & battleID, const CStack * stack, std::vector<BattleHex> dest, int distance, bool teleport)
  674. {
  675. EVENT_HANDLER_CALLED_BY_CLIENT;
  676. BATTLE_EVENT_POSSIBLE_RETURN;
  677. battleInt->stackMoved(stack, dest, distance, teleport);
  678. }
  679. void CPlayerInterface::battleSpellCast(const BattleID & battleID, const BattleSpellCast * sc)
  680. {
  681. EVENT_HANDLER_CALLED_BY_CLIENT;
  682. BATTLE_EVENT_POSSIBLE_RETURN;
  683. battleInt->spellCast(sc);
  684. }
  685. void CPlayerInterface::battleStacksEffectsSet(const BattleID & battleID, const SetStackEffect & sse)
  686. {
  687. EVENT_HANDLER_CALLED_BY_CLIENT;
  688. BATTLE_EVENT_POSSIBLE_RETURN;
  689. battleInt->battleStacksEffectsSet(sse);
  690. }
  691. void CPlayerInterface::battleTriggerEffect(const BattleID & battleID, const BattleTriggerEffect & bte)
  692. {
  693. EVENT_HANDLER_CALLED_BY_CLIENT;
  694. BATTLE_EVENT_POSSIBLE_RETURN;
  695. battleInt->effectsController->battleTriggerEffect(bte);
  696. if(bte.effect == vstd::to_underlying(BonusType::MANA_DRAIN))
  697. {
  698. const CGHeroInstance * manaDrainedHero = LOCPLINT->cb->getHero(ObjectInstanceID(bte.additionalInfo));
  699. battleInt->windowObject->heroManaPointsChanged(manaDrainedHero);
  700. }
  701. }
  702. void CPlayerInterface::battleStacksAttacked(const BattleID & battleID, const std::vector<BattleStackAttacked> & bsa, bool ranged)
  703. {
  704. EVENT_HANDLER_CALLED_BY_CLIENT;
  705. BATTLE_EVENT_POSSIBLE_RETURN;
  706. std::vector<StackAttackedInfo> arg;
  707. for(auto & elem : bsa)
  708. {
  709. const CStack * defender = cb->getBattle(battleID)->battleGetStackByID(elem.stackAttacked, false);
  710. const CStack * attacker = cb->getBattle(battleID)->battleGetStackByID(elem.attackerID, false);
  711. assert(defender);
  712. StackAttackedInfo info;
  713. info.defender = defender;
  714. info.attacker = attacker;
  715. info.damageDealt = elem.damageAmount;
  716. info.amountKilled = elem.killedAmount;
  717. info.spellEffect = SpellID::NONE;
  718. info.indirectAttack = ranged;
  719. info.killed = elem.killed();
  720. info.rebirth = elem.willRebirth();
  721. info.cloneKilled = elem.cloneKilled();
  722. info.fireShield = elem.fireShield();
  723. if (elem.isSpell())
  724. info.spellEffect = elem.spellID;
  725. arg.push_back(info);
  726. }
  727. battleInt->stacksAreAttacked(arg);
  728. }
  729. void CPlayerInterface::battleAttack(const BattleID & battleID, const BattleAttack * ba)
  730. {
  731. EVENT_HANDLER_CALLED_BY_CLIENT;
  732. BATTLE_EVENT_POSSIBLE_RETURN;
  733. StackAttackInfo info;
  734. info.attacker = cb->getBattle(battleID)->battleGetStackByID(ba->stackAttacking);
  735. info.defender = nullptr;
  736. info.indirectAttack = ba->shot();
  737. info.lucky = ba->lucky();
  738. info.unlucky = ba->unlucky();
  739. info.deathBlow = ba->deathBlow();
  740. info.lifeDrain = ba->lifeDrain();
  741. info.tile = ba->tile;
  742. info.spellEffect = SpellID::NONE;
  743. if (ba->spellLike())
  744. info.spellEffect = ba->spellID;
  745. for(auto & elem : ba->bsa)
  746. {
  747. if(!elem.isSecondary())
  748. {
  749. assert(info.defender == nullptr);
  750. info.defender = cb->getBattle(battleID)->battleGetStackByID(elem.stackAttacked);
  751. }
  752. else
  753. {
  754. info.secondaryDefender.push_back(cb->getBattle(battleID)->battleGetStackByID(elem.stackAttacked));
  755. }
  756. }
  757. assert(info.defender != nullptr);
  758. assert(info.attacker != nullptr);
  759. battleInt->stackAttacking(info);
  760. }
  761. void CPlayerInterface::battleGateStateChanged(const BattleID & battleID, const EGateState state)
  762. {
  763. EVENT_HANDLER_CALLED_BY_CLIENT;
  764. BATTLE_EVENT_POSSIBLE_RETURN;
  765. battleInt->gateStateChanged(state);
  766. }
  767. void CPlayerInterface::yourTacticPhase(const BattleID & battleID, int distance)
  768. {
  769. EVENT_HANDLER_CALLED_BY_CLIENT;
  770. }
  771. void CPlayerInterface::showInfoDialog(EInfoWindowMode type, const std::string &text, const std::vector<Component> & components, int soundID)
  772. {
  773. EVENT_HANDLER_CALLED_BY_CLIENT;
  774. bool autoTryHover = settings["gameTweaks"]["infoBarPick"].Bool() && type == EInfoWindowMode::AUTO;
  775. auto timer = type == EInfoWindowMode::INFO ? 3000 : 4500; //Implement long info windows like in HD mod
  776. if(autoTryHover || type == EInfoWindowMode::INFO)
  777. {
  778. waitWhileDialog(); //Fix for mantis #98
  779. adventureInt->showInfoBoxMessage(components, text, timer);
  780. // abort movement, if any. Strictly speaking unnecessary, but prevents some edge cases, like movement sound on visiting Magi Hut with "show messages in status window" on
  781. movementController->requestMovementAbort();
  782. if (makingTurn && GH.windows().count() > 0 && LOCPLINT == this)
  783. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  784. return;
  785. }
  786. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  787. {
  788. return;
  789. }
  790. std::vector<Component> vect = components; //I do not know currently how to avoid copy here
  791. do
  792. {
  793. std::vector<Component> sender = {vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8))};
  794. std::vector<std::shared_ptr<CComponent>> intComps;
  795. for (auto & component : sender)
  796. intComps.push_back(std::make_shared<CComponent>(component));
  797. showInfoDialog(text,intComps,soundID);
  798. vect.erase(vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8)));
  799. }
  800. while(!vect.empty());
  801. }
  802. void CPlayerInterface::showInfoDialog(const std::string & text, std::shared_ptr<CComponent> component)
  803. {
  804. std::vector<std::shared_ptr<CComponent>> intComps;
  805. intComps.push_back(component);
  806. showInfoDialog(text, intComps, soundBase::sound_todo);
  807. }
  808. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<std::shared_ptr<CComponent>> & components, int soundID)
  809. {
  810. LOG_TRACE_PARAMS(logGlobal, "player=%s, text=%s, is LOCPLINT=%d", playerID % text % (this==LOCPLINT));
  811. waitWhileDialog();
  812. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  813. {
  814. return;
  815. }
  816. std::shared_ptr<CInfoWindow> temp = CInfoWindow::create(text, playerID, components);
  817. if (makingTurn && GH.windows().count() > 0 && LOCPLINT == this)
  818. {
  819. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  820. showingDialog->set(true);
  821. movementController->requestMovementAbort(); // interrupt movement to show dialog
  822. GH.windows().pushWindow(temp);
  823. }
  824. else
  825. {
  826. dialogs.push_back(temp);
  827. }
  828. }
  829. void CPlayerInterface::showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text)
  830. {
  831. EVENT_HANDLER_CALLED_BY_CLIENT;
  832. std::string str = text.toString();
  833. showInfoDialog(EInfoWindowMode::MODAL, str, components, 0);
  834. waitWhileDialog();
  835. }
  836. void CPlayerInterface::showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, const std::vector<std::shared_ptr<CComponent>> & components)
  837. {
  838. movementController->requestMovementAbort();
  839. LOCPLINT->showingDialog->setn(true);
  840. CInfoWindow::showYesNoDialog(text, components, onYes, onNo, playerID);
  841. }
  842. void CPlayerInterface::showBlockingDialog( const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel )
  843. {
  844. EVENT_HANDLER_CALLED_BY_CLIENT;
  845. waitWhileDialog();
  846. movementController->requestMovementAbort();
  847. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  848. if (!selection && cancel) //simple yes/no dialog
  849. {
  850. std::vector<std::shared_ptr<CComponent>> intComps;
  851. for (auto & component : components)
  852. intComps.push_back(std::make_shared<CComponent>(component)); //will be deleted by close in window
  853. showYesNoDialog(text, [=](){ cb->selectionMade(1, askID); }, [=](){ cb->selectionMade(0, askID); }, intComps);
  854. }
  855. else if (selection)
  856. {
  857. std::vector<std::shared_ptr<CSelectableComponent>> intComps;
  858. for (auto & component : components)
  859. intComps.push_back(std::make_shared<CSelectableComponent>(component)); //will be deleted by CSelWindow::close
  860. std::vector<std::pair<AnimationPath,CFunctionList<void()> > > pom;
  861. pom.push_back({ AnimationPath::builtin("IOKAY.DEF"),0});
  862. if (cancel)
  863. {
  864. pom.push_back({AnimationPath::builtin("ICANCEL.DEF"),0});
  865. }
  866. int charperline = 35;
  867. if (pom.size() > 1)
  868. charperline = 50;
  869. GH.windows().createAndPushWindow<CSelWindow>(text, playerID, charperline, intComps, pom, askID);
  870. intComps[0]->clickPressed(GH.getCursorPosition());
  871. intComps[0]->clickReleased(GH.getCursorPosition());
  872. }
  873. }
  874. void CPlayerInterface::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  875. {
  876. EVENT_HANDLER_CALLED_BY_CLIENT;
  877. movementController->showTeleportDialog(hero, channel, exits, impassable, askID);
  878. }
  879. void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  880. {
  881. EVENT_HANDLER_CALLED_BY_CLIENT;
  882. auto selectCallback = [=](int selection)
  883. {
  884. cb->sendQueryReply(selection, askID);
  885. };
  886. auto cancelCallback = [=]()
  887. {
  888. cb->sendQueryReply(std::nullopt, askID);
  889. };
  890. const std::string localTitle = title.toString();
  891. const std::string localDescription = description.toString();
  892. std::vector<int> tempList;
  893. tempList.reserve(objects.size());
  894. for(auto item : objects)
  895. tempList.push_back(item.getNum());
  896. CComponent localIconC(icon);
  897. std::shared_ptr<CIntObject> localIcon = localIconC.image;
  898. localIconC.removeChild(localIcon.get(), false);
  899. std::shared_ptr<CObjectListWindow> wnd = std::make_shared<CObjectListWindow>(tempList, localIcon, localTitle, localDescription, selectCallback);
  900. wnd->onExit = cancelCallback;
  901. GH.windows().pushWindow(wnd);
  902. }
  903. void CPlayerInterface::tileRevealed(const std::unordered_set<int3> &pos)
  904. {
  905. EVENT_HANDLER_CALLED_BY_CLIENT;
  906. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  907. adventureInt->onMapTilesChanged(pos);
  908. }
  909. void CPlayerInterface::tileHidden(const std::unordered_set<int3> &pos)
  910. {
  911. EVENT_HANDLER_CALLED_BY_CLIENT;
  912. adventureInt->onMapTilesChanged(pos);
  913. }
  914. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  915. {
  916. GH.windows().createAndPushWindow<CHeroWindow>(hero);
  917. }
  918. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  919. {
  920. EVENT_HANDLER_CALLED_BY_CLIENT;
  921. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  922. {
  923. for (auto fortScreen : GH.windows().findWindows<CFortScreen>())
  924. fortScreen->creaturesChangedEventHandler();
  925. for (auto castleInterface : GH.windows().findWindows<CCastleInterface>())
  926. if(castleInterface->town == town)
  927. castleInterface->creaturesChangedEventHandler();
  928. if (townObj)
  929. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  930. ki->townChanged(townObj);
  931. }
  932. else if(town && GH.windows().count() > 0 && (town->ID == Obj::CREATURE_GENERATOR1
  933. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  934. {
  935. for (auto crw : GH.windows().findWindows<CRecruitmentWindow>())
  936. if (crw->dwelling == town)
  937. crw->availableCreaturesChanged();
  938. }
  939. }
  940. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  941. {
  942. EVENT_HANDLER_CALLED_BY_CLIENT;
  943. if (bonus.type == BonusType::NONE)
  944. return;
  945. adventureInt->onHeroChanged(hero);
  946. if ((bonus.type == BonusType::FLYING_MOVEMENT || bonus.type == BonusType::WATER_WALKING) && !gain)
  947. {
  948. //recalculate paths because hero has lost bonus influencing pathfinding
  949. localState->erasePath(hero);
  950. }
  951. }
  952. void CPlayerInterface::saveGame( BinarySerializer & h, const int version )
  953. {
  954. EVENT_HANDLER_CALLED_BY_CLIENT;
  955. localState->serialize(h, version);
  956. }
  957. void CPlayerInterface::loadGame( BinaryDeserializer & h, const int version )
  958. {
  959. EVENT_HANDLER_CALLED_BY_CLIENT;
  960. localState->serialize(h, version);
  961. firstCall = -1;
  962. }
  963. void CPlayerInterface::moveHero( const CGHeroInstance *h, const CGPath& path )
  964. {
  965. assert(LOCPLINT->makingTurn);
  966. assert(h);
  967. assert(!showingDialog->get());
  968. assert(dialogs.empty());
  969. LOG_TRACE(logGlobal);
  970. if (!LOCPLINT->makingTurn)
  971. return;
  972. if (!h)
  973. return; //can't find hero
  974. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  975. if (showingDialog->get() || !dialogs.empty())
  976. return;
  977. if (localState->isHeroSleeping(h))
  978. localState->setHeroAwaken(h);
  979. movementController->requestMovementStart(h, path);
  980. }
  981. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  982. {
  983. EVENT_HANDLER_CALLED_BY_CLIENT;
  984. auto onEnd = [=](){ cb->selectionMade(0, queryID); };
  985. if (movementController->isHeroMovingThroughGarrison(down, up))
  986. {
  987. onEnd();
  988. return;
  989. }
  990. waitForAllDialogs();
  991. auto cgw = std::make_shared<CGarrisonWindow>(up, down, removableUnits);
  992. cgw->quit->addCallback(onEnd);
  993. GH.windows().pushWindow(cgw);
  994. }
  995. /**
  996. * Shows the dialog that appears when right-clicking an artifact that can be assembled
  997. * into a combinational one on an artifact screen. Does not require the combination of
  998. * artifacts to be legal.
  999. */
  1000. void CPlayerInterface::showArtifactAssemblyDialog(const Artifact * artifact, const Artifact * assembledArtifact, CFunctionList<void()> onYes)
  1001. {
  1002. std::string text = artifact->getDescriptionTranslated();
  1003. text += "\n\n";
  1004. std::vector<std::shared_ptr<CComponent>> scs;
  1005. if(assembledArtifact)
  1006. {
  1007. // You possess all of the components to...
  1008. text += boost::str(boost::format(CGI->generaltexth->allTexts[732]) % assembledArtifact->getNameTranslated());
  1009. // Picture of assembled artifact at bottom.
  1010. auto sc = std::make_shared<CComponent>(ComponentType::ARTIFACT, assembledArtifact->getId());
  1011. scs.push_back(sc);
  1012. }
  1013. else
  1014. {
  1015. // Do you wish to disassemble this artifact?
  1016. text += CGI->generaltexth->allTexts[733];
  1017. }
  1018. showYesNoDialog(text, onYes, nullptr, scs);
  1019. }
  1020. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1021. {
  1022. if(pa->packType == CTypeList::getInstance().getTypeID<MoveHero>(nullptr))
  1023. movementController->onMoveHeroApplied();
  1024. if(pa->packType == CTypeList::getInstance().getTypeID<QueryReply>(nullptr))
  1025. movementController->onQueryReplyApplied();
  1026. }
  1027. void CPlayerInterface::showHeroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  1028. {
  1029. heroExchangeStarted(hero1, hero2, QueryID(-1));
  1030. }
  1031. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1032. {
  1033. EVENT_HANDLER_CALLED_BY_CLIENT;
  1034. GH.windows().createAndPushWindow<CExchangeWindow>(hero1, hero2, query);
  1035. }
  1036. void CPlayerInterface::beforeObjectPropertyChanged(const SetObjectProperty * sop)
  1037. {
  1038. if (sop->what == ObjProperty::OWNER)
  1039. {
  1040. const CGObjectInstance * obj = cb->getObj(sop->id);
  1041. if(obj->ID == Obj::TOWN)
  1042. {
  1043. auto town = static_cast<const CGTownInstance *>(obj);
  1044. if(obj->tempOwner == playerID)
  1045. {
  1046. localState->removeOwnedTown(town);
  1047. adventureInt->onTownChanged(town);
  1048. }
  1049. }
  1050. }
  1051. }
  1052. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1053. {
  1054. EVENT_HANDLER_CALLED_BY_CLIENT;
  1055. if (sop->what == ObjProperty::OWNER)
  1056. {
  1057. const CGObjectInstance * obj = cb->getObj(sop->id);
  1058. if(obj->ID == Obj::TOWN)
  1059. {
  1060. auto town = static_cast<const CGTownInstance *>(obj);
  1061. if(obj->tempOwner == playerID)
  1062. {
  1063. localState->addOwnedTown(town);
  1064. adventureInt->onTownChanged(town);
  1065. }
  1066. }
  1067. //redraw minimap if owner changed
  1068. std::set<int3> pos = obj->getBlockedPos();
  1069. std::unordered_set<int3> upos(pos.begin(), pos.end());
  1070. adventureInt->onMapTilesChanged(upos);
  1071. assert(cb->getTownsInfo().size() == localState->getOwnedTowns().size());
  1072. }
  1073. }
  1074. void CPlayerInterface::initializeHeroTownList()
  1075. {
  1076. if(localState->getWanderingHeroes().empty())
  1077. {
  1078. for(auto & hero : cb->getHeroesInfo())
  1079. {
  1080. if(!hero->inTownGarrison)
  1081. localState->addWanderingHero(hero);
  1082. }
  1083. }
  1084. if(localState->getOwnedTowns().empty())
  1085. {
  1086. for(auto & town : cb->getTownsInfo())
  1087. localState->addOwnedTown(town);
  1088. }
  1089. if(adventureInt)
  1090. adventureInt->onHeroChanged(nullptr);
  1091. }
  1092. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level, QueryID queryID)
  1093. {
  1094. EVENT_HANDLER_CALLED_BY_CLIENT;
  1095. waitWhileDialog();
  1096. auto recruitCb = [=](CreatureID id, int count)
  1097. {
  1098. cb->recruitCreatures(dwelling, dst, id, count, -1);
  1099. };
  1100. auto closeCb = [=]()
  1101. {
  1102. cb->selectionMade(0, queryID);
  1103. };
  1104. GH.windows().createAndPushWindow<CRecruitmentWindow>(dwelling, level, dst, recruitCb, closeCb);
  1105. }
  1106. void CPlayerInterface::waitWhileDialog()
  1107. {
  1108. if (GH.amIGuiThread())
  1109. {
  1110. logGlobal->warn("Cannot wait for dialogs in gui thread (deadlock risk)!");
  1111. return;
  1112. }
  1113. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  1114. boost::unique_lock<boost::mutex> un(showingDialog->mx);
  1115. while(showingDialog->data)
  1116. showingDialog->cond.wait(un);
  1117. }
  1118. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1119. {
  1120. EVENT_HANDLER_CALLED_BY_CLIENT;
  1121. auto state = obj->shipyardStatus();
  1122. TResources cost;
  1123. obj->getBoatCost(cost);
  1124. GH.windows().createAndPushWindow<CShipyardWindow>(cost, state, obj->getBoatType(), [=](){ cb->buildBoat(obj); });
  1125. }
  1126. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1127. {
  1128. EVENT_HANDLER_CALLED_BY_CLIENT;
  1129. //we might have built a boat in shipyard in opened town screen
  1130. if (obj->ID == Obj::BOAT
  1131. && LOCPLINT->castleInt
  1132. && obj->visitablePos() == LOCPLINT->castleInt->town->bestLocation())
  1133. {
  1134. CCS->soundh->playSound(soundBase::newBuilding);
  1135. LOCPLINT->castleInt->addBuilding(BuildingID::SHIP);
  1136. }
  1137. }
  1138. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1139. {
  1140. EVENT_HANDLER_CALLED_BY_CLIENT;
  1141. waitWhileDialog();
  1142. CCS->curh->hide();
  1143. adventureInt->centerOnTile(pos);
  1144. if (focusTime)
  1145. {
  1146. GH.windows().totalRedraw();
  1147. {
  1148. IgnoreEvents ignore(*this);
  1149. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  1150. boost::this_thread::sleep_for(boost::chrono::milliseconds(focusTime));
  1151. }
  1152. }
  1153. CCS->curh->show();
  1154. }
  1155. void CPlayerInterface::objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator)
  1156. {
  1157. EVENT_HANDLER_CALLED_BY_CLIENT;
  1158. if(playerID == initiator && obj->getRemovalSound())
  1159. {
  1160. waitWhileDialog();
  1161. CCS->soundh->playSound(obj->getRemovalSound().value());
  1162. }
  1163. CGI->mh->waitForOngoingAnimations();
  1164. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1165. {
  1166. const CGHeroInstance * h = static_cast<const CGHeroInstance *>(obj);
  1167. heroKilled(h);
  1168. }
  1169. GH.fakeMouseMove();
  1170. }
  1171. void CPlayerInterface::objectRemovedAfter()
  1172. {
  1173. EVENT_HANDLER_CALLED_BY_CLIENT;
  1174. adventureInt->onMapTilesChanged(boost::none);
  1175. // visiting or garrisoned hero removed - update window
  1176. if (castleInt)
  1177. castleInt->updateGarrisons();
  1178. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  1179. ki->heroRemoved();
  1180. }
  1181. void CPlayerInterface::playerBlocked(int reason, bool start)
  1182. {
  1183. if(reason == PlayerBlocked::EReason::UPCOMING_BATTLE)
  1184. {
  1185. if(CSH->howManyPlayerInterfaces() > 1 && LOCPLINT != this && LOCPLINT->makingTurn == false)
  1186. {
  1187. //one of our players who isn't last in order got attacked not by our another player (happens for example in hotseat mode)
  1188. LOCPLINT = this;
  1189. GH.curInt = this;
  1190. adventureInt->onCurrentPlayerChanged(playerID);
  1191. std::string msg = CGI->generaltexth->translate("vcmi.adventureMap.playerAttacked");
  1192. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  1193. std::vector<std::shared_ptr<CComponent>> cmp;
  1194. cmp.push_back(std::make_shared<CComponent>(ComponentType::FLAG, playerID));
  1195. makingTurn = true; //workaround for stiff showInfoDialog implementation
  1196. showInfoDialog(msg, cmp);
  1197. makingTurn = false;
  1198. }
  1199. }
  1200. }
  1201. void CPlayerInterface::update()
  1202. {
  1203. // Make sure that gamestate won't change when GUI objects may obtain its parts on event processing or drawing request
  1204. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  1205. // While mutexes were locked away we may be have stopped being the active interface
  1206. if (LOCPLINT != this)
  1207. return;
  1208. //if there are any waiting dialogs, show them
  1209. if ((CSH->howManyPlayerInterfaces() <= 1 || makingTurn) && !dialogs.empty() && !showingDialog->get())
  1210. {
  1211. showingDialog->set(true);
  1212. GH.windows().pushWindow(dialogs.front());
  1213. dialogs.pop_front();
  1214. }
  1215. assert(adventureInt);
  1216. // Handles mouse and key input
  1217. GH.handleEvents();
  1218. GH.windows().simpleRedraw();
  1219. }
  1220. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1221. {
  1222. using namespace boost::filesystem;
  1223. using namespace boost::algorithm;
  1224. path gamesDir = VCMIDirs::get().userSavePath();
  1225. std::map<std::time_t, int> dates; //save number => datestamp
  1226. const directory_iterator enddir;
  1227. if (!exists(gamesDir))
  1228. create_directory(gamesDir);
  1229. else
  1230. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1231. {
  1232. if (is_regular_file(dir->status()))
  1233. {
  1234. std::string name = dir->path().filename().string();
  1235. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1236. {
  1237. char nr = name[namePrefix.size()];
  1238. if (std::isdigit(nr))
  1239. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1240. }
  1241. }
  1242. }
  1243. if (!dates.empty())
  1244. return (--dates.end())->second; //return latest file number
  1245. return 0;
  1246. }
  1247. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1248. {
  1249. EVENT_HANDLER_CALLED_BY_CLIENT;
  1250. if (player == playerID)
  1251. {
  1252. if (victoryLossCheckResult.loss())
  1253. showInfoDialog(CGI->generaltexth->allTexts[95]);
  1254. assert(GH.curInt == LOCPLINT);
  1255. auto previousInterface = LOCPLINT; //without multiple player interfaces some of lines below are useless, but for hotseat we wanna swap player interface temporarily
  1256. LOCPLINT = this; //this is needed for dialog to show and avoid freeze, dialog showing logic should be reworked someday
  1257. GH.curInt = this; //waiting for dialogs requires this to get events
  1258. if(!makingTurn)
  1259. {
  1260. makingTurn = true; //also needed for dialog to show with current implementation
  1261. waitForAllDialogs();
  1262. makingTurn = false;
  1263. }
  1264. else
  1265. waitForAllDialogs();
  1266. GH.curInt = previousInterface;
  1267. LOCPLINT = previousInterface;
  1268. if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool()) //all human players eliminated
  1269. {
  1270. if(adventureInt)
  1271. {
  1272. GH.windows().popWindows(GH.windows().count());
  1273. adventureInt.reset();
  1274. }
  1275. }
  1276. if (victoryLossCheckResult.victory() && LOCPLINT == this)
  1277. {
  1278. // end game if current human player has won
  1279. CSH->sendClientDisconnecting();
  1280. requestReturningToMainMenu(true);
  1281. }
  1282. else if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool())
  1283. {
  1284. //all human players eliminated
  1285. CSH->sendClientDisconnecting();
  1286. requestReturningToMainMenu(false);
  1287. }
  1288. if (GH.curInt == this)
  1289. GH.curInt = nullptr;
  1290. }
  1291. }
  1292. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1293. {
  1294. EVENT_HANDLER_CALLED_BY_CLIENT;
  1295. }
  1296. void CPlayerInterface::showPuzzleMap()
  1297. {
  1298. EVENT_HANDLER_CALLED_BY_CLIENT;
  1299. waitWhileDialog();
  1300. //TODO: interface should not know the real position of Grail...
  1301. double ratio = 0;
  1302. int3 grailPos = cb->getGrailPos(&ratio);
  1303. GH.windows().createAndPushWindow<CPuzzleWindow>(grailPos, ratio);
  1304. }
  1305. void CPlayerInterface::viewWorldMap()
  1306. {
  1307. adventureInt->openWorldView();
  1308. }
  1309. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, SpellID spellID)
  1310. {
  1311. EVENT_HANDLER_CALLED_BY_CLIENT;
  1312. if(GH.windows().topWindow<CSpellWindow>())
  1313. GH.windows().popWindows(1);
  1314. if(spellID == SpellID::FLY || spellID == SpellID::WATER_WALK)
  1315. localState->erasePath(caster);
  1316. auto castSoundPath = spellID.toSpell()->getCastSound();
  1317. if(!castSoundPath.empty())
  1318. CCS->soundh->playSound(castSoundPath);
  1319. }
  1320. void CPlayerInterface::tryDigging(const CGHeroInstance * h)
  1321. {
  1322. int msgToShow = -1;
  1323. const auto diggingStatus = h->diggingStatus();
  1324. switch(diggingStatus)
  1325. {
  1326. case EDiggingStatus::CAN_DIG:
  1327. break;
  1328. case EDiggingStatus::LACK_OF_MOVEMENT:
  1329. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  1330. break;
  1331. case EDiggingStatus::TILE_OCCUPIED:
  1332. msgToShow = 97; //Try searching on clear ground.
  1333. break;
  1334. case EDiggingStatus::WRONG_TERRAIN:
  1335. msgToShow = 60; ////Try looking on land!
  1336. break;
  1337. case EDiggingStatus::BACKPACK_IS_FULL:
  1338. msgToShow = 247; //Searching for the Grail is fruitless...
  1339. break;
  1340. default:
  1341. assert(0);
  1342. }
  1343. if(msgToShow < 0)
  1344. cb->dig(h);
  1345. else
  1346. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  1347. }
  1348. void CPlayerInterface::battleNewRoundFirst(const BattleID & battleID)
  1349. {
  1350. EVENT_HANDLER_CALLED_BY_CLIENT;
  1351. BATTLE_EVENT_POSSIBLE_RETURN;
  1352. battleInt->newRoundFirst();
  1353. }
  1354. void CPlayerInterface::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor, QueryID queryID)
  1355. {
  1356. EVENT_HANDLER_CALLED_BY_CLIENT;
  1357. auto onWindowClosed = [this, queryID](){
  1358. cb->selectionMade(0, queryID);
  1359. };
  1360. if(market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  1361. GH.windows().createAndPushWindow<CAltarWindow>(market, visitor, onWindowClosed, EMarketMode::ARTIFACT_EXP);
  1362. else if(market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  1363. GH.windows().createAndPushWindow<CAltarWindow>(market, visitor, onWindowClosed, EMarketMode::CREATURE_EXP);
  1364. else if(market->allowsTrade(EMarketMode::CREATURE_UNDEAD))
  1365. GH.windows().createAndPushWindow<CTransformerWindow>(market, visitor, onWindowClosed);
  1366. else if(!market->availableModes().empty())
  1367. GH.windows().createAndPushWindow<CMarketplaceWindow>(market, visitor, onWindowClosed, market->availableModes().front());
  1368. }
  1369. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor, QueryID queryID)
  1370. {
  1371. EVENT_HANDLER_CALLED_BY_CLIENT;
  1372. auto onWindowClosed = [this, queryID](){
  1373. cb->selectionMade(0, queryID);
  1374. };
  1375. GH.windows().createAndPushWindow<CUniversityWindow>(visitor, market, onWindowClosed);
  1376. }
  1377. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  1378. {
  1379. EVENT_HANDLER_CALLED_BY_CLIENT;
  1380. GH.windows().createAndPushWindow<CHillFortWindow>(visitor, object);
  1381. }
  1382. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket * bm)
  1383. {
  1384. EVENT_HANDLER_CALLED_BY_CLIENT;
  1385. for (auto cmw : GH.windows().findWindows<CMarketplaceWindow>())
  1386. cmw->artifactsChanged(false);
  1387. }
  1388. void CPlayerInterface::showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID)
  1389. {
  1390. EVENT_HANDLER_CALLED_BY_CLIENT;
  1391. auto onWindowClosed = [this, queryID](){
  1392. cb->selectionMade(0, queryID);
  1393. };
  1394. GH.windows().createAndPushWindow<CTavernWindow>(object, onWindowClosed);
  1395. }
  1396. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  1397. {
  1398. EVENT_HANDLER_CALLED_BY_CLIENT;
  1399. GH.windows().createAndPushWindow<CThievesGuildWindow>(obj);
  1400. }
  1401. void CPlayerInterface::showQuestLog()
  1402. {
  1403. EVENT_HANDLER_CALLED_BY_CLIENT;
  1404. GH.windows().createAndPushWindow<CQuestLog>(LOCPLINT->cb->getMyQuests());
  1405. }
  1406. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  1407. {
  1408. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  1409. {
  1410. MetaString txt;
  1411. obj->getProblemText(txt);
  1412. showInfoDialog(txt.toString());
  1413. }
  1414. else
  1415. showShipyardDialog(obj);
  1416. }
  1417. void CPlayerInterface::requestReturningToMainMenu(bool won)
  1418. {
  1419. HighScoreParameter param;
  1420. param.difficulty = cb->getStartInfo()->difficulty;
  1421. param.day = cb->getDate();
  1422. param.townAmount = cb->howManyTowns();
  1423. param.usedCheat = cb->getPlayerState(*cb->getPlayerID())->cheated;
  1424. param.hasGrail = false;
  1425. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1426. if(h->hasArt(ArtifactID::GRAIL))
  1427. param.hasGrail = true;
  1428. for(const CGTownInstance * t : cb->getTownsInfo())
  1429. if(t->builtBuildings.count(BuildingID::GRAIL))
  1430. param.hasGrail = true;
  1431. param.allDefeated = true;
  1432. for (PlayerColor player(0); player < PlayerColor::PLAYER_LIMIT; ++player)
  1433. {
  1434. auto ps = cb->getPlayerState(player, false);
  1435. if(ps && player != *cb->getPlayerID())
  1436. if(!ps->checkVanquished())
  1437. param.allDefeated = false;
  1438. }
  1439. param.scenarioName = cb->getMapHeader()->name.toString();
  1440. param.playerName = cb->getStartInfo()->playerInfos.find(*cb->getPlayerID())->second.name;
  1441. HighScoreCalculation highScoreCalc;
  1442. highScoreCalc.parameters.push_back(param);
  1443. highScoreCalc.isCampaign = false;
  1444. if(won && cb->getStartInfo()->campState)
  1445. CSH->startCampaignScenario(param, cb->getStartInfo()->campState);
  1446. else
  1447. {
  1448. GH.dispatchMainThread(
  1449. [won, highScoreCalc]()
  1450. {
  1451. CSH->endGameplay();
  1452. GH.defActionsDef = 63;
  1453. CMM->menu->switchToTab("main");
  1454. GH.windows().createAndPushWindow<CHighScoreInputScreen>(won, highScoreCalc);
  1455. }
  1456. );
  1457. }
  1458. }
  1459. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  1460. {
  1461. if(auto hero = cb->getHero(al.artHolder))
  1462. {
  1463. auto art = hero->getArt(al.slot);
  1464. if(art == nullptr)
  1465. {
  1466. logGlobal->error("artifact location %d points to nothing",
  1467. al.slot.num);
  1468. return;
  1469. }
  1470. ArtifactUtilsClient::askToAssemble(hero, al.slot);
  1471. }
  1472. }
  1473. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  1474. {
  1475. EVENT_HANDLER_CALLED_BY_CLIENT;
  1476. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1477. }
  1478. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  1479. {
  1480. EVENT_HANDLER_CALLED_BY_CLIENT;
  1481. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1482. for(auto artWin : GH.windows().findWindows<CArtifactHolder>())
  1483. artWin->artifactRemoved(al);
  1484. waitWhileDialog();
  1485. }
  1486. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1487. {
  1488. EVENT_HANDLER_CALLED_BY_CLIENT;
  1489. adventureInt->onHeroChanged(cb->getHero(dst.artHolder));
  1490. bool redraw = true;
  1491. // If a bulk transfer has arrived, then redrawing only the last art movement.
  1492. if(numOfMovedArts != 0)
  1493. {
  1494. numOfMovedArts--;
  1495. if(numOfMovedArts != 0)
  1496. redraw = false;
  1497. }
  1498. for(auto artWin : GH.windows().findWindows<CArtifactHolder>())
  1499. artWin->artifactMoved(src, dst, redraw);
  1500. waitWhileDialog();
  1501. }
  1502. void CPlayerInterface::bulkArtMovementStart(size_t numOfArts)
  1503. {
  1504. numOfMovedArts = numOfArts;
  1505. }
  1506. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1507. {
  1508. EVENT_HANDLER_CALLED_BY_CLIENT;
  1509. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1510. for(auto artWin : GH.windows().findWindows<CArtifactHolder>())
  1511. artWin->artifactAssembled(al);
  1512. }
  1513. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1514. {
  1515. EVENT_HANDLER_CALLED_BY_CLIENT;
  1516. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1517. for(auto artWin : GH.windows().findWindows<CArtifactHolder>())
  1518. artWin->artifactDisassembled(al);
  1519. }
  1520. void CPlayerInterface::waitForAllDialogs()
  1521. {
  1522. while(!dialogs.empty())
  1523. {
  1524. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  1525. boost::this_thread::sleep_for(boost::chrono::milliseconds(5));
  1526. }
  1527. waitWhileDialog();
  1528. }
  1529. void CPlayerInterface::proposeLoadingGame()
  1530. {
  1531. showYesNoDialog(
  1532. CGI->generaltexth->allTexts[68],
  1533. []()
  1534. {
  1535. GH.dispatchMainThread(
  1536. []()
  1537. {
  1538. CSH->endGameplay();
  1539. GH.defActionsDef = 63;
  1540. CMM->menu->switchToTab("load");
  1541. }
  1542. );
  1543. },
  1544. nullptr
  1545. );
  1546. }
  1547. bool CPlayerInterface::capturedAllEvents()
  1548. {
  1549. if(movementController->isHeroMoving())
  1550. {
  1551. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  1552. return true;
  1553. }
  1554. bool needToLockAdventureMap = adventureInt && adventureInt->isActive() && CGI->mh->hasOngoingAnimations();
  1555. bool quickCombatOngoing = isAutoFightOn && !battleInt;
  1556. if (ignoreEvents || needToLockAdventureMap || quickCombatOngoing )
  1557. {
  1558. GH.input().ignoreEventsUntilInput();
  1559. return true;
  1560. }
  1561. return false;
  1562. }
  1563. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions, bool showTerrain)
  1564. {
  1565. EVENT_HANDLER_CALLED_BY_CLIENT;
  1566. adventureInt->openWorldView(objectPositions, showTerrain );
  1567. }
  1568. std::optional<BattleAction> CPlayerInterface::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  1569. {
  1570. return std::nullopt;
  1571. }