CPlayerInterface.cpp 93 KB

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