CPlayerInterface.cpp 76 KB

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