CPlayerInterface.cpp 94 KB

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