CPlayerInterface.cpp 93 KB

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