CPlayerInterface.cpp 63 KB

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