CPlayerInterface.cpp 93 KB

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