CPlayerInterface.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  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, bool safeToAutoaccept)
  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. if(settings["general"]["enableUiEnhancements"].Bool() && safeToAutoaccept)
  854. {
  855. cb->selectionMade(1, askID); //as in HD mod, we try to skip dialogs that server considers visual fluff which does not affect gamestate
  856. return;
  857. }
  858. std::vector<std::shared_ptr<CComponent>> intComps;
  859. for (auto & component : components)
  860. intComps.push_back(std::make_shared<CComponent>(component)); //will be deleted by close in window
  861. showYesNoDialog(text, [=](){ cb->selectionMade(1, askID); }, [=](){ cb->selectionMade(0, askID); }, intComps);
  862. }
  863. else if (selection)
  864. {
  865. std::vector<std::shared_ptr<CSelectableComponent>> intComps;
  866. for (auto & component : components)
  867. intComps.push_back(std::make_shared<CSelectableComponent>(component)); //will be deleted by CSelWindow::close
  868. std::vector<std::pair<AnimationPath,CFunctionList<void()> > > pom;
  869. pom.push_back({ AnimationPath::builtin("IOKAY.DEF"),0});
  870. if (cancel)
  871. {
  872. pom.push_back({AnimationPath::builtin("ICANCEL.DEF"),0});
  873. }
  874. int charperline = 35;
  875. if (pom.size() > 1)
  876. charperline = 50;
  877. GH.windows().createAndPushWindow<CSelWindow>(text, playerID, charperline, intComps, pom, askID);
  878. intComps[0]->clickPressed(GH.getCursorPosition());
  879. intComps[0]->clickReleased(GH.getCursorPosition());
  880. }
  881. }
  882. void CPlayerInterface::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  883. {
  884. EVENT_HANDLER_CALLED_BY_CLIENT;
  885. movementController->showTeleportDialog(hero, channel, exits, impassable, askID);
  886. }
  887. void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  888. {
  889. EVENT_HANDLER_CALLED_BY_CLIENT;
  890. std::vector<ObjectInstanceID> tmpObjects;
  891. if(objects.size() && dynamic_cast<const CGTownInstance *>(cb->getObj(objects[0])))
  892. {
  893. // sorting towns (like in client)
  894. std::vector <const CGTownInstance*> Towns = LOCPLINT->localState->getOwnedTowns();
  895. for(auto town : Towns)
  896. for(auto item : objects)
  897. if(town == cb->getObj(item))
  898. tmpObjects.push_back(item);
  899. }
  900. else // other object list than town
  901. tmpObjects = objects;
  902. auto selectCallback = [=](int selection)
  903. {
  904. cb->sendQueryReply(selection, askID);
  905. };
  906. auto cancelCallback = [=]()
  907. {
  908. cb->sendQueryReply(std::nullopt, askID);
  909. };
  910. const std::string localTitle = title.toString();
  911. const std::string localDescription = description.toString();
  912. std::vector<int> tempList;
  913. tempList.reserve(tmpObjects.size());
  914. for(auto item : tmpObjects)
  915. tempList.push_back(item.getNum());
  916. CComponent localIconC(icon);
  917. std::shared_ptr<CIntObject> localIcon = localIconC.image;
  918. localIconC.removeChild(localIcon.get(), false);
  919. std::vector<std::shared_ptr<IImage>> images;
  920. for(auto & obj : tmpObjects)
  921. {
  922. if(!settings["general"]["enableUiEnhancements"].Bool())
  923. break;
  924. const CGTownInstance * t = dynamic_cast<const CGTownInstance *>(cb->getObj(obj));
  925. if(t)
  926. {
  927. std::shared_ptr<CAnimation> a = GH.renderHandler().loadAnimation(AnimationPath::builtin("ITPA"));
  928. a->preload();
  929. images.push_back(a->getImage(t->town->clientInfo.icons[t->hasFort()][false] + 2)->scaleFast(Point(35, 23)));
  930. }
  931. }
  932. auto wnd = std::make_shared<CObjectListWindow>(tempList, localIcon, localTitle, localDescription, selectCallback, 0, images);
  933. wnd->onExit = cancelCallback;
  934. wnd->onPopup = [this, tmpObjects](int index) { CRClickPopup::createAndPush(cb->getObj(tmpObjects[index]), GH.getCursorPosition()); };
  935. wnd->onClicked = [this, tmpObjects](int index) { adventureInt->centerOnObject(cb->getObj(tmpObjects[index])); GH.windows().totalRedraw(); };
  936. GH.windows().pushWindow(wnd);
  937. }
  938. void CPlayerInterface::tileRevealed(const std::unordered_set<int3> &pos)
  939. {
  940. EVENT_HANDLER_CALLED_BY_CLIENT;
  941. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  942. adventureInt->onMapTilesChanged(pos);
  943. }
  944. void CPlayerInterface::tileHidden(const std::unordered_set<int3> &pos)
  945. {
  946. EVENT_HANDLER_CALLED_BY_CLIENT;
  947. adventureInt->onMapTilesChanged(pos);
  948. }
  949. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  950. {
  951. GH.windows().createAndPushWindow<CHeroWindow>(hero);
  952. }
  953. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  954. {
  955. EVENT_HANDLER_CALLED_BY_CLIENT;
  956. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  957. {
  958. for (auto fortScreen : GH.windows().findWindows<CFortScreen>())
  959. fortScreen->creaturesChangedEventHandler();
  960. for (auto castleInterface : GH.windows().findWindows<CCastleInterface>())
  961. if(castleInterface->town == town)
  962. castleInterface->creaturesChangedEventHandler();
  963. if (townObj)
  964. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  965. ki->townChanged(townObj);
  966. }
  967. else if(town && GH.windows().count() > 0 && (town->ID == Obj::CREATURE_GENERATOR1
  968. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  969. {
  970. for (auto crw : GH.windows().findWindows<CRecruitmentWindow>())
  971. if (crw->dwelling == town)
  972. crw->availableCreaturesChanged();
  973. }
  974. }
  975. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  976. {
  977. EVENT_HANDLER_CALLED_BY_CLIENT;
  978. if (bonus.type == BonusType::NONE)
  979. return;
  980. adventureInt->onHeroChanged(hero);
  981. if ((bonus.type == BonusType::FLYING_MOVEMENT || bonus.type == BonusType::WATER_WALKING) && !gain)
  982. {
  983. //recalculate paths because hero has lost bonus influencing pathfinding
  984. localState->erasePath(hero);
  985. }
  986. }
  987. void CPlayerInterface::saveGame( BinarySerializer & h )
  988. {
  989. EVENT_HANDLER_CALLED_BY_CLIENT;
  990. localState->serialize(h);
  991. }
  992. void CPlayerInterface::loadGame( BinaryDeserializer & h )
  993. {
  994. EVENT_HANDLER_CALLED_BY_CLIENT;
  995. localState->serialize(h);
  996. firstCall = -1;
  997. }
  998. void CPlayerInterface::moveHero( const CGHeroInstance *h, const CGPath& path )
  999. {
  1000. assert(LOCPLINT->makingTurn);
  1001. assert(h);
  1002. assert(!showingDialog->get());
  1003. assert(dialogs.empty());
  1004. LOG_TRACE(logGlobal);
  1005. if (!LOCPLINT->makingTurn)
  1006. return;
  1007. if (!h)
  1008. return; //can't find hero
  1009. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  1010. if (showingDialog->get() || !dialogs.empty())
  1011. return;
  1012. if (localState->isHeroSleeping(h))
  1013. localState->setHeroAwaken(h);
  1014. movementController->requestMovementStart(h, path);
  1015. }
  1016. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  1017. {
  1018. EVENT_HANDLER_CALLED_BY_CLIENT;
  1019. auto onEnd = [=](){ cb->selectionMade(0, queryID); };
  1020. if (movementController->isHeroMovingThroughGarrison(down, up))
  1021. {
  1022. onEnd();
  1023. return;
  1024. }
  1025. waitForAllDialogs();
  1026. auto cgw = std::make_shared<CGarrisonWindow>(up, down, removableUnits);
  1027. cgw->quit->addCallback(onEnd);
  1028. GH.windows().pushWindow(cgw);
  1029. }
  1030. /**
  1031. * Shows the dialog that appears when right-clicking an artifact that can be assembled
  1032. * into a combinational one on an artifact screen. Does not require the combination of
  1033. * artifacts to be legal.
  1034. */
  1035. void CPlayerInterface::showArtifactAssemblyDialog(const Artifact * artifact, const Artifact * assembledArtifact, CFunctionList<void()> onYes)
  1036. {
  1037. std::string text = artifact->getDescriptionTranslated();
  1038. text += "\n\n";
  1039. std::vector<std::shared_ptr<CComponent>> scs;
  1040. if(assembledArtifact)
  1041. {
  1042. // You possess all of the components to...
  1043. text += boost::str(boost::format(CGI->generaltexth->allTexts[732]) % assembledArtifact->getNameTranslated());
  1044. // Picture of assembled artifact at bottom.
  1045. auto sc = std::make_shared<CComponent>(ComponentType::ARTIFACT, assembledArtifact->getId());
  1046. scs.push_back(sc);
  1047. }
  1048. else
  1049. {
  1050. // Do you wish to disassemble this artifact?
  1051. text += CGI->generaltexth->allTexts[733];
  1052. }
  1053. showYesNoDialog(text, onYes, nullptr, scs);
  1054. }
  1055. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1056. {
  1057. if(pa->packType == CTypeList::getInstance().getTypeID<MoveHero>(nullptr))
  1058. movementController->onMoveHeroApplied();
  1059. if(pa->packType == CTypeList::getInstance().getTypeID<QueryReply>(nullptr))
  1060. movementController->onQueryReplyApplied();
  1061. }
  1062. void CPlayerInterface::showHeroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  1063. {
  1064. heroExchangeStarted(hero1, hero2, QueryID(-1));
  1065. }
  1066. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1067. {
  1068. EVENT_HANDLER_CALLED_BY_CLIENT;
  1069. GH.windows().createAndPushWindow<CExchangeWindow>(hero1, hero2, query);
  1070. }
  1071. void CPlayerInterface::beforeObjectPropertyChanged(const SetObjectProperty * sop)
  1072. {
  1073. if (sop->what == ObjProperty::OWNER)
  1074. {
  1075. const CGObjectInstance * obj = cb->getObj(sop->id);
  1076. if(obj->ID == Obj::TOWN)
  1077. {
  1078. auto town = static_cast<const CGTownInstance *>(obj);
  1079. if(obj->tempOwner == playerID)
  1080. {
  1081. localState->removeOwnedTown(town);
  1082. adventureInt->onTownChanged(town);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1088. {
  1089. EVENT_HANDLER_CALLED_BY_CLIENT;
  1090. if (sop->what == ObjProperty::OWNER)
  1091. {
  1092. const CGObjectInstance * obj = cb->getObj(sop->id);
  1093. if(obj->ID == Obj::TOWN)
  1094. {
  1095. auto town = static_cast<const CGTownInstance *>(obj);
  1096. if(obj->tempOwner == playerID)
  1097. {
  1098. localState->addOwnedTown(town);
  1099. adventureInt->onTownChanged(town);
  1100. }
  1101. }
  1102. //redraw minimap if owner changed
  1103. std::set<int3> pos = obj->getBlockedPos();
  1104. std::unordered_set<int3> upos(pos.begin(), pos.end());
  1105. adventureInt->onMapTilesChanged(upos);
  1106. assert(cb->getTownsInfo().size() == localState->getOwnedTowns().size());
  1107. }
  1108. }
  1109. void CPlayerInterface::initializeHeroTownList()
  1110. {
  1111. if(localState->getWanderingHeroes().empty())
  1112. {
  1113. for(auto & hero : cb->getHeroesInfo())
  1114. {
  1115. if(!hero->inTownGarrison)
  1116. localState->addWanderingHero(hero);
  1117. }
  1118. }
  1119. if(localState->getOwnedTowns().empty())
  1120. {
  1121. for(auto & town : cb->getTownsInfo())
  1122. localState->addOwnedTown(town);
  1123. }
  1124. if(adventureInt)
  1125. adventureInt->onHeroChanged(nullptr);
  1126. }
  1127. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level, QueryID queryID)
  1128. {
  1129. EVENT_HANDLER_CALLED_BY_CLIENT;
  1130. waitWhileDialog();
  1131. auto recruitCb = [=](CreatureID id, int count)
  1132. {
  1133. cb->recruitCreatures(dwelling, dst, id, count, -1);
  1134. };
  1135. auto closeCb = [=]()
  1136. {
  1137. cb->selectionMade(0, queryID);
  1138. };
  1139. GH.windows().createAndPushWindow<CRecruitmentWindow>(dwelling, level, dst, recruitCb, closeCb);
  1140. }
  1141. void CPlayerInterface::waitWhileDialog()
  1142. {
  1143. if (GH.amIGuiThread())
  1144. {
  1145. logGlobal->warn("Cannot wait for dialogs in gui thread (deadlock risk)!");
  1146. return;
  1147. }
  1148. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  1149. boost::unique_lock<boost::mutex> un(showingDialog->mx);
  1150. while(showingDialog->data)
  1151. showingDialog->cond.wait(un);
  1152. }
  1153. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1154. {
  1155. EVENT_HANDLER_CALLED_BY_CLIENT;
  1156. auto state = obj->shipyardStatus();
  1157. TResources cost;
  1158. obj->getBoatCost(cost);
  1159. GH.windows().createAndPushWindow<CShipyardWindow>(cost, state, obj->getBoatType(), [=](){ cb->buildBoat(obj); });
  1160. }
  1161. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1162. {
  1163. EVENT_HANDLER_CALLED_BY_CLIENT;
  1164. //we might have built a boat in shipyard in opened town screen
  1165. if (obj->ID == Obj::BOAT
  1166. && LOCPLINT->castleInt
  1167. && obj->visitablePos() == LOCPLINT->castleInt->town->bestLocation())
  1168. {
  1169. CCS->soundh->playSound(soundBase::newBuilding);
  1170. LOCPLINT->castleInt->addBuilding(BuildingID::SHIP);
  1171. }
  1172. }
  1173. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1174. {
  1175. EVENT_HANDLER_CALLED_BY_CLIENT;
  1176. waitWhileDialog();
  1177. CCS->curh->hide();
  1178. adventureInt->centerOnTile(pos);
  1179. if (focusTime)
  1180. {
  1181. GH.windows().totalRedraw();
  1182. {
  1183. IgnoreEvents ignore(*this);
  1184. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  1185. boost::this_thread::sleep_for(boost::chrono::milliseconds(focusTime));
  1186. }
  1187. }
  1188. CCS->curh->show();
  1189. }
  1190. void CPlayerInterface::objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator)
  1191. {
  1192. EVENT_HANDLER_CALLED_BY_CLIENT;
  1193. if(playerID == initiator && obj->getRemovalSound())
  1194. {
  1195. waitWhileDialog();
  1196. CCS->soundh->playSound(obj->getRemovalSound().value());
  1197. }
  1198. CGI->mh->waitForOngoingAnimations();
  1199. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1200. {
  1201. const CGHeroInstance * h = static_cast<const CGHeroInstance *>(obj);
  1202. heroKilled(h);
  1203. }
  1204. GH.fakeMouseMove();
  1205. }
  1206. void CPlayerInterface::objectRemovedAfter()
  1207. {
  1208. EVENT_HANDLER_CALLED_BY_CLIENT;
  1209. adventureInt->onMapTilesChanged(boost::none);
  1210. // visiting or garrisoned hero removed - update window
  1211. if (castleInt)
  1212. castleInt->updateGarrisons();
  1213. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  1214. ki->heroRemoved();
  1215. }
  1216. void CPlayerInterface::playerBlocked(int reason, bool start)
  1217. {
  1218. if(reason == PlayerBlocked::EReason::UPCOMING_BATTLE)
  1219. {
  1220. if(CSH->howManyPlayerInterfaces() > 1 && LOCPLINT != this && LOCPLINT->makingTurn == false)
  1221. {
  1222. //one of our players who isn't last in order got attacked not by our another player (happens for example in hotseat mode)
  1223. LOCPLINT = this;
  1224. GH.curInt = this;
  1225. adventureInt->onCurrentPlayerChanged(playerID);
  1226. std::string msg = CGI->generaltexth->translate("vcmi.adventureMap.playerAttacked");
  1227. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  1228. std::vector<std::shared_ptr<CComponent>> cmp;
  1229. cmp.push_back(std::make_shared<CComponent>(ComponentType::FLAG, playerID));
  1230. makingTurn = true; //workaround for stiff showInfoDialog implementation
  1231. showInfoDialog(msg, cmp);
  1232. makingTurn = false;
  1233. }
  1234. }
  1235. }
  1236. void CPlayerInterface::update()
  1237. {
  1238. // Make sure that gamestate won't change when GUI objects may obtain its parts on event processing or drawing request
  1239. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  1240. // While mutexes were locked away we may be have stopped being the active interface
  1241. if (LOCPLINT != this)
  1242. return;
  1243. //if there are any waiting dialogs, show them
  1244. if ((CSH->howManyPlayerInterfaces() <= 1 || makingTurn) && !dialogs.empty() && !showingDialog->get())
  1245. {
  1246. showingDialog->set(true);
  1247. GH.windows().pushWindow(dialogs.front());
  1248. dialogs.pop_front();
  1249. }
  1250. assert(adventureInt);
  1251. // Handles mouse and key input
  1252. GH.handleEvents();
  1253. GH.windows().simpleRedraw();
  1254. }
  1255. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1256. {
  1257. using namespace boost::filesystem;
  1258. using namespace boost::algorithm;
  1259. path gamesDir = VCMIDirs::get().userSavePath();
  1260. std::map<std::time_t, int> dates; //save number => datestamp
  1261. const directory_iterator enddir;
  1262. if (!exists(gamesDir))
  1263. create_directory(gamesDir);
  1264. else
  1265. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1266. {
  1267. if (is_regular_file(dir->status()))
  1268. {
  1269. std::string name = dir->path().filename().string();
  1270. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1271. {
  1272. char nr = name[namePrefix.size()];
  1273. if (std::isdigit(nr))
  1274. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1275. }
  1276. }
  1277. }
  1278. if (!dates.empty())
  1279. return (--dates.end())->second; //return latest file number
  1280. return 0;
  1281. }
  1282. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1283. {
  1284. EVENT_HANDLER_CALLED_BY_CLIENT;
  1285. if (player == playerID)
  1286. {
  1287. if (victoryLossCheckResult.loss())
  1288. showInfoDialog(CGI->generaltexth->allTexts[95]);
  1289. assert(GH.curInt == LOCPLINT);
  1290. auto previousInterface = LOCPLINT; //without multiple player interfaces some of lines below are useless, but for hotseat we wanna swap player interface temporarily
  1291. LOCPLINT = this; //this is needed for dialog to show and avoid freeze, dialog showing logic should be reworked someday
  1292. GH.curInt = this; //waiting for dialogs requires this to get events
  1293. if(!makingTurn)
  1294. {
  1295. makingTurn = true; //also needed for dialog to show with current implementation
  1296. waitForAllDialogs();
  1297. makingTurn = false;
  1298. }
  1299. else
  1300. waitForAllDialogs();
  1301. GH.curInt = previousInterface;
  1302. LOCPLINT = previousInterface;
  1303. }
  1304. }
  1305. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1306. {
  1307. EVENT_HANDLER_CALLED_BY_CLIENT;
  1308. }
  1309. void CPlayerInterface::showPuzzleMap()
  1310. {
  1311. EVENT_HANDLER_CALLED_BY_CLIENT;
  1312. waitWhileDialog();
  1313. //TODO: interface should not know the real position of Grail...
  1314. double ratio = 0;
  1315. int3 grailPos = cb->getGrailPos(&ratio);
  1316. GH.windows().createAndPushWindow<CPuzzleWindow>(grailPos, ratio);
  1317. }
  1318. void CPlayerInterface::viewWorldMap()
  1319. {
  1320. adventureInt->openWorldView();
  1321. }
  1322. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, SpellID spellID)
  1323. {
  1324. EVENT_HANDLER_CALLED_BY_CLIENT;
  1325. if(GH.windows().topWindow<CSpellWindow>())
  1326. GH.windows().popWindows(1);
  1327. if(spellID == SpellID::FLY || spellID == SpellID::WATER_WALK)
  1328. localState->erasePath(caster);
  1329. auto castSoundPath = spellID.toSpell()->getCastSound();
  1330. if(!castSoundPath.empty())
  1331. CCS->soundh->playSound(castSoundPath);
  1332. }
  1333. void CPlayerInterface::tryDigging(const CGHeroInstance * h)
  1334. {
  1335. int msgToShow = -1;
  1336. const auto diggingStatus = h->diggingStatus();
  1337. switch(diggingStatus)
  1338. {
  1339. case EDiggingStatus::CAN_DIG:
  1340. break;
  1341. case EDiggingStatus::LACK_OF_MOVEMENT:
  1342. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  1343. break;
  1344. case EDiggingStatus::TILE_OCCUPIED:
  1345. msgToShow = 97; //Try searching on clear ground.
  1346. break;
  1347. case EDiggingStatus::WRONG_TERRAIN:
  1348. msgToShow = 60; ////Try looking on land!
  1349. break;
  1350. case EDiggingStatus::BACKPACK_IS_FULL:
  1351. msgToShow = 247; //Searching for the Grail is fruitless...
  1352. break;
  1353. default:
  1354. assert(0);
  1355. }
  1356. if(msgToShow < 0)
  1357. cb->dig(h);
  1358. else
  1359. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  1360. }
  1361. void CPlayerInterface::battleNewRoundFirst(const BattleID & battleID)
  1362. {
  1363. EVENT_HANDLER_CALLED_BY_CLIENT;
  1364. BATTLE_EVENT_POSSIBLE_RETURN;
  1365. battleInt->newRoundFirst();
  1366. }
  1367. void CPlayerInterface::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor, QueryID queryID)
  1368. {
  1369. EVENT_HANDLER_CALLED_BY_CLIENT;
  1370. auto onWindowClosed = [this, queryID](){
  1371. cb->selectionMade(0, queryID);
  1372. };
  1373. if(market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  1374. GH.windows().createAndPushWindow<CMarketWindow>(market, visitor, onWindowClosed, EMarketMode::ARTIFACT_EXP);
  1375. else if(market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  1376. GH.windows().createAndPushWindow<CMarketWindow>(market, visitor, onWindowClosed, EMarketMode::CREATURE_EXP);
  1377. else if(market->allowsTrade(EMarketMode::CREATURE_UNDEAD))
  1378. GH.windows().createAndPushWindow<CTransformerWindow>(market, visitor, onWindowClosed);
  1379. else if(!market->availableModes().empty())
  1380. GH.windows().createAndPushWindow<CMarketWindow>(market, visitor, onWindowClosed, market->availableModes().front());
  1381. }
  1382. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor, QueryID queryID)
  1383. {
  1384. EVENT_HANDLER_CALLED_BY_CLIENT;
  1385. auto onWindowClosed = [this, queryID](){
  1386. cb->selectionMade(0, queryID);
  1387. };
  1388. GH.windows().createAndPushWindow<CUniversityWindow>(visitor, market, onWindowClosed);
  1389. }
  1390. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  1391. {
  1392. EVENT_HANDLER_CALLED_BY_CLIENT;
  1393. GH.windows().createAndPushWindow<CHillFortWindow>(visitor, object);
  1394. }
  1395. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket * bm)
  1396. {
  1397. EVENT_HANDLER_CALLED_BY_CLIENT;
  1398. for (auto cmw : GH.windows().findWindows<CMarketWindow>())
  1399. cmw->updateArtifacts();
  1400. }
  1401. void CPlayerInterface::showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID)
  1402. {
  1403. EVENT_HANDLER_CALLED_BY_CLIENT;
  1404. auto onWindowClosed = [this, queryID](){
  1405. if (queryID != QueryID::NONE)
  1406. cb->selectionMade(0, queryID);
  1407. };
  1408. GH.windows().createAndPushWindow<CTavernWindow>(object, onWindowClosed);
  1409. }
  1410. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  1411. {
  1412. EVENT_HANDLER_CALLED_BY_CLIENT;
  1413. GH.windows().createAndPushWindow<CThievesGuildWindow>(obj);
  1414. }
  1415. void CPlayerInterface::showQuestLog()
  1416. {
  1417. EVENT_HANDLER_CALLED_BY_CLIENT;
  1418. GH.windows().createAndPushWindow<CQuestLog>(LOCPLINT->cb->getMyQuests());
  1419. }
  1420. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  1421. {
  1422. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  1423. {
  1424. MetaString txt;
  1425. obj->getProblemText(txt);
  1426. showInfoDialog(txt.toString());
  1427. }
  1428. else
  1429. showShipyardDialog(obj);
  1430. }
  1431. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  1432. {
  1433. if(auto hero = cb->getHero(al.artHolder))
  1434. {
  1435. auto art = hero->getArt(al.slot);
  1436. if(art == nullptr)
  1437. {
  1438. logGlobal->error("artifact location %d points to nothing",
  1439. al.slot.num);
  1440. return;
  1441. }
  1442. ArtifactUtilsClient::askToAssemble(hero, al.slot);
  1443. }
  1444. }
  1445. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  1446. {
  1447. EVENT_HANDLER_CALLED_BY_CLIENT;
  1448. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1449. }
  1450. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  1451. {
  1452. EVENT_HANDLER_CALLED_BY_CLIENT;
  1453. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1454. for(auto artWin : GH.windows().findWindows<CWindowWithArtifacts>())
  1455. artWin->artifactRemoved(al);
  1456. waitWhileDialog();
  1457. }
  1458. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1459. {
  1460. EVENT_HANDLER_CALLED_BY_CLIENT;
  1461. adventureInt->onHeroChanged(cb->getHero(dst.artHolder));
  1462. bool redraw = true;
  1463. // If a bulk transfer has arrived, then redrawing only the last art movement.
  1464. if(numOfMovedArts != 0)
  1465. {
  1466. numOfMovedArts--;
  1467. if(numOfMovedArts != 0)
  1468. redraw = false;
  1469. }
  1470. for(auto artWin : GH.windows().findWindows<CWindowWithArtifacts>())
  1471. artWin->artifactMoved(src, dst, redraw);
  1472. waitWhileDialog();
  1473. }
  1474. void CPlayerInterface::bulkArtMovementStart(size_t numOfArts)
  1475. {
  1476. numOfMovedArts = numOfArts;
  1477. }
  1478. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1479. {
  1480. EVENT_HANDLER_CALLED_BY_CLIENT;
  1481. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1482. for(auto artWin : GH.windows().findWindows<CWindowWithArtifacts>())
  1483. artWin->artifactAssembled(al);
  1484. }
  1485. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1486. {
  1487. EVENT_HANDLER_CALLED_BY_CLIENT;
  1488. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1489. for(auto artWin : GH.windows().findWindows<CWindowWithArtifacts>())
  1490. artWin->artifactDisassembled(al);
  1491. }
  1492. void CPlayerInterface::waitForAllDialogs()
  1493. {
  1494. while(!dialogs.empty())
  1495. {
  1496. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  1497. boost::this_thread::sleep_for(boost::chrono::milliseconds(5));
  1498. }
  1499. waitWhileDialog();
  1500. }
  1501. void CPlayerInterface::proposeLoadingGame()
  1502. {
  1503. showYesNoDialog(
  1504. CGI->generaltexth->allTexts[68],
  1505. []()
  1506. {
  1507. CSH->endGameplay();
  1508. GH.defActionsDef = 63;
  1509. CMM->menu->switchToTab("load");
  1510. },
  1511. nullptr
  1512. );
  1513. }
  1514. bool CPlayerInterface::capturedAllEvents()
  1515. {
  1516. if(movementController->isHeroMoving())
  1517. {
  1518. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  1519. return true;
  1520. }
  1521. bool needToLockAdventureMap = adventureInt && adventureInt->isActive() && CGI->mh->hasOngoingAnimations();
  1522. bool quickCombatOngoing = isAutoFightOn && !battleInt;
  1523. if (ignoreEvents || needToLockAdventureMap || quickCombatOngoing )
  1524. {
  1525. GH.input().ignoreEventsUntilInput();
  1526. return true;
  1527. }
  1528. return false;
  1529. }
  1530. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions, bool showTerrain)
  1531. {
  1532. EVENT_HANDLER_CALLED_BY_CLIENT;
  1533. adventureInt->openWorldView(objectPositions, showTerrain );
  1534. }
  1535. std::optional<BattleAction> CPlayerInterface::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  1536. {
  1537. return std::nullopt;
  1538. }