CPlayerInterface.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090
  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 "adventureMap/CAdventureMapInterface.h"
  14. #include "mapView/mapHandler.h"
  15. #include "adventureMap/CList.h"
  16. #include "adventureMap/CInfoBar.h"
  17. #include "battle/BattleInterface.h"
  18. #include "battle/BattleEffectsController.h"
  19. #include "battle/BattleFieldController.h"
  20. #include "battle/BattleInterfaceClasses.h"
  21. #include "battle/BattleWindow.h"
  22. #include "../CCallback.h"
  23. #include "windows/CCastleInterface.h"
  24. #include "gui/CursorHandler.h"
  25. #include "windows/CKingdomInterface.h"
  26. #include "CGameInfo.h"
  27. #include "PlayerLocalState.h"
  28. #include "CMT.h"
  29. #include "windows/CHeroWindow.h"
  30. #include "windows/CCreatureWindow.h"
  31. #include "windows/CQuestLog.h"
  32. #include "windows/CPuzzleWindow.h"
  33. #include "widgets/CComponent.h"
  34. #include "widgets/Buttons.h"
  35. #include "windows/CTradeWindow.h"
  36. #include "windows/CSpellWindow.h"
  37. #include "../lib/CConfigHandler.h"
  38. #include "windows/GUIClasses.h"
  39. #include "render/CAnimation.h"
  40. #include "render/IImage.h"
  41. #include "../lib/CArtHandler.h"
  42. #include "../lib/CGeneralTextHandler.h"
  43. #include "../lib/CHeroHandler.h"
  44. #include "../lib/bonuses/CBonusSystemNode.h"
  45. #include "../lib/bonuses/Limiters.h"
  46. #include "../lib/bonuses/Updaters.h"
  47. #include "../lib/bonuses/Propagators.h"
  48. #include "../lib/serializer/CTypeList.h"
  49. #include "../lib/serializer/BinaryDeserializer.h"
  50. #include "../lib/serializer/BinarySerializer.h"
  51. #include "../lib/spells/CSpellHandler.h"
  52. #include "../lib/CTownHandler.h"
  53. #include "../lib/mapObjects/CObjectClassesHandler.h" // For displaying correct UI when interacting with objects
  54. #include "../lib/CStack.h"
  55. #include "../lib/JsonNode.h"
  56. #include "CMusicHandler.h"
  57. #include "../lib/CondSh.h"
  58. #include "../lib/NetPacksBase.h"
  59. #include "../lib/NetPacks.h"//todo: remove
  60. #include "../lib/mapping/CMap.h"
  61. #include "../lib/VCMIDirs.h"
  62. #include "../lib/CStopWatch.h"
  63. #include "../lib/StartInfo.h"
  64. #include "../lib/CPlayerState.h"
  65. #include "../lib/GameConstants.h"
  66. #include "gui/CGuiHandler.h"
  67. #include "windows/InfoWindows.h"
  68. #include "../lib/UnlockGuard.h"
  69. #include "../lib/CPathfinder.h"
  70. #include "../lib/RoadHandler.h"
  71. #include "../lib/TerrainHandler.h"
  72. #include "CServerHandler.h"
  73. // FIXME: only needed for CGameState::mutex
  74. #include "../lib/CGameState.h"
  75. #include "gui/NotificationHandler.h"
  76. #include "adventureMap/CInGameConsole.h"
  77. #include <SDL_events.h>
  78. // The macro below is used to mark functions that are called by client when game state changes.
  79. // They all assume that CPlayerInterface::pim mutex is locked.
  80. #define EVENT_HANDLER_CALLED_BY_CLIENT
  81. // The macro marks functions that are run on a new thread by client.
  82. // They do not own any mutexes intiially.
  83. #define THREAD_CREATED_BY_CLIENT
  84. #define RETURN_IF_QUICK_COMBAT \
  85. if (isAutoFightOn && !battleInt) \
  86. return;
  87. #define BATTLE_EVENT_POSSIBLE_RETURN\
  88. if (LOCPLINT != this) \
  89. return; \
  90. RETURN_IF_QUICK_COMBAT
  91. extern std::queue<SDL_Event> SDLEventsQueue;
  92. extern boost::mutex eventsM;
  93. boost::recursive_mutex * CPlayerInterface::pim = new boost::recursive_mutex;
  94. CPlayerInterface * LOCPLINT;
  95. std::shared_ptr<BattleInterface> CPlayerInterface::battleInt;
  96. enum EMoveState {STOP_MOVE, WAITING_MOVE, CONTINUE_MOVE, DURING_MOVE};
  97. CondSh<EMoveState> stillMoveHero(STOP_MOVE); //used during hero movement
  98. struct HeroObjectRetriever
  99. {
  100. const CGHeroInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  101. {
  102. return h;
  103. }
  104. const CGHeroInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  105. {
  106. return nullptr;
  107. }
  108. };
  109. CPlayerInterface::CPlayerInterface(PlayerColor Player):
  110. localState(std::make_unique<PlayerLocalState>(*this))
  111. {
  112. logGlobal->trace("\tHuman player interface for player %s being constructed", Player.getStr());
  113. destinationTeleport = ObjectInstanceID();
  114. destinationTeleportPos = int3(-1);
  115. GH.defActionsDef = 0;
  116. LOCPLINT = this;
  117. curAction = nullptr;
  118. playerID=Player;
  119. human=true;
  120. battleInt = nullptr;
  121. castleInt = nullptr;
  122. makingTurn = false;
  123. showingDialog = new CondSh<bool>(false);
  124. cingconsole = new CInGameConsole();
  125. GH.terminate_cond->set(false);
  126. firstCall = 1; //if loading will be overwritten in serialize
  127. autosaveCount = 0;
  128. isAutoFightOn = false;
  129. duringMovement = false;
  130. ignoreEvents = false;
  131. numOfMovedArts = 0;
  132. }
  133. CPlayerInterface::~CPlayerInterface()
  134. {
  135. logGlobal->trace("\tHuman player interface for player %s being destructed", playerID.getStr());
  136. delete showingDialog;
  137. delete cingconsole;
  138. if (LOCPLINT == this)
  139. LOCPLINT = nullptr;
  140. }
  141. void CPlayerInterface::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  142. {
  143. cb = CB;
  144. env = ENV;
  145. CCS->musich->loadTerrainMusicThemes();
  146. initializeHeroTownList();
  147. // always recreate advmap interface to avoid possible memory-corruption bugs
  148. adventureInt.reset(new CAdventureMapInterface());
  149. }
  150. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  151. {
  152. EVENT_HANDLER_CALLED_BY_CLIENT;
  153. if (!vstd::contains (GH.listInt, adventureInt))
  154. {
  155. // after map load - remove all active windows and replace them with adventure map
  156. GH.popInts ((int)GH.listInt.size());
  157. GH.pushInt (adventureInt);
  158. }
  159. // remove all dialogs that do not expect query answer
  160. while (GH.listInt.front() != adventureInt && !dynamic_cast<CInfoWindow*>(GH.listInt.front().get()))
  161. GH.popInts(1);
  162. if (player != playerID && LOCPLINT == this)
  163. {
  164. waitWhileDialog();
  165. adventureInt->onEnemyTurnStarted(player);
  166. }
  167. }
  168. void CPlayerInterface::performAutosave()
  169. {
  170. std::string prefix = settings["session"]["saveprefix"].String();
  171. int frequency = static_cast<int>(settings["general"]["saveFrequency"].Integer());
  172. if(firstCall)
  173. {
  174. autosaveCount = getLastIndex(prefix + "Autosave_");
  175. if(firstCall > 0) //new game, not loaded
  176. {
  177. int index = getLastIndex(prefix + "Newgame_");
  178. index %= SAVES_COUNT;
  179. cb->save("Saves/" + prefix + "Newgame_Autosave_" + std::to_string(index + 1));
  180. }
  181. firstCall = 0;
  182. }
  183. else if(frequency > 0 && cb->getDate() % frequency == 0)
  184. {
  185. LOCPLINT->cb->save("Saves/" + prefix + "Autosave_" + std::to_string(autosaveCount++ + 1));
  186. autosaveCount %= 5;
  187. }
  188. }
  189. void CPlayerInterface::yourTurn()
  190. {
  191. EVENT_HANDLER_CALLED_BY_CLIENT;
  192. {
  193. boost::unique_lock<boost::mutex> lock(eventsM); //block handling events until interface is ready
  194. LOCPLINT = this;
  195. GH.curInt = this;
  196. NotificationHandler::notify("Your turn");
  197. performAutosave();
  198. if (CSH->howManyPlayerInterfaces() > 1) //hot seat message
  199. {
  200. adventureInt->onHotseatWaitStarted(playerID);
  201. makingTurn = true;
  202. std::string msg = CGI->generaltexth->allTexts[13];
  203. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  204. std::vector<std::shared_ptr<CComponent>> cmp;
  205. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  206. showInfoDialog(msg, cmp);
  207. }
  208. else
  209. {
  210. makingTurn = true;
  211. adventureInt->onPlayerTurnStarted(playerID);
  212. }
  213. }
  214. acceptTurn();
  215. }
  216. void CPlayerInterface::acceptTurn()
  217. {
  218. if (settings["session"]["autoSkip"].Bool())
  219. {
  220. while(CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt().get()))
  221. iw->close();
  222. }
  223. if(CSH->howManyPlayerInterfaces() > 1)
  224. {
  225. waitWhileDialog(); // wait for player to accept turn in hot-seat mode
  226. adventureInt->onPlayerTurnStarted(playerID);
  227. }
  228. // warn player if he has no town
  229. if (cb->howManyTowns() == 0)
  230. {
  231. auto playerColor = *cb->getPlayerID();
  232. std::vector<Component> components;
  233. components.emplace_back(Component::EComponentType::FLAG, playerColor.getNum(), 0, 0);
  234. MetaString text;
  235. const auto & optDaysWithoutCastle = cb->getPlayerState(playerColor)->daysWithoutCastle;
  236. if(optDaysWithoutCastle)
  237. {
  238. auto daysWithoutCastle = optDaysWithoutCastle.value();
  239. if (daysWithoutCastle < 6)
  240. {
  241. text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  242. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  243. text.addReplacement(7 - daysWithoutCastle);
  244. }
  245. else if (daysWithoutCastle == 6)
  246. {
  247. text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  248. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  249. }
  250. showInfoDialogAndWait(components, text);
  251. }
  252. else
  253. logGlobal->warn("Player has no towns, but daysWithoutCastle is not set");
  254. }
  255. }
  256. void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose)
  257. {
  258. EVENT_HANDLER_CALLED_BY_CLIENT;
  259. waitWhileDialog();
  260. if(LOCPLINT != this)
  261. return;
  262. //FIXME: read once and store
  263. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-ignore-hero"].Bool())
  264. return;
  265. const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
  266. if (!hero)
  267. return;
  268. if (details.result == TryMoveHero::EMBARK || details.result == TryMoveHero::DISEMBARK)
  269. {
  270. if(hero->getRemovalSound() && hero->tempOwner == playerID)
  271. CCS->soundh->playSound(hero->getRemovalSound().value());
  272. }
  273. std::unordered_set<int3> changedTiles {
  274. hero->convertToVisitablePos(details.start),
  275. hero->convertToVisitablePos(details.end)
  276. };
  277. adventureInt->onMapTilesChanged(changedTiles);
  278. adventureInt->onHeroMovementStarted(hero);
  279. bool directlyAttackingCreature = details.attackedFrom && localState->hasPath(hero) && localState->getPath(hero).endPos() == *details.attackedFrom;
  280. if(makingTurn && hero->tempOwner == playerID) //we are moving our hero - we may need to update assigned path
  281. {
  282. if(details.result == TryMoveHero::TELEPORTATION)
  283. {
  284. if(localState->hasPath(hero))
  285. {
  286. assert(localState->getPath(hero).nodes.size() >= 2);
  287. auto nodesIt = localState->getPath(hero).nodes.end() - 1;
  288. if((nodesIt)->coord == hero->convertToVisitablePos(details.start)
  289. && (nodesIt - 1)->coord == hero->convertToVisitablePos(details.end))
  290. {
  291. //path was between entrance and exit of teleport -> OK, erase node as usual
  292. localState->removeLastNode(hero);
  293. }
  294. else
  295. {
  296. //teleport was not along current path, it'll now be invalid (hero is somewhere else)
  297. localState->erasePath(hero);
  298. }
  299. }
  300. }
  301. if(hero->pos != details.end //hero didn't change tile but visit succeeded
  302. || directlyAttackingCreature) // or creature was attacked from endangering tile.
  303. {
  304. localState->erasePath(hero);
  305. }
  306. else if(localState->hasPath(hero) && hero->pos == details.end) //&& hero is moving
  307. {
  308. if(details.start != details.end) //so we don't touch path when revisiting with spacebar
  309. localState->removeLastNode(hero);
  310. }
  311. }
  312. if(details.stopMovement()) //hero failed to move
  313. {
  314. stillMoveHero.setn(STOP_MOVE);
  315. adventureInt->onHeroChanged(hero);
  316. return;
  317. }
  318. CGI->mh->waitForOngoingAnimations();
  319. //move finished
  320. adventureInt->onHeroChanged(hero);
  321. //check if user cancelled movement
  322. {
  323. boost::unique_lock<boost::mutex> un(eventsM);
  324. while(!SDLEventsQueue.empty())
  325. {
  326. SDL_Event ev = SDLEventsQueue.front();
  327. SDLEventsQueue.pop();
  328. switch(ev.type)
  329. {
  330. case SDL_MOUSEBUTTONDOWN:
  331. stillMoveHero.setn(STOP_MOVE);
  332. break;
  333. case SDL_KEYDOWN:
  334. if (ev.key.keysym.sym < SDLK_F1 || ev.key.keysym.sym > SDLK_F15)
  335. stillMoveHero.setn(STOP_MOVE);
  336. break;
  337. }
  338. }
  339. }
  340. if (stillMoveHero.get() == WAITING_MOVE)
  341. stillMoveHero.setn(DURING_MOVE);
  342. // Hero attacked creature directly, set direction to face it.
  343. if (directlyAttackingCreature) {
  344. // Get direction to attacker.
  345. int3 posOffset = *details.attackedFrom - details.end + int3(2, 1, 0);
  346. static const ui8 dirLookup[3][3] = {
  347. { 1, 2, 3 },
  348. { 8, 0, 4 },
  349. { 7, 6, 5 }
  350. };
  351. // FIXME: Avoid const_cast, make moveDir mutable in some other way?
  352. const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
  353. }
  354. }
  355. void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
  356. {
  357. EVENT_HANDLER_CALLED_BY_CLIENT;
  358. LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->getNameTranslated() % playerID);
  359. localState->removeWanderingHero(hero);
  360. adventureInt->onHeroChanged(hero);
  361. localState->erasePath(hero);
  362. }
  363. void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  364. {
  365. EVENT_HANDLER_CALLED_BY_CLIENT;
  366. if(start && visitedObj)
  367. {
  368. if(visitedObj->getVisitSound())
  369. CCS->soundh->playSound(visitedObj->getVisitSound().value());
  370. }
  371. }
  372. void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
  373. {
  374. EVENT_HANDLER_CALLED_BY_CLIENT;
  375. localState->addWanderingHero(hero);
  376. adventureInt->onHeroChanged(hero);
  377. }
  378. void CPlayerInterface::openTownWindow(const CGTownInstance * town)
  379. {
  380. if(castleInt)
  381. castleInt->close();
  382. castleInt = nullptr;
  383. auto newCastleInt = std::make_shared<CCastleInterface>(town);
  384. GH.pushInt(newCastleInt);
  385. }
  386. void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  387. {
  388. EVENT_HANDLER_CALLED_BY_CLIENT;
  389. if (which == 4)
  390. {
  391. if (CAltarWindow *ctw = dynamic_cast<CAltarWindow *>(GH.topInt().get()))
  392. ctw->setExpToLevel();
  393. }
  394. else
  395. adventureInt->onHeroChanged(hero);
  396. }
  397. void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  398. {
  399. EVENT_HANDLER_CALLED_BY_CLIENT;
  400. CUniversityWindow* cuw = dynamic_cast<CUniversityWindow*>(GH.topInt().get());
  401. if (cuw) //university window is open
  402. {
  403. GH.totalRedraw();
  404. }
  405. }
  406. void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
  407. {
  408. EVENT_HANDLER_CALLED_BY_CLIENT;
  409. adventureInt->onHeroChanged(hero);
  410. if (makingTurn && hero->tempOwner == playerID)
  411. adventureInt->onHeroChanged(hero);
  412. }
  413. void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
  414. {
  415. EVENT_HANDLER_CALLED_BY_CLIENT;
  416. if (makingTurn && hero->tempOwner == playerID)
  417. adventureInt->onHeroChanged(hero);
  418. }
  419. void CPlayerInterface::receivedResource()
  420. {
  421. EVENT_HANDLER_CALLED_BY_CLIENT;
  422. if (CMarketplaceWindow *mw = dynamic_cast<CMarketplaceWindow *>(GH.topInt().get()))
  423. mw->resourceChanged();
  424. GH.totalRedraw();
  425. }
  426. void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
  427. {
  428. EVENT_HANDLER_CALLED_BY_CLIENT;
  429. waitWhileDialog();
  430. CCS->soundh->playSound(soundBase::heroNewLevel);
  431. GH.pushIntT<CLevelWindow>(hero, pskill, skills, [=](ui32 selection)
  432. {
  433. cb->selectionMade(selection, queryID);
  434. });
  435. }
  436. void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  437. {
  438. EVENT_HANDLER_CALLED_BY_CLIENT;
  439. waitWhileDialog();
  440. CCS->soundh->playSound(soundBase::heroNewLevel);
  441. GH.pushIntT<CStackWindow>(commander, skills, [=](ui32 selection)
  442. {
  443. cb->selectionMade(selection, queryID);
  444. });
  445. }
  446. void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
  447. {
  448. EVENT_HANDLER_CALLED_BY_CLIENT;
  449. if(town->garrisonHero) //wandering hero moved to the garrison
  450. {
  451. // This method also gets called on hero recruitment -> garrisoned hero is already in garrison
  452. if(town->garrisonHero->tempOwner == playerID && !vstd::contains(localState->getWanderingHeroes(), town->visitingHero))
  453. localState->removeWanderingHero(town->garrisonHero);
  454. }
  455. if(town->visitingHero) //hero leaves garrison
  456. {
  457. // This method also gets called on hero recruitment -> wandering heroes already contains new hero
  458. if(town->visitingHero->tempOwner == playerID && !vstd::contains(localState->getWanderingHeroes(), town->visitingHero))
  459. localState->addWanderingHero(town->visitingHero);
  460. }
  461. adventureInt->onHeroChanged(nullptr);
  462. adventureInt->onTownChanged(town);
  463. if(castleInt)
  464. {
  465. castleInt->garr->selectSlot(nullptr);
  466. castleInt->garr->setArmy(town->getUpperArmy(), 0);
  467. castleInt->garr->setArmy(town->visitingHero, 1);
  468. castleInt->garr->recreateSlots();
  469. castleInt->heroes->update();
  470. castleInt->redraw();
  471. }
  472. for (auto isa : GH.listInt)
  473. {
  474. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa.get());
  475. if (ki)
  476. {
  477. ki->townChanged(town);
  478. ki->updateGarrisons();
  479. ki->redraw();
  480. }
  481. }
  482. }
  483. void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  484. {
  485. EVENT_HANDLER_CALLED_BY_CLIENT;
  486. if (hero->tempOwner != playerID )
  487. return;
  488. waitWhileDialog();
  489. openTownWindow(town);
  490. }
  491. void CPlayerInterface::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  492. {
  493. std::vector<const CGObjectInstance *> instances;
  494. if(auto obj = cb->getObj(id1))
  495. instances.push_back(obj);
  496. if(id2 != ObjectInstanceID() && id2 != id1)
  497. {
  498. if(auto obj = cb->getObj(id2))
  499. instances.push_back(obj);
  500. }
  501. garrisonsChanged(instances);
  502. }
  503. void CPlayerInterface::garrisonsChanged(std::vector<const CGObjectInstance *> objs)
  504. {
  505. boost::unique_lock<boost::recursive_mutex> un(*pim);
  506. for (auto object : objs)
  507. {
  508. auto * hero = dynamic_cast<const CGHeroInstance*>(object);
  509. auto * town = dynamic_cast<const CGTownInstance*>(object);
  510. if (hero)
  511. adventureInt->onHeroChanged(hero);
  512. if (town)
  513. adventureInt->onTownChanged(town);
  514. }
  515. for (auto & elem : GH.listInt)
  516. {
  517. CGarrisonHolder *cgh = dynamic_cast<CGarrisonHolder*>(elem.get());
  518. if (cgh)
  519. cgh->updateGarrisons();
  520. if (CTradeWindow *cmw = dynamic_cast<CTradeWindow*>(elem.get()))
  521. {
  522. if (vstd::contains(objs, cmw->hero))
  523. cmw->garrisonChanged();
  524. }
  525. }
  526. GH.totalRedraw();
  527. }
  528. void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
  529. {
  530. EVENT_HANDLER_CALLED_BY_CLIENT;
  531. if (castleInt)
  532. {
  533. castleInt->townlist->update(town);
  534. if (castleInt->town == town)
  535. {
  536. switch(what)
  537. {
  538. case 1:
  539. CCS->soundh->playSound(soundBase::newBuilding);
  540. castleInt->addBuilding(buildingID);
  541. break;
  542. case 2:
  543. castleInt->removeBuilding(buildingID);
  544. break;
  545. }
  546. }
  547. }
  548. adventureInt->onTownChanged(town);
  549. }
  550. void CPlayerInterface::battleStartBefore(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  551. {
  552. //Don't wait for dialogs when we are non-active hot-seat player
  553. if (LOCPLINT == this)
  554. waitForAllDialogs();
  555. }
  556. void CPlayerInterface::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  557. {
  558. EVENT_HANDLER_CALLED_BY_CLIENT;
  559. bool autoBattleResultRefused = (lastBattleArmies.first == army1 && lastBattleArmies.second == army2);
  560. lastBattleArmies.first = army1;
  561. lastBattleArmies.second = army2;
  562. //quick combat with neutral creatures only
  563. auto * army2_object = dynamic_cast<const CGObjectInstance *>(army2);
  564. if((!autoBattleResultRefused && !allowBattleReplay && army2_object
  565. && army2_object->getOwner() == PlayerColor::UNFLAGGABLE
  566. && settings["adventure"]["quickCombat"].Bool())
  567. || settings["adventure"]["alwaysSkipCombat"].Bool())
  568. {
  569. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  570. autofightingAI->initBattleInterface(env, cb);
  571. autofightingAI->battleStart(army1, army2, int3(0,0,0), hero1, hero2, side);
  572. isAutoFightOn = true;
  573. cb->registerBattleInterface(autofightingAI);
  574. // Player shouldn't be able to move on adventure map if quick combat is going
  575. allowBattleReplay = true;
  576. }
  577. //Don't wait for dialogs when we are non-active hot-seat player
  578. if (LOCPLINT == this)
  579. waitForAllDialogs();
  580. BATTLE_EVENT_POSSIBLE_RETURN;
  581. }
  582. void CPlayerInterface::battleUnitsChanged(const std::vector<UnitChanges> & units)
  583. {
  584. EVENT_HANDLER_CALLED_BY_CLIENT;
  585. BATTLE_EVENT_POSSIBLE_RETURN;
  586. for(auto & info : units)
  587. {
  588. switch(info.operation)
  589. {
  590. case UnitChanges::EOperation::RESET_STATE:
  591. {
  592. const CStack * stack = cb->battleGetStackByID(info.id );
  593. if(!stack)
  594. {
  595. logGlobal->error("Invalid unit ID %d", info.id);
  596. continue;
  597. }
  598. battleInt->stackReset(stack);
  599. }
  600. break;
  601. case UnitChanges::EOperation::REMOVE:
  602. battleInt->stackRemoved(info.id);
  603. break;
  604. case UnitChanges::EOperation::ADD:
  605. {
  606. const CStack * unit = cb->battleGetStackByID(info.id);
  607. if(!unit)
  608. {
  609. logGlobal->error("Invalid unit ID %d", info.id);
  610. continue;
  611. }
  612. battleInt->stackAdded(unit);
  613. }
  614. break;
  615. default:
  616. logGlobal->error("Unknown unit operation %d", (int)info.operation);
  617. break;
  618. }
  619. }
  620. }
  621. void CPlayerInterface::battleObstaclesChanged(const std::vector<ObstacleChanges> & obstacles)
  622. {
  623. EVENT_HANDLER_CALLED_BY_CLIENT;
  624. BATTLE_EVENT_POSSIBLE_RETURN;
  625. std::vector<std::shared_ptr<const CObstacleInstance>> newObstacles;
  626. std::vector<ObstacleChanges> removedObstacles;
  627. for(auto & change : obstacles)
  628. {
  629. if(change.operation == BattleChanges::EOperation::ADD)
  630. {
  631. auto instance = cb->battleGetObstacleByID(change.id);
  632. if(instance)
  633. newObstacles.push_back(instance);
  634. else
  635. logNetwork->error("Invalid obstacle instance %d", change.id);
  636. }
  637. if(change.operation == BattleChanges::EOperation::REMOVE)
  638. removedObstacles.push_back(change); //Obstacles are already removed, so, show animation based on json struct
  639. }
  640. if (!newObstacles.empty())
  641. battleInt->obstaclePlaced(newObstacles);
  642. if (!removedObstacles.empty())
  643. battleInt->obstacleRemoved(removedObstacles);
  644. battleInt->fieldController->redrawBackgroundWithHexes();
  645. }
  646. void CPlayerInterface::battleCatapultAttacked(const CatapultAttack & ca)
  647. {
  648. EVENT_HANDLER_CALLED_BY_CLIENT;
  649. BATTLE_EVENT_POSSIBLE_RETURN;
  650. battleInt->stackIsCatapulting(ca);
  651. }
  652. void CPlayerInterface::battleNewRound(int round) //called at the beginning of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
  653. {
  654. EVENT_HANDLER_CALLED_BY_CLIENT;
  655. BATTLE_EVENT_POSSIBLE_RETURN;
  656. battleInt->newRound(round);
  657. }
  658. void CPlayerInterface::actionStarted(const BattleAction &action)
  659. {
  660. EVENT_HANDLER_CALLED_BY_CLIENT;
  661. BATTLE_EVENT_POSSIBLE_RETURN;
  662. curAction = new BattleAction(action);
  663. battleInt->startAction(curAction);
  664. }
  665. void CPlayerInterface::actionFinished(const BattleAction &action)
  666. {
  667. EVENT_HANDLER_CALLED_BY_CLIENT;
  668. BATTLE_EVENT_POSSIBLE_RETURN;
  669. battleInt->endAction(curAction);
  670. delete curAction;
  671. curAction = nullptr;
  672. }
  673. BattleAction CPlayerInterface::activeStack(const CStack * stack) //called when it's turn of that stack
  674. {
  675. THREAD_CREATED_BY_CLIENT;
  676. logGlobal->trace("Awaiting command for %s", stack->nodeName());
  677. auto stackId = stack->unitId();
  678. auto stackName = stack->nodeName();
  679. if (autofightingAI)
  680. {
  681. if (isAutoFightOn)
  682. {
  683. auto ret = autofightingAI->activeStack(stack);
  684. if(cb->battleIsFinished())
  685. {
  686. return BattleAction::makeDefend(stack); // battle finished with spellcast
  687. }
  688. if (isAutoFightOn)
  689. {
  690. return ret;
  691. }
  692. }
  693. cb->unregisterBattleInterface(autofightingAI);
  694. autofightingAI.reset();
  695. }
  696. assert(battleInt);
  697. if(!battleInt)
  698. {
  699. return BattleAction::makeDefend(stack); // probably battle is finished already
  700. }
  701. if(BattleInterface::givenCommand.get())
  702. {
  703. logGlobal->error("Command buffer must be clean! (we don't want to use old command)");
  704. vstd::clear_pointer(BattleInterface::givenCommand.data);
  705. }
  706. {
  707. boost::unique_lock<boost::recursive_mutex> un(*pim);
  708. battleInt->stackActivated(stack);
  709. //Regeneration & mana drain go there
  710. }
  711. //wait till BattleInterface sets its command
  712. boost::unique_lock<boost::mutex> lock(BattleInterface::givenCommand.mx);
  713. while(!BattleInterface::givenCommand.data)
  714. {
  715. BattleInterface::givenCommand.cond.wait(lock);
  716. if (!battleInt) //battle ended while we were waiting for movement (eg. because of spell)
  717. throw boost::thread_interrupted(); //will shut the thread peacefully
  718. }
  719. //tidy up
  720. BattleAction ret = *(BattleInterface::givenCommand.data);
  721. vstd::clear_pointer(BattleInterface::givenCommand.data);
  722. if(ret.actionType == EActionType::CANCEL)
  723. {
  724. if(stackId != ret.stackNumber)
  725. logGlobal->error("Not current active stack action canceled");
  726. logGlobal->trace("Canceled command for %s", stackName);
  727. }
  728. else
  729. logGlobal->trace("Giving command for %s", stackName);
  730. return ret;
  731. }
  732. void CPlayerInterface::battleEnd(const BattleResult *br, QueryID queryID)
  733. {
  734. EVENT_HANDLER_CALLED_BY_CLIENT;
  735. if(isAutoFightOn || autofightingAI)
  736. {
  737. isAutoFightOn = false;
  738. cb->unregisterBattleInterface(autofightingAI);
  739. autofightingAI.reset();
  740. if(!battleInt)
  741. {
  742. bool allowManualReplay = allowBattleReplay && !settings["adventure"]["alwaysSkipCombat"].Bool();
  743. allowBattleReplay = false;
  744. auto wnd = std::make_shared<BattleResultWindow>(*br, *this, allowManualReplay);
  745. wnd->resultCallback = [=](ui32 selection)
  746. {
  747. cb->selectionMade(selection, queryID);
  748. };
  749. GH.pushInt(wnd);
  750. // #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
  751. // Otherwise NewTurn causes freeze.
  752. waitWhileDialog();
  753. return;
  754. }
  755. }
  756. BATTLE_EVENT_POSSIBLE_RETURN;
  757. battleInt->battleFinished(*br, queryID);
  758. }
  759. void CPlayerInterface::battleLogMessage(const std::vector<MetaString> & lines)
  760. {
  761. EVENT_HANDLER_CALLED_BY_CLIENT;
  762. BATTLE_EVENT_POSSIBLE_RETURN;
  763. battleInt->displayBattleLog(lines);
  764. }
  765. void CPlayerInterface::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance, bool teleport)
  766. {
  767. EVENT_HANDLER_CALLED_BY_CLIENT;
  768. BATTLE_EVENT_POSSIBLE_RETURN;
  769. battleInt->stackMoved(stack, dest, distance, teleport);
  770. }
  771. void CPlayerInterface::battleSpellCast( const BattleSpellCast *sc )
  772. {
  773. EVENT_HANDLER_CALLED_BY_CLIENT;
  774. BATTLE_EVENT_POSSIBLE_RETURN;
  775. battleInt->spellCast(sc);
  776. }
  777. void CPlayerInterface::battleStacksEffectsSet( const SetStackEffect & sse )
  778. {
  779. EVENT_HANDLER_CALLED_BY_CLIENT;
  780. BATTLE_EVENT_POSSIBLE_RETURN;
  781. battleInt->battleStacksEffectsSet(sse);
  782. }
  783. void CPlayerInterface::battleTriggerEffect (const BattleTriggerEffect & bte)
  784. {
  785. EVENT_HANDLER_CALLED_BY_CLIENT;
  786. BATTLE_EVENT_POSSIBLE_RETURN;
  787. RETURN_IF_QUICK_COMBAT;
  788. battleInt->effectsController->battleTriggerEffect(bte);
  789. }
  790. void CPlayerInterface::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa, bool ranged)
  791. {
  792. EVENT_HANDLER_CALLED_BY_CLIENT;
  793. BATTLE_EVENT_POSSIBLE_RETURN;
  794. std::vector<StackAttackedInfo> arg;
  795. for(auto & elem : bsa)
  796. {
  797. const CStack * defender = cb->battleGetStackByID(elem.stackAttacked, false);
  798. const CStack * attacker = cb->battleGetStackByID(elem.attackerID, false);
  799. assert(defender);
  800. StackAttackedInfo info;
  801. info.defender = defender;
  802. info.attacker = attacker;
  803. info.damageDealt = elem.damageAmount;
  804. info.amountKilled = elem.killedAmount;
  805. info.spellEffect = SpellID::NONE;
  806. info.indirectAttack = ranged;
  807. info.killed = elem.killed();
  808. info.rebirth = elem.willRebirth();
  809. info.cloneKilled = elem.cloneKilled();
  810. info.fireShield = elem.fireShield();
  811. if (elem.isSpell())
  812. info.spellEffect = elem.spellID;
  813. arg.push_back(info);
  814. }
  815. battleInt->stacksAreAttacked(arg);
  816. }
  817. void CPlayerInterface::battleAttack(const BattleAttack * ba)
  818. {
  819. EVENT_HANDLER_CALLED_BY_CLIENT;
  820. BATTLE_EVENT_POSSIBLE_RETURN;
  821. assert(curAction);
  822. StackAttackInfo info;
  823. info.attacker = cb->battleGetStackByID(ba->stackAttacking);
  824. info.defender = nullptr;
  825. info.indirectAttack = ba->shot();
  826. info.lucky = ba->lucky();
  827. info.unlucky = ba->unlucky();
  828. info.deathBlow = ba->deathBlow();
  829. info.lifeDrain = ba->lifeDrain();
  830. info.tile = ba->tile;
  831. info.spellEffect = SpellID::NONE;
  832. if (ba->spellLike())
  833. info.spellEffect = ba->spellID;
  834. for(auto & elem : ba->bsa)
  835. {
  836. if(!elem.isSecondary())
  837. {
  838. assert(info.defender == nullptr);
  839. info.defender = cb->battleGetStackByID(elem.stackAttacked);
  840. }
  841. else
  842. {
  843. info.secondaryDefender.push_back(cb->battleGetStackByID(elem.stackAttacked));
  844. }
  845. }
  846. assert(info.defender != nullptr);
  847. assert(info.attacker != nullptr);
  848. battleInt->stackAttacking(info);
  849. }
  850. void CPlayerInterface::battleGateStateChanged(const EGateState state)
  851. {
  852. EVENT_HANDLER_CALLED_BY_CLIENT;
  853. BATTLE_EVENT_POSSIBLE_RETURN;
  854. battleInt->gateStateChanged(state);
  855. }
  856. void CPlayerInterface::yourTacticPhase(int distance)
  857. {
  858. THREAD_CREATED_BY_CLIENT;
  859. while(battleInt && battleInt->tacticsMode)
  860. boost::this_thread::sleep(boost::posix_time::millisec(1));
  861. }
  862. void CPlayerInterface::forceEndTacticPhase()
  863. {
  864. if (battleInt)
  865. battleInt->tacticsMode = false;
  866. }
  867. void CPlayerInterface::showInfoDialog(EInfoWindowMode type, const std::string &text, const std::vector<Component> & components, int soundID)
  868. {
  869. EVENT_HANDLER_CALLED_BY_CLIENT;
  870. bool autoTryHover = settings["gameTweaks"]["infoBarPick"].Bool() && type == EInfoWindowMode::AUTO;
  871. auto timer = type == EInfoWindowMode::INFO ? 3000 : 4500; //Implement long info windows like in HD mod
  872. if(autoTryHover || type == EInfoWindowMode::INFO)
  873. {
  874. waitWhileDialog(); //Fix for mantis #98
  875. adventureInt->showInfoBoxMessage(components, text, timer);
  876. if (makingTurn && GH.listInt.size() && LOCPLINT == this)
  877. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  878. return;
  879. }
  880. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  881. {
  882. return;
  883. }
  884. std::vector<Component> vect = components; //I do not know currently how to avoid copy here
  885. do
  886. {
  887. std::vector<Component> sender = {vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8))};
  888. std::vector<std::shared_ptr<CComponent>> intComps;
  889. for (auto & component : sender)
  890. intComps.push_back(std::make_shared<CComponent>(component));
  891. showInfoDialog(text,intComps,soundID);
  892. vect.erase(vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8)));
  893. }
  894. while(!vect.empty());
  895. }
  896. void CPlayerInterface::showInfoDialog(const std::string & text, std::shared_ptr<CComponent> component)
  897. {
  898. std::vector<std::shared_ptr<CComponent>> intComps;
  899. intComps.push_back(component);
  900. showInfoDialog(text, intComps, soundBase::sound_todo);
  901. }
  902. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<std::shared_ptr<CComponent>> & components, int soundID)
  903. {
  904. LOG_TRACE_PARAMS(logGlobal, "player=%s, text=%s, is LOCPLINT=%d", playerID % text % (this==LOCPLINT));
  905. waitWhileDialog();
  906. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  907. {
  908. return;
  909. }
  910. std::shared_ptr<CInfoWindow> temp = CInfoWindow::create(text, playerID, components);
  911. if (makingTurn && GH.listInt.size() && LOCPLINT == this)
  912. {
  913. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  914. showingDialog->set(true);
  915. stopMovement(); // interrupt movement to show dialog
  916. GH.pushInt(temp);
  917. }
  918. else
  919. {
  920. dialogs.push_back(temp);
  921. }
  922. }
  923. void CPlayerInterface::showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text)
  924. {
  925. EVENT_HANDLER_CALLED_BY_CLIENT;
  926. std::string str;
  927. text.toString(str);
  928. showInfoDialog(EInfoWindowMode::MODAL, str, components, 0);
  929. waitWhileDialog();
  930. }
  931. void CPlayerInterface::showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, const std::vector<std::shared_ptr<CComponent>> & components)
  932. {
  933. boost::unique_lock<boost::recursive_mutex> un(*pim);
  934. stopMovement();
  935. LOCPLINT->showingDialog->setn(true);
  936. CInfoWindow::showYesNoDialog(text, components, onYes, onNo, playerID);
  937. }
  938. void CPlayerInterface::showBlockingDialog( const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel )
  939. {
  940. EVENT_HANDLER_CALLED_BY_CLIENT;
  941. waitWhileDialog();
  942. stopMovement();
  943. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  944. if (!selection && cancel) //simple yes/no dialog
  945. {
  946. std::vector<std::shared_ptr<CComponent>> intComps;
  947. for (auto & component : components)
  948. intComps.push_back(std::make_shared<CComponent>(component)); //will be deleted by close in window
  949. showYesNoDialog(text, [=](){ cb->selectionMade(1, askID); }, [=](){ cb->selectionMade(0, askID); }, intComps);
  950. }
  951. else if (selection)
  952. {
  953. std::vector<std::shared_ptr<CSelectableComponent>> intComps;
  954. for (auto & component : components)
  955. intComps.push_back(std::make_shared<CSelectableComponent>(component)); //will be deleted by CSelWindow::close
  956. std::vector<std::pair<std::string,CFunctionList<void()> > > pom;
  957. pom.push_back(std::pair<std::string,CFunctionList<void()> >("IOKAY.DEF",0));
  958. if (cancel)
  959. {
  960. pom.push_back(std::pair<std::string,CFunctionList<void()> >("ICANCEL.DEF",0));
  961. }
  962. int charperline = 35;
  963. if (pom.size() > 1)
  964. charperline = 50;
  965. GH.pushIntT<CSelWindow>(text, playerID, charperline, intComps, pom, askID);
  966. intComps[0]->clickLeft(true, false);
  967. }
  968. }
  969. void CPlayerInterface::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  970. {
  971. EVENT_HANDLER_CALLED_BY_CLIENT;
  972. int choosenExit = -1;
  973. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  974. if (destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  975. choosenExit = vstd::find_pos(exits, neededExit);
  976. cb->selectionMade(choosenExit, askID);
  977. }
  978. void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  979. {
  980. EVENT_HANDLER_CALLED_BY_CLIENT;
  981. auto selectCallback = [=](int selection)
  982. {
  983. JsonNode reply(JsonNode::JsonType::DATA_INTEGER);
  984. reply.Integer() = selection;
  985. cb->sendQueryReply(reply, askID);
  986. };
  987. auto cancelCallback = [=]()
  988. {
  989. JsonNode reply(JsonNode::JsonType::DATA_NULL);
  990. cb->sendQueryReply(reply, askID);
  991. };
  992. const std::string localTitle = title.toString();
  993. const std::string localDescription = description.toString();
  994. std::vector<int> tempList;
  995. tempList.reserve(objects.size());
  996. for(auto item : objects)
  997. tempList.push_back(item.getNum());
  998. CComponent localIconC(icon);
  999. std::shared_ptr<CIntObject> localIcon = localIconC.image;
  1000. localIconC.removeChild(localIcon.get(), false);
  1001. std::shared_ptr<CObjectListWindow> wnd = std::make_shared<CObjectListWindow>(tempList, localIcon, localTitle, localDescription, selectCallback);
  1002. wnd->onExit = cancelCallback;
  1003. GH.pushInt(wnd);
  1004. }
  1005. void CPlayerInterface::tileRevealed(const std::unordered_set<int3> &pos)
  1006. {
  1007. EVENT_HANDLER_CALLED_BY_CLIENT;
  1008. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  1009. adventureInt->onMapTilesChanged(pos);
  1010. }
  1011. void CPlayerInterface::tileHidden(const std::unordered_set<int3> &pos)
  1012. {
  1013. EVENT_HANDLER_CALLED_BY_CLIENT;
  1014. adventureInt->onMapTilesChanged(pos);
  1015. }
  1016. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  1017. {
  1018. boost::unique_lock<boost::recursive_mutex> un(*pim);
  1019. GH.pushIntT<CHeroWindow>(hero);
  1020. }
  1021. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  1022. {
  1023. EVENT_HANDLER_CALLED_BY_CLIENT;
  1024. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  1025. {
  1026. CFortScreen * fortScreen = dynamic_cast<CFortScreen*>(GH.topInt().get());
  1027. CCastleInterface * castleInterface = dynamic_cast<CCastleInterface*>(GH.topInt().get());
  1028. if (fortScreen)
  1029. fortScreen->creaturesChangedEventHandler();
  1030. else if(castleInterface)
  1031. castleInterface->creaturesChangedEventHandler();
  1032. for(auto isa : GH.listInt)
  1033. {
  1034. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa.get());
  1035. if (ki && townObj)
  1036. ki->townChanged(townObj);
  1037. }
  1038. }
  1039. else if(town && GH.listInt.size() && (town->ID == Obj::CREATURE_GENERATOR1
  1040. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  1041. {
  1042. CRecruitmentWindow *crw = dynamic_cast<CRecruitmentWindow*>(GH.topInt().get());
  1043. if (crw && crw->dwelling == town)
  1044. crw->availableCreaturesChanged();
  1045. }
  1046. }
  1047. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  1048. {
  1049. EVENT_HANDLER_CALLED_BY_CLIENT;
  1050. if (bonus.type == BonusType::NONE)
  1051. return;
  1052. adventureInt->onHeroChanged(hero);
  1053. if ((bonus.type == BonusType::FLYING_MOVEMENT || bonus.type == BonusType::WATER_WALKING) && !gain)
  1054. {
  1055. //recalculate paths because hero has lost bonus influencing pathfinding
  1056. localState->erasePath(hero);
  1057. }
  1058. }
  1059. void CPlayerInterface::saveGame( BinarySerializer & h, const int version )
  1060. {
  1061. EVENT_HANDLER_CALLED_BY_CLIENT;
  1062. localState->serialize(h, version);
  1063. }
  1064. void CPlayerInterface::loadGame( BinaryDeserializer & h, const int version )
  1065. {
  1066. EVENT_HANDLER_CALLED_BY_CLIENT;
  1067. localState->serialize(h, version);
  1068. firstCall = -1;
  1069. }
  1070. void CPlayerInterface::moveHero( const CGHeroInstance *h, const CGPath& path )
  1071. {
  1072. LOG_TRACE(logGlobal);
  1073. if (!LOCPLINT->makingTurn)
  1074. return;
  1075. if (!h)
  1076. return; //can't find hero
  1077. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  1078. if (showingDialog->get() || !dialogs.empty())
  1079. return;
  1080. setMovementStatus(true);
  1081. if (localState->isHeroSleeping(h))
  1082. localState->setHeroAwaken(h);
  1083. boost::thread moveHeroTask(std::bind(&CPlayerInterface::doMoveHero,this,h,path));
  1084. }
  1085. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  1086. {
  1087. EVENT_HANDLER_CALLED_BY_CLIENT;
  1088. auto onEnd = [=](){ cb->selectionMade(0, queryID); };
  1089. if (stillMoveHero.get() == DURING_MOVE && localState->hasPath(down) && localState->getPath(down).nodes.size() > 1) //to ignore calls on passing through garrisons
  1090. {
  1091. onEnd();
  1092. return;
  1093. }
  1094. waitForAllDialogs();
  1095. auto cgw = std::make_shared<CGarrisonWindow>(up, down, removableUnits);
  1096. cgw->quit->addCallback(onEnd);
  1097. GH.pushInt(cgw);
  1098. }
  1099. /**
  1100. * Shows the dialog that appears when right-clicking an artifact that can be assembled
  1101. * into a combinational one on an artifact screen. Does not require the combination of
  1102. * artifacts to be legal.
  1103. */
  1104. void CPlayerInterface::showArtifactAssemblyDialog(const Artifact * artifact, const Artifact * assembledArtifact, CFunctionList<bool()> onYes)
  1105. {
  1106. std::string text = artifact->getDescriptionTranslated();
  1107. text += "\n\n";
  1108. std::vector<std::shared_ptr<CComponent>> scs;
  1109. if(assembledArtifact)
  1110. {
  1111. // You possess all of the components to...
  1112. text += boost::str(boost::format(CGI->generaltexth->allTexts[732]) % assembledArtifact->getNameTranslated());
  1113. // Picture of assembled artifact at bottom.
  1114. auto sc = std::make_shared<CComponent>(CComponent::artifact, assembledArtifact->getIndex(), 0);
  1115. scs.push_back(sc);
  1116. }
  1117. else
  1118. {
  1119. // Do you wish to disassemble this artifact?
  1120. text += CGI->generaltexth->allTexts[733];
  1121. }
  1122. showYesNoDialog(text, onYes, nullptr, scs);
  1123. }
  1124. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1125. {
  1126. EVENT_HANDLER_CALLED_BY_CLIENT;
  1127. if (pa->packType == typeList.getTypeID<MoveHero>() && stillMoveHero.get() == DURING_MOVE
  1128. && destinationTeleport == ObjectInstanceID())
  1129. stillMoveHero.setn(CONTINUE_MOVE);
  1130. if (destinationTeleport != ObjectInstanceID()
  1131. && pa->packType == typeList.getTypeID<QueryReply>()
  1132. && stillMoveHero.get() == DURING_MOVE)
  1133. { // After teleportation via CGTeleport object is finished
  1134. destinationTeleport = ObjectInstanceID();
  1135. destinationTeleportPos = int3(-1);
  1136. stillMoveHero.setn(CONTINUE_MOVE);
  1137. }
  1138. }
  1139. void CPlayerInterface::showHeroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  1140. {
  1141. heroExchangeStarted(hero1, hero2, QueryID(-1));
  1142. }
  1143. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1144. {
  1145. EVENT_HANDLER_CALLED_BY_CLIENT;
  1146. GH.pushIntT<CExchangeWindow>(hero1, hero2, query);
  1147. }
  1148. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1149. {
  1150. EVENT_HANDLER_CALLED_BY_CLIENT;
  1151. //redraw minimap if owner changed
  1152. if (sop->what == ObjProperty::OWNER)
  1153. {
  1154. const CGObjectInstance * obj = cb->getObj(sop->id);
  1155. if(obj->ID == Obj::TOWN)
  1156. {
  1157. auto town = static_cast<const CGTownInstance *>(obj);
  1158. if(obj->tempOwner == playerID)
  1159. localState->addOwnedTown(town);
  1160. else
  1161. localState->removeOwnedTown(town);
  1162. adventureInt->onTownChanged(town);
  1163. }
  1164. std::set<int3> pos = obj->getBlockedPos();
  1165. std::unordered_set<int3> upos(pos.begin(), pos.end());
  1166. adventureInt->onMapTilesChanged(upos);
  1167. assert(cb->getTownsInfo().size() == localState->getOwnedTowns().size());
  1168. }
  1169. }
  1170. void CPlayerInterface::initializeHeroTownList()
  1171. {
  1172. if(localState->getWanderingHeroes().empty())
  1173. {
  1174. for(auto & hero : cb->getHeroesInfo())
  1175. {
  1176. if(!hero->inTownGarrison)
  1177. localState->addWanderingHero(hero);
  1178. }
  1179. }
  1180. if(localState->getOwnedTowns().empty())
  1181. {
  1182. for(auto & town : cb->getTownsInfo())
  1183. localState->addOwnedTown(town);
  1184. }
  1185. if(adventureInt)
  1186. adventureInt->onHeroChanged(nullptr);
  1187. }
  1188. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  1189. {
  1190. EVENT_HANDLER_CALLED_BY_CLIENT;
  1191. waitWhileDialog();
  1192. auto recruitCb = [=](CreatureID id, int count)
  1193. {
  1194. LOCPLINT->cb->recruitCreatures(dwelling, dst, id, count, -1);
  1195. };
  1196. GH.pushIntT<CRecruitmentWindow>(dwelling, level, dst, recruitCb);
  1197. }
  1198. void CPlayerInterface::waitWhileDialog(bool unlockPim)
  1199. {
  1200. if (GH.amIGuiThread())
  1201. {
  1202. logGlobal->warn("Cannot wait for dialogs in gui thread (deadlock risk)!");
  1203. return;
  1204. }
  1205. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1206. boost::unique_lock<boost::mutex> un(showingDialog->mx);
  1207. while(showingDialog->data)
  1208. showingDialog->cond.wait(un);
  1209. }
  1210. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1211. {
  1212. EVENT_HANDLER_CALLED_BY_CLIENT;
  1213. auto state = obj->shipyardStatus();
  1214. TResources cost;
  1215. obj->getBoatCost(cost);
  1216. GH.pushIntT<CShipyardWindow>(cost, state, obj->getBoatType(), [=](){ cb->buildBoat(obj); });
  1217. }
  1218. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1219. {
  1220. EVENT_HANDLER_CALLED_BY_CLIENT;
  1221. //we might have built a boat in shipyard in opened town screen
  1222. if (obj->ID == Obj::BOAT
  1223. && LOCPLINT->castleInt
  1224. && obj->visitablePos() == LOCPLINT->castleInt->town->bestLocation())
  1225. {
  1226. CCS->soundh->playSound(soundBase::newBuilding);
  1227. LOCPLINT->castleInt->addBuilding(BuildingID::SHIP);
  1228. }
  1229. }
  1230. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1231. {
  1232. EVENT_HANDLER_CALLED_BY_CLIENT;
  1233. waitWhileDialog();
  1234. CCS->curh->hide();
  1235. adventureInt->centerOnTile(pos);
  1236. if (focusTime)
  1237. {
  1238. GH.totalRedraw();
  1239. {
  1240. auto unlockPim = vstd::makeUnlockGuard(*pim);
  1241. IgnoreEvents ignore(*this);
  1242. boost::this_thread::sleep(boost::posix_time::milliseconds(focusTime));
  1243. }
  1244. }
  1245. CCS->curh->show();
  1246. }
  1247. void CPlayerInterface::objectRemoved(const CGObjectInstance * obj)
  1248. {
  1249. EVENT_HANDLER_CALLED_BY_CLIENT;
  1250. if(LOCPLINT->cb->getCurrentPlayer() == playerID && obj->getRemovalSound())
  1251. {
  1252. waitWhileDialog();
  1253. CCS->soundh->playSound(obj->getRemovalSound().value());
  1254. }
  1255. CGI->mh->waitForOngoingAnimations();
  1256. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1257. {
  1258. const CGHeroInstance * h = static_cast<const CGHeroInstance *>(obj);
  1259. heroKilled(h);
  1260. }
  1261. GH.fakeMouseMove();
  1262. }
  1263. void CPlayerInterface::objectRemovedAfter()
  1264. {
  1265. EVENT_HANDLER_CALLED_BY_CLIENT;
  1266. adventureInt->onMapTilesChanged(boost::none);
  1267. }
  1268. void CPlayerInterface::playerBlocked(int reason, bool start)
  1269. {
  1270. if(reason == PlayerBlocked::EReason::UPCOMING_BATTLE)
  1271. {
  1272. if(CSH->howManyPlayerInterfaces() > 1 && LOCPLINT != this && LOCPLINT->makingTurn == false)
  1273. {
  1274. //one of our players who isn't last in order got attacked not by our another player (happens for example in hotseat mode)
  1275. boost::unique_lock<boost::mutex> lock(eventsM); //TODO: copied from yourTurn, no idea if it's needed
  1276. LOCPLINT = this;
  1277. GH.curInt = this;
  1278. adventureInt->onCurrentPlayerChanged(playerID);
  1279. std::string msg = CGI->generaltexth->translate("vcmi.adventureMap.playerAttacked");
  1280. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  1281. std::vector<std::shared_ptr<CComponent>> cmp;
  1282. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  1283. makingTurn = true; //workaround for stiff showInfoDialog implementation
  1284. showInfoDialog(msg, cmp);
  1285. makingTurn = false;
  1286. }
  1287. }
  1288. }
  1289. void CPlayerInterface::update()
  1290. {
  1291. // Make sure that gamestate won't change when GUI objects may obtain its parts on event processing or drawing request
  1292. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  1293. // While mutexes were locked away we may be have stopped being the active interface
  1294. if (LOCPLINT != this)
  1295. return;
  1296. //if there are any waiting dialogs, show them
  1297. if ((CSH->howManyPlayerInterfaces() <= 1 || makingTurn) && !dialogs.empty() && !showingDialog->get())
  1298. {
  1299. showingDialog->set(true);
  1300. GH.pushInt(dialogs.front());
  1301. dialogs.pop_front();
  1302. }
  1303. assert(adventureInt);
  1304. // Handles mouse and key input
  1305. GH.updateTime();
  1306. GH.handleEvents();
  1307. GH.simpleRedraw();
  1308. }
  1309. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1310. {
  1311. using namespace boost::filesystem;
  1312. using namespace boost::algorithm;
  1313. path gamesDir = VCMIDirs::get().userSavePath();
  1314. std::map<std::time_t, int> dates; //save number => datestamp
  1315. const directory_iterator enddir;
  1316. if (!exists(gamesDir))
  1317. create_directory(gamesDir);
  1318. else
  1319. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1320. {
  1321. if (is_regular_file(dir->status()))
  1322. {
  1323. std::string name = dir->path().filename().string();
  1324. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1325. {
  1326. char nr = name[namePrefix.size()];
  1327. if (std::isdigit(nr))
  1328. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1329. }
  1330. }
  1331. }
  1332. if (!dates.empty())
  1333. return (--dates.end())->second; //return latest file number
  1334. return 0;
  1335. }
  1336. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1337. {
  1338. EVENT_HANDLER_CALLED_BY_CLIENT;
  1339. if (player == playerID)
  1340. {
  1341. if (victoryLossCheckResult.loss())
  1342. showInfoDialog(CGI->generaltexth->allTexts[95]);
  1343. assert(GH.curInt == LOCPLINT);
  1344. auto previousInterface = LOCPLINT; //without multiple player interfaces some of lines below are useless, but for hotseat we wanna swap player interface temporarily
  1345. LOCPLINT = this; //this is needed for dialog to show and avoid freeze, dialog showing logic should be reworked someday
  1346. GH.curInt = this; //waiting for dialogs requires this to get events
  1347. if(!makingTurn)
  1348. {
  1349. makingTurn = true; //also needed for dialog to show with current implementation
  1350. waitForAllDialogs();
  1351. makingTurn = false;
  1352. }
  1353. else
  1354. waitForAllDialogs();
  1355. GH.curInt = previousInterface;
  1356. LOCPLINT = previousInterface;
  1357. if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool()) //all human players eliminated
  1358. {
  1359. if(adventureInt)
  1360. {
  1361. GH.terminate_cond->setn(true);
  1362. GH.popInts(GH.listInt.size());
  1363. adventureInt.reset();
  1364. }
  1365. }
  1366. if (victoryLossCheckResult.victory() && LOCPLINT == this)
  1367. {
  1368. // end game if current human player has won
  1369. CSH->sendClientDisconnecting();
  1370. requestReturningToMainMenu(true);
  1371. }
  1372. else if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool())
  1373. {
  1374. //all human players eliminated
  1375. CSH->sendClientDisconnecting();
  1376. requestReturningToMainMenu(false);
  1377. }
  1378. if (GH.curInt == this)
  1379. GH.curInt = nullptr;
  1380. }
  1381. else
  1382. {
  1383. if (victoryLossCheckResult.loss() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME) //enemy has lost
  1384. {
  1385. std::string str = victoryLossCheckResult.messageToSelf;
  1386. boost::algorithm::replace_first(str, "%s", CGI->generaltexth->capColors[player.getNum()]);
  1387. showInfoDialog(str, std::vector<std::shared_ptr<CComponent>>(1, std::make_shared<CComponent>(CComponent::flag, player.getNum(), 0)));
  1388. }
  1389. }
  1390. }
  1391. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1392. {
  1393. EVENT_HANDLER_CALLED_BY_CLIENT;
  1394. }
  1395. void CPlayerInterface::showPuzzleMap()
  1396. {
  1397. EVENT_HANDLER_CALLED_BY_CLIENT;
  1398. waitWhileDialog();
  1399. //TODO: interface should not know the real position of Grail...
  1400. double ratio = 0;
  1401. int3 grailPos = cb->getGrailPos(&ratio);
  1402. GH.pushIntT<CPuzzleWindow>(grailPos, ratio);
  1403. }
  1404. void CPlayerInterface::viewWorldMap()
  1405. {
  1406. adventureInt->openWorldView();
  1407. }
  1408. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  1409. {
  1410. EVENT_HANDLER_CALLED_BY_CLIENT;
  1411. if(dynamic_cast<CSpellWindow *>(GH.topInt().get()))
  1412. GH.popInts(1);
  1413. if(spellID == SpellID::FLY || spellID == SpellID::WATER_WALK)
  1414. localState->erasePath(caster);
  1415. const spells::Spell * spell = CGI->spells()->getByIndex(spellID);
  1416. auto castSoundPath = spell->getCastSound();
  1417. if(!castSoundPath.empty())
  1418. CCS->soundh->playSound(castSoundPath);
  1419. }
  1420. void CPlayerInterface::tryDiggging(const CGHeroInstance * h)
  1421. {
  1422. int msgToShow = -1;
  1423. const auto diggingStatus = h->diggingStatus();
  1424. switch(diggingStatus)
  1425. {
  1426. case EDiggingStatus::CAN_DIG:
  1427. break;
  1428. case EDiggingStatus::LACK_OF_MOVEMENT:
  1429. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  1430. break;
  1431. case EDiggingStatus::TILE_OCCUPIED:
  1432. msgToShow = 97; //Try searching on clear ground.
  1433. break;
  1434. case EDiggingStatus::WRONG_TERRAIN:
  1435. msgToShow = 60; ////Try looking on land!
  1436. break;
  1437. case EDiggingStatus::BACKPACK_IS_FULL:
  1438. msgToShow = 247; //Searching for the Grail is fruitless...
  1439. break;
  1440. default:
  1441. assert(0);
  1442. }
  1443. if(msgToShow < 0)
  1444. cb->dig(h);
  1445. else
  1446. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  1447. }
  1448. void CPlayerInterface::battleNewRoundFirst( int round )
  1449. {
  1450. EVENT_HANDLER_CALLED_BY_CLIENT;
  1451. BATTLE_EVENT_POSSIBLE_RETURN;
  1452. battleInt->newRoundFirst(round);
  1453. }
  1454. void CPlayerInterface::stopMovement()
  1455. {
  1456. if (stillMoveHero.get() == DURING_MOVE)//if we are in the middle of hero movement
  1457. stillMoveHero.setn(STOP_MOVE); //after showing dialog movement will be stopped
  1458. }
  1459. void CPlayerInterface::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  1460. {
  1461. EVENT_HANDLER_CALLED_BY_CLIENT;
  1462. if(market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  1463. GH.pushIntT<CAltarWindow>(market, visitor, EMarketMode::ARTIFACT_EXP);
  1464. else if(market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  1465. GH.pushIntT<CAltarWindow>(market, visitor, EMarketMode::CREATURE_EXP);
  1466. else if(market->allowsTrade(EMarketMode::CREATURE_UNDEAD))
  1467. GH.pushIntT<CTransformerWindow>(market, visitor);
  1468. else if(!market->availableModes().empty())
  1469. GH.pushIntT<CMarketplaceWindow>(market, visitor, market->availableModes().front());
  1470. }
  1471. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  1472. {
  1473. EVENT_HANDLER_CALLED_BY_CLIENT;
  1474. GH.pushIntT<CUniversityWindow>(visitor, market);
  1475. }
  1476. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  1477. {
  1478. EVENT_HANDLER_CALLED_BY_CLIENT;
  1479. GH.pushIntT<CHillFortWindow>(visitor, object);
  1480. }
  1481. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket * bm)
  1482. {
  1483. EVENT_HANDLER_CALLED_BY_CLIENT;
  1484. if (CMarketplaceWindow *cmw = dynamic_cast<CMarketplaceWindow*>(GH.topInt().get()))
  1485. cmw->artifactsChanged(false);
  1486. }
  1487. void CPlayerInterface::showTavernWindow(const CGObjectInstance *townOrTavern)
  1488. {
  1489. EVENT_HANDLER_CALLED_BY_CLIENT;
  1490. GH.pushIntT<CTavernWindow>(townOrTavern);
  1491. }
  1492. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  1493. {
  1494. EVENT_HANDLER_CALLED_BY_CLIENT;
  1495. GH.pushIntT<CThievesGuildWindow>(obj);
  1496. }
  1497. void CPlayerInterface::showQuestLog()
  1498. {
  1499. EVENT_HANDLER_CALLED_BY_CLIENT;
  1500. GH.pushIntT<CQuestLog>(LOCPLINT->cb->getMyQuests());
  1501. }
  1502. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  1503. {
  1504. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  1505. {
  1506. MetaString txt;
  1507. obj->getProblemText(txt);
  1508. showInfoDialog(txt.toString());
  1509. }
  1510. else
  1511. showShipyardDialog(obj);
  1512. }
  1513. void CPlayerInterface::requestReturningToMainMenu(bool won)
  1514. {
  1515. if(won && cb->getStartInfo()->campState)
  1516. CSH->startCampaignScenario(cb->getStartInfo()->campState);
  1517. else
  1518. GH.pushUserEvent(EUserEvent::RETURN_TO_MAIN_MENU);
  1519. }
  1520. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  1521. {
  1522. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1523. if(hero)
  1524. {
  1525. auto art = hero->getArt(al.slot);
  1526. if(art == nullptr)
  1527. {
  1528. logGlobal->error("artifact location %d points to nothing",
  1529. al.slot.num);
  1530. return;
  1531. }
  1532. ArtifactUtilsClient::askToAssemble(hero, al.slot);
  1533. }
  1534. }
  1535. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  1536. {
  1537. EVENT_HANDLER_CALLED_BY_CLIENT;
  1538. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1539. adventureInt->onHeroChanged(hero);
  1540. }
  1541. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  1542. {
  1543. EVENT_HANDLER_CALLED_BY_CLIENT;
  1544. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1545. adventureInt->onHeroChanged(hero);
  1546. for(auto isa : GH.listInt)
  1547. {
  1548. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1549. if (artWin)
  1550. artWin->artifactRemoved(al);
  1551. }
  1552. waitWhileDialog();
  1553. }
  1554. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1555. {
  1556. EVENT_HANDLER_CALLED_BY_CLIENT;
  1557. auto hero = std::visit(HeroObjectRetriever(), dst.artHolder);
  1558. adventureInt->onHeroChanged(hero);
  1559. bool redraw = true;
  1560. // If a bulk transfer has arrived, then redrawing only the last art movement.
  1561. if(numOfMovedArts != 0)
  1562. {
  1563. numOfMovedArts--;
  1564. if(numOfMovedArts != 0)
  1565. redraw = false;
  1566. }
  1567. for(auto isa : GH.listInt)
  1568. {
  1569. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1570. if (artWin)
  1571. artWin->artifactMoved(src, dst, redraw);
  1572. }
  1573. waitWhileDialog();
  1574. }
  1575. void CPlayerInterface::bulkArtMovementStart(size_t numOfArts)
  1576. {
  1577. numOfMovedArts = numOfArts;
  1578. }
  1579. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1580. {
  1581. EVENT_HANDLER_CALLED_BY_CLIENT;
  1582. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1583. adventureInt->onHeroChanged(hero);
  1584. for(auto isa : GH.listInt)
  1585. {
  1586. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1587. if (artWin)
  1588. artWin->artifactAssembled(al);
  1589. }
  1590. }
  1591. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1592. {
  1593. EVENT_HANDLER_CALLED_BY_CLIENT;
  1594. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1595. adventureInt->onHeroChanged(hero);
  1596. for(auto isa : GH.listInt)
  1597. {
  1598. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1599. if (artWin)
  1600. artWin->artifactDisassembled(al);
  1601. }
  1602. }
  1603. void CPlayerInterface::waitForAllDialogs(bool unlockPim)
  1604. {
  1605. while(!dialogs.empty())
  1606. {
  1607. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1608. boost::this_thread::sleep(boost::posix_time::milliseconds(5));
  1609. }
  1610. waitWhileDialog(unlockPim);
  1611. }
  1612. void CPlayerInterface::proposeLoadingGame()
  1613. {
  1614. showYesNoDialog(CGI->generaltexth->allTexts[68], [](){ GH.pushUserEvent(EUserEvent::RETURN_TO_MENU_LOAD); }, nullptr);
  1615. }
  1616. bool CPlayerInterface::capturedAllEvents()
  1617. {
  1618. if(duringMovement)
  1619. {
  1620. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  1621. return true;
  1622. }
  1623. bool needToLockAdventureMap = adventureInt && adventureInt->active && CGI->mh->hasOngoingAnimations();
  1624. if (ignoreEvents || needToLockAdventureMap || isAutoFightOn)
  1625. {
  1626. boost::unique_lock<boost::mutex> un(eventsM);
  1627. while(!SDLEventsQueue.empty())
  1628. {
  1629. SDLEventsQueue.pop();
  1630. }
  1631. return true;
  1632. }
  1633. return false;
  1634. }
  1635. void CPlayerInterface::setMovementStatus(bool value)
  1636. {
  1637. duringMovement = value;
  1638. if (value)
  1639. {
  1640. CCS->curh->hide();
  1641. }
  1642. else
  1643. {
  1644. CCS->curh->show();
  1645. }
  1646. }
  1647. void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path)
  1648. {
  1649. int i = 1;
  1650. auto getObj = [&](int3 coord, bool ignoreHero)
  1651. {
  1652. return cb->getTile(h->convertToVisitablePos(coord))->topVisitableObj(ignoreHero);
  1653. };
  1654. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  1655. {
  1656. if (action != CGPathNode::TELEPORT_NORMAL &&
  1657. action != CGPathNode::TELEPORT_BLOCKING_VISIT &&
  1658. action != CGPathNode::TELEPORT_BATTLE)
  1659. {
  1660. return false;
  1661. }
  1662. return true;
  1663. };
  1664. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1665. {
  1666. if (CGTeleport::isConnected(currentObject, nextObjectTop))
  1667. return nextObjectTop;
  1668. if (nextObjectTop && nextObjectTop->ID == Obj::HERO &&
  1669. CGTeleport::isConnected(currentObject, nextObject))
  1670. {
  1671. return nextObject;
  1672. }
  1673. return nullptr;
  1674. };
  1675. boost::unique_lock<boost::mutex> un(stillMoveHero.mx);
  1676. stillMoveHero.data = CONTINUE_MOVE;
  1677. auto doMovement = [&](int3 dst, bool transit)
  1678. {
  1679. stillMoveHero.data = WAITING_MOVE;
  1680. cb->moveHero(h, dst, transit);
  1681. while(stillMoveHero.data != STOP_MOVE && stillMoveHero.data != CONTINUE_MOVE)
  1682. stillMoveHero.cond.wait(un);
  1683. };
  1684. {
  1685. for (auto & elem : path.nodes)
  1686. elem.coord = h->convertFromVisitablePos(elem.coord);
  1687. TerrainId currentTerrain = ETerrainId::NONE;
  1688. TerrainId newTerrain;
  1689. bool wasOnRoad = true;
  1690. int sh = -1;
  1691. auto canStop = [&](CGPathNode * node) -> bool
  1692. {
  1693. if (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  1694. return true;
  1695. if (node->accessible == CGPathNode::ACCESSIBLE)
  1696. return true;
  1697. return false;
  1698. };
  1699. for (i=(int)path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE || !canStop(&path.nodes[i])); i--)
  1700. {
  1701. int3 prevCoord = path.nodes[i].coord;
  1702. int3 nextCoord = path.nodes[i-1].coord;
  1703. auto prevRoad = cb->getTile(h->convertToVisitablePos(prevCoord))->roadType;
  1704. auto nextRoad = cb->getTile(h->convertToVisitablePos(nextCoord))->roadType;
  1705. bool movingOnRoad = prevRoad->getId() != Road::NO_ROAD && nextRoad->getId() != Road::NO_ROAD;
  1706. auto prevObject = getObj(prevCoord, prevCoord == h->pos);
  1707. auto nextObjectTop = getObj(nextCoord, false);
  1708. auto nextObject = getObj(nextCoord, true);
  1709. auto destTeleportObj = getDestTeleportObj(prevObject, nextObjectTop, nextObject);
  1710. if (isTeleportAction(path.nodes[i-1].action) && destTeleportObj != nullptr)
  1711. {
  1712. CCS->soundh->stopSound(sh);
  1713. destinationTeleport = destTeleportObj->id;
  1714. destinationTeleportPos = nextCoord;
  1715. doMovement(h->pos, false);
  1716. if (path.nodes[i-1].action == CGPathNode::TELEPORT_BLOCKING_VISIT
  1717. || path.nodes[i-1].action == CGPathNode::TELEPORT_BATTLE)
  1718. {
  1719. destinationTeleport = ObjectInstanceID();
  1720. destinationTeleportPos = int3(-1);
  1721. }
  1722. if(i != path.nodes.size() - 1)
  1723. {
  1724. if (movingOnRoad)
  1725. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(currentTerrain)->horseSound, -1);
  1726. else
  1727. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(currentTerrain)->horseSoundPenalty, -1);
  1728. }
  1729. continue;
  1730. }
  1731. if (path.nodes[i-1].turns)
  1732. { //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1733. stillMoveHero.data = STOP_MOVE;
  1734. break;
  1735. }
  1736. // Start a new sound for the hero movement or let the existing one carry on.
  1737. #if 0
  1738. // TODO
  1739. if (hero is flying && sh == -1)
  1740. sh = CCS->soundh->playSound(soundBase::horseFlying, -1);
  1741. #endif
  1742. {
  1743. newTerrain = cb->getTile(h->convertToVisitablePos(prevCoord))->terType->getId();
  1744. if(newTerrain != currentTerrain || wasOnRoad != movingOnRoad)
  1745. {
  1746. CCS->soundh->stopSound(sh);
  1747. if (movingOnRoad)
  1748. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(newTerrain)->horseSound, -1);
  1749. else
  1750. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(newTerrain)->horseSoundPenalty, -1);
  1751. currentTerrain = newTerrain;
  1752. wasOnRoad = movingOnRoad;
  1753. }
  1754. }
  1755. assert(h->pos.z == nextCoord.z); // Z should change only if it's movement via teleporter and in this case this code shouldn't be executed at all
  1756. int3 endpos(nextCoord.x, nextCoord.y, h->pos.z);
  1757. logGlobal->trace("Requesting hero movement to %s", endpos.toString());
  1758. bool useTransit = false;
  1759. if ((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless
  1760. && (CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i-2].coord, false))
  1761. || CGTeleport::isTeleport(nextObjectTop)))
  1762. { // Hero should be able to go through object if it's allow transit
  1763. useTransit = true;
  1764. }
  1765. else if (path.nodes[i-1].layer == EPathfindingLayer::AIR)
  1766. useTransit = true;
  1767. doMovement(endpos, useTransit);
  1768. logGlobal->trace("Resuming %s", __FUNCTION__);
  1769. bool guarded = cb->isInTheMap(cb->getGuardingCreaturePosition(endpos - int3(1, 0, 0)));
  1770. if ((!useTransit && guarded) || showingDialog->get() == true) // Abort movement if a guard was fought or there is a dialog to display (Mantis #1136)
  1771. break;
  1772. }
  1773. CCS->soundh->stopSound(sh);
  1774. }
  1775. //Update cursor so icon can change if needed when it reappears; doesn;'t apply if a dialog box pops up at the end of the movement
  1776. if (!showingDialog->get())
  1777. GH.fakeMouseMove();
  1778. CGI->mh->waitForOngoingAnimations();
  1779. setMovementStatus(false);
  1780. }
  1781. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions, bool showTerrain)
  1782. {
  1783. EVENT_HANDLER_CALLED_BY_CLIENT;
  1784. adventureInt->openWorldView(objectPositions, showTerrain );
  1785. }