CPlayerInterface.cpp 94 KB

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