CPlayerInterface.cpp 54 KB

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