CPlayerInterface.cpp 74 KB

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