CPlayerInterface.cpp 52 KB

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