VCAI.cpp 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587
  1. /*
  2. * VCAI.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "VCAI.h"
  12. #include "Fuzzy.h"
  13. #include "ResourceManager.h"
  14. #include "../../lib/UnlockGuard.h"
  15. #include "../../lib/mapObjects/MapObjects.h"
  16. #include "../../lib/CConfigHandler.h"
  17. #include "../../lib/CHeroHandler.h"
  18. #include "../../lib/CModHandler.h"
  19. #include "../../lib/CGameState.h"
  20. #include "../../lib/NetPacks.h"
  21. #include "../../lib/serializer/CTypeList.h"
  22. #include "../../lib/serializer/BinarySerializer.h"
  23. #include "../../lib/serializer/BinaryDeserializer.h"
  24. #include "AIhelper.h"
  25. extern FuzzyHelper * fh;
  26. class CGVisitableOPW;
  27. const double SAFE_ATTACK_CONSTANT = 1.5;
  28. //one thread may be turn of AI and another will be handling a side effect for AI2
  29. boost::thread_specific_ptr<CCallback> cb;
  30. boost::thread_specific_ptr<VCAI> ai;
  31. extern boost::thread_specific_ptr<AIhelper> ah;
  32. //std::map<int, std::map<int, int> > HeroView::infosCount;
  33. //helper RAII to manage global ai/cb ptrs
  34. struct SetGlobalState
  35. {
  36. SetGlobalState(VCAI * AI)
  37. {
  38. assert(!ai.get());
  39. assert(!cb.get());
  40. ai.reset(AI);
  41. cb.reset(AI->myCb.get());
  42. if (!ah.get())
  43. ah.reset(new AIhelper());
  44. ah->setAI(AI); //does this make any sense?
  45. ah->setCB(cb.get());
  46. }
  47. ~SetGlobalState()
  48. {
  49. //TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
  50. //TODO: to ensure that, make rm unique_ptr
  51. ai.release();
  52. cb.release();
  53. }
  54. };
  55. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  56. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  57. #define MAKING_TURN SET_GLOBAL_STATE(this)
  58. void foreach_tile(std::vector<std::vector<std::vector<unsigned char>>> & vectors, std::function<void(unsigned char & in)> foo)
  59. {
  60. for(auto & vector : vectors)
  61. {
  62. for(auto j = vector.begin(); j != vector.end(); j++)
  63. {
  64. for(auto & elem : *j)
  65. foo(elem);
  66. }
  67. }
  68. }
  69. struct ObjInfo
  70. {
  71. int3 pos;
  72. std::string name;
  73. ObjInfo(){}
  74. ObjInfo(const CGObjectInstance * obj)
  75. : pos(obj->pos), name(obj->getObjectName())
  76. {
  77. }
  78. };
  79. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  80. VCAI::VCAI()
  81. {
  82. LOG_TRACE(logAi);
  83. makingTurn = nullptr;
  84. destinationTeleport = ObjectInstanceID();
  85. destinationTeleportPos = int3(-1);
  86. }
  87. VCAI::~VCAI()
  88. {
  89. LOG_TRACE(logAi);
  90. finish();
  91. }
  92. void VCAI::availableCreaturesChanged(const CGDwelling * town)
  93. {
  94. LOG_TRACE(logAi);
  95. NET_EVENT_HANDLER;
  96. }
  97. void VCAI::heroMoved(const TryMoveHero & details)
  98. {
  99. LOG_TRACE(logAi);
  100. NET_EVENT_HANDLER;
  101. validateObject(details.id); //enemy hero may have left visible area
  102. auto hero = cb->getHero(details.id);
  103. cachedSectorMaps.clear();
  104. const int3 from = CGHeroInstance::convertPosition(details.start, false);
  105. const int3 to = CGHeroInstance::convertPosition(details.end, false);
  106. const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from));
  107. const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to));
  108. if(details.result == TryMoveHero::TELEPORTATION)
  109. {
  110. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  111. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  112. if(t1 && t2)
  113. {
  114. if(cb->isTeleportChannelBidirectional(t1->channel))
  115. {
  116. if(o1->ID == Obj::SUBTERRANEAN_GATE && o1->ID == o2->ID) // We need to only add subterranean gates in knownSubterraneanGates. Used for features not yet ported to use teleport channels
  117. {
  118. knownSubterraneanGates[o1] = o2;
  119. knownSubterraneanGates[o2] = o1;
  120. logAi->debug("Found a pair of subterranean gates between %s and %s!", from.toString(), to.toString());
  121. }
  122. }
  123. }
  124. //FIXME: teleports are not correctly visited
  125. unreserveObject(hero, t1);
  126. unreserveObject(hero, t2);
  127. }
  128. else if(details.result == TryMoveHero::EMBARK && hero)
  129. {
  130. //make sure AI not attempt to visit used boat
  131. validateObject(hero->boat);
  132. }
  133. else if(details.result == TryMoveHero::DISEMBARK && o1)
  134. {
  135. auto boat = dynamic_cast<const CGBoat *>(o1);
  136. if(boat)
  137. addVisitableObj(boat);
  138. }
  139. }
  140. void VCAI::heroInGarrisonChange(const CGTownInstance * town)
  141. {
  142. LOG_TRACE(logAi);
  143. NET_EVENT_HANDLER;
  144. }
  145. void VCAI::centerView(int3 pos, int focusTime)
  146. {
  147. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  148. NET_EVENT_HANDLER;
  149. }
  150. void VCAI::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
  151. {
  152. LOG_TRACE(logAi);
  153. NET_EVENT_HANDLER;
  154. }
  155. void VCAI::artifactAssembled(const ArtifactLocation & al)
  156. {
  157. LOG_TRACE(logAi);
  158. NET_EVENT_HANDLER;
  159. }
  160. void VCAI::showTavernWindow(const CGObjectInstance * townOrTavern)
  161. {
  162. LOG_TRACE(logAi);
  163. NET_EVENT_HANDLER;
  164. }
  165. void VCAI::showThievesGuildWindow(const CGObjectInstance * obj)
  166. {
  167. LOG_TRACE(logAi);
  168. NET_EVENT_HANDLER;
  169. }
  170. void VCAI::playerBlocked(int reason, bool start)
  171. {
  172. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  173. NET_EVENT_HANDLER;
  174. if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
  175. status.setBattle(UPCOMING_BATTLE);
  176. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  177. status.setMove(start);
  178. }
  179. void VCAI::showPuzzleMap()
  180. {
  181. LOG_TRACE(logAi);
  182. NET_EVENT_HANDLER;
  183. }
  184. void VCAI::showShipyardDialog(const IShipyard * obj)
  185. {
  186. LOG_TRACE(logAi);
  187. NET_EVENT_HANDLER;
  188. }
  189. void VCAI::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  190. {
  191. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf);
  192. NET_EVENT_HANDLER;
  193. logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.getStr(), player, player.getStr(), (victoryLossCheckResult.victory() ? "won" : "lost"));
  194. if(player == playerID)
  195. {
  196. if(victoryLossCheckResult.victory())
  197. {
  198. logAi->debug("VCAI: I won! Incredible!");
  199. logAi->debug("Turn nr %d", myCb->getDate());
  200. }
  201. else
  202. {
  203. logAi->debug("VCAI: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.getStr());
  204. }
  205. finish();
  206. }
  207. }
  208. void VCAI::artifactPut(const ArtifactLocation & al)
  209. {
  210. LOG_TRACE(logAi);
  211. NET_EVENT_HANDLER;
  212. }
  213. void VCAI::artifactRemoved(const ArtifactLocation & al)
  214. {
  215. LOG_TRACE(logAi);
  216. NET_EVENT_HANDLER;
  217. }
  218. void VCAI::artifactDisassembled(const ArtifactLocation & al)
  219. {
  220. LOG_TRACE(logAi);
  221. NET_EVENT_HANDLER;
  222. }
  223. void VCAI::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  224. {
  225. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
  226. NET_EVENT_HANDLER;
  227. if(start && visitedObj) //we can end visit with null object, anyway
  228. {
  229. markObjectVisited(visitedObj);
  230. unreserveObject(visitor, visitedObj);
  231. completeGoal(sptr(Goals::GetObj(visitedObj->id.getNum()).sethero(visitor))); //we don't need to visit it anymore
  232. //TODO: what if we visited one-time visitable object that was reserved by another hero (shouldn't, but..)
  233. }
  234. status.heroVisit(visitedObj, start);
  235. }
  236. void VCAI::availableArtifactsChanged(const CGBlackMarket * bm)
  237. {
  238. LOG_TRACE(logAi);
  239. NET_EVENT_HANDLER;
  240. }
  241. void VCAI::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
  242. {
  243. LOG_TRACE(logAi);
  244. NET_EVENT_HANDLER;
  245. //buildArmyIn(town);
  246. //moveCreaturesToHero(town);
  247. }
  248. void VCAI::tileHidden(const std::unordered_set<int3, ShashInt3> & pos)
  249. {
  250. LOG_TRACE(logAi);
  251. NET_EVENT_HANDLER;
  252. validateVisitableObjs();
  253. clearPathsInfo();
  254. }
  255. void VCAI::tileRevealed(const std::unordered_set<int3, ShashInt3> & pos)
  256. {
  257. LOG_TRACE(logAi);
  258. NET_EVENT_HANDLER;
  259. for(int3 tile : pos)
  260. {
  261. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  262. addVisitableObj(obj);
  263. }
  264. clearPathsInfo();
  265. }
  266. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  267. {
  268. LOG_TRACE(logAi);
  269. NET_EVENT_HANDLER;
  270. auto firstHero = cb->getHero(hero1);
  271. auto secondHero = cb->getHero(hero2);
  272. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->name % firstHero->tempOwner % secondHero->name % secondHero->tempOwner));
  273. requestActionASAP([=]()
  274. {
  275. float goalpriority1 = 0, goalpriority2 = 0;
  276. auto firstGoal = getGoal(firstHero);
  277. if(firstGoal->goalType == Goals::GATHER_ARMY)
  278. goalpriority1 = firstGoal->priority;
  279. auto secondGoal = getGoal(secondHero);
  280. if(secondGoal->goalType == Goals::GATHER_ARMY)
  281. goalpriority2 = secondGoal->priority;
  282. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  283. {
  284. this->pickBestCreatures(h1, h2);
  285. this->pickBestArtifacts(h1, h2);
  286. };
  287. //Do not attempt army or artifacts exchange if we visited ally player
  288. //Visits can still be useful if hero have skills like Scholar
  289. if(firstHero->tempOwner != secondHero->tempOwner)
  290. {
  291. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  292. }
  293. else if(goalpriority1 > goalpriority2)
  294. {
  295. transferFrom2to1(firstHero, secondHero);
  296. }
  297. else if(goalpriority1 < goalpriority2)
  298. {
  299. transferFrom2to1(secondHero, firstHero);
  300. }
  301. else //regular criteria
  302. {
  303. if(firstHero->getFightingStrength() > secondHero->getFightingStrength() && canGetArmy(firstHero, secondHero))
  304. transferFrom2to1(firstHero, secondHero);
  305. else if(canGetArmy(secondHero, firstHero))
  306. transferFrom2to1(secondHero, firstHero);
  307. }
  308. completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
  309. completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
  310. answerQuery(query, 0);
  311. });
  312. }
  313. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  314. {
  315. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  316. NET_EVENT_HANDLER;
  317. }
  318. void VCAI::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level)
  319. {
  320. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  321. NET_EVENT_HANDLER;
  322. }
  323. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  324. {
  325. LOG_TRACE(logAi);
  326. NET_EVENT_HANDLER;
  327. }
  328. void VCAI::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  329. {
  330. LOG_TRACE(logAi);
  331. NET_EVENT_HANDLER;
  332. }
  333. void VCAI::newObject(const CGObjectInstance * obj)
  334. {
  335. LOG_TRACE(logAi);
  336. NET_EVENT_HANDLER;
  337. if(obj->isVisitable())
  338. addVisitableObj(obj);
  339. cachedSectorMaps.clear();
  340. }
  341. void VCAI::objectRemoved(const CGObjectInstance * obj)
  342. {
  343. LOG_TRACE(logAi);
  344. NET_EVENT_HANDLER;
  345. vstd::erase_if_present(visitableObjs, obj);
  346. vstd::erase_if_present(alreadyVisited, obj);
  347. for(auto h : cb->getHeroesInfo())
  348. unreserveObject(h, obj);
  349. //TODO: Find better way to handle hero boat removal
  350. if(auto hero = dynamic_cast<const CGHeroInstance *>(obj))
  351. {
  352. if(hero->boat)
  353. {
  354. vstd::erase_if_present(visitableObjs, hero->boat);
  355. vstd::erase_if_present(alreadyVisited, hero->boat);
  356. for(auto h : cb->getHeroesInfo())
  357. unreserveObject(h, hero->boat);
  358. }
  359. }
  360. cachedSectorMaps.clear(); //invalidate all paths
  361. //TODO
  362. //there are other places where CGObjectinstance ptrs are stored...
  363. //
  364. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  365. {
  366. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  367. }
  368. }
  369. void VCAI::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  370. {
  371. LOG_TRACE(logAi);
  372. NET_EVENT_HANDLER;
  373. requestActionASAP([=]()
  374. {
  375. makePossibleUpgrades(visitor);
  376. });
  377. }
  378. void VCAI::playerBonusChanged(const Bonus & bonus, bool gain)
  379. {
  380. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  381. NET_EVENT_HANDLER;
  382. }
  383. void VCAI::heroCreated(const CGHeroInstance * h)
  384. {
  385. LOG_TRACE(logAi);
  386. if(h->visitedTown)
  387. townVisitsThisWeek[HeroPtr(h)].insert(h->visitedTown);
  388. NET_EVENT_HANDLER;
  389. }
  390. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  391. {
  392. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  393. NET_EVENT_HANDLER;
  394. }
  395. void VCAI::showInfoDialog(const std::string & text, const std::vector<Component> & components, int soundID)
  396. {
  397. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  398. NET_EVENT_HANDLER;
  399. }
  400. void VCAI::requestRealized(PackageApplied * pa)
  401. {
  402. LOG_TRACE(logAi);
  403. NET_EVENT_HANDLER;
  404. if(status.haveTurn())
  405. {
  406. if(pa->packType == typeList.getTypeID<EndTurn>())
  407. {
  408. if(pa->result)
  409. status.madeTurn();
  410. }
  411. }
  412. if(pa->packType == typeList.getTypeID<QueryReply>())
  413. {
  414. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  415. }
  416. }
  417. void VCAI::receivedResource()
  418. {
  419. LOG_TRACE(logAi);
  420. NET_EVENT_HANDLER;
  421. }
  422. void VCAI::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor)
  423. {
  424. LOG_TRACE(logAi);
  425. NET_EVENT_HANDLER;
  426. }
  427. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  428. {
  429. LOG_TRACE(logAi);
  430. NET_EVENT_HANDLER;
  431. }
  432. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  433. {
  434. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  435. NET_EVENT_HANDLER;
  436. }
  437. void VCAI::battleResultsApplied()
  438. {
  439. LOG_TRACE(logAi);
  440. NET_EVENT_HANDLER;
  441. assert(status.getBattle() == ENDING_BATTLE);
  442. status.setBattle(NO_BATTLE);
  443. }
  444. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  445. {
  446. LOG_TRACE(logAi);
  447. NET_EVENT_HANDLER;
  448. if(sop->what == ObjProperty::OWNER)
  449. {
  450. if(myCb->getPlayerRelations(playerID, (PlayerColor)sop->val) == PlayerRelations::ENEMIES)
  451. {
  452. //we want to visit objects owned by oppponents
  453. auto obj = myCb->getObj(sop->id, false);
  454. if(obj)
  455. {
  456. addVisitableObj(obj); // TODO: Remove once save compatability broken. In past owned objects were removed from this set
  457. vstd::erase_if_present(alreadyVisited, obj);
  458. }
  459. }
  460. }
  461. }
  462. void VCAI::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  463. {
  464. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  465. if (town->getOwner() == playerID && what == 1) //built
  466. completeGoal(sptr(Goals::BuildThis(buildingID, town)));
  467. NET_EVENT_HANDLER;
  468. }
  469. void VCAI::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  470. {
  471. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  472. NET_EVENT_HANDLER;
  473. }
  474. void VCAI::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor)
  475. {
  476. LOG_TRACE(logAi);
  477. NET_EVENT_HANDLER;
  478. }
  479. void VCAI::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions)
  480. {
  481. //TODO: AI support for ViewXXX spell
  482. LOG_TRACE(logAi);
  483. NET_EVENT_HANDLER;
  484. }
  485. void VCAI::init(std::shared_ptr<CCallback> CB)
  486. {
  487. LOG_TRACE(logAi);
  488. myCb = CB;
  489. cbc = CB;
  490. ah.reset(new AIhelper());
  491. NET_EVENT_HANDLER; //sets ah->rm->cb
  492. playerID = *myCb->getMyColor();
  493. myCb->waitTillRealize = true;
  494. myCb->unlockGsWhenWaiting = true;
  495. if(!fh)
  496. fh = new FuzzyHelper();
  497. retrieveVisitableObjs();
  498. }
  499. void VCAI::yourTurn()
  500. {
  501. LOG_TRACE(logAi);
  502. NET_EVENT_HANDLER;
  503. status.startedTurn();
  504. makingTurn = make_unique<boost::thread>(&VCAI::makeTurn, this);
  505. }
  506. void VCAI::heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  507. {
  508. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  509. NET_EVENT_HANDLER;
  510. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  511. requestActionASAP([=](){ answerQuery(queryID, 0); });
  512. }
  513. void VCAI::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  514. {
  515. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  516. NET_EVENT_HANDLER;
  517. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  518. requestActionASAP([=](){ answerQuery(queryID, 0); });
  519. }
  520. void VCAI::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel)
  521. {
  522. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  523. NET_EVENT_HANDLER;
  524. int sel = 0;
  525. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  526. % components.size() % text));
  527. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  528. sel = components.size();
  529. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  530. sel = 1;
  531. requestActionASAP([=]()
  532. {
  533. answerQuery(askID, sel);
  534. });
  535. }
  536. void VCAI::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  537. {
  538. // LOG_TRACE_PARAMS(logAi, "askID '%i', exits '%s'", askID % exits);
  539. NET_EVENT_HANDLER;
  540. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits")
  541. % exits.size()));
  542. int choosenExit = -1;
  543. if(impassable)
  544. {
  545. knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  546. }
  547. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.valid())
  548. {
  549. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  550. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  551. choosenExit = vstd::find_pos(exits, neededExit);
  552. }
  553. for(auto exit : exits)
  554. {
  555. if(status.channelProbing() && exit.first == destinationTeleport)
  556. {
  557. choosenExit = vstd::find_pos(exits, exit);
  558. break;
  559. }
  560. else
  561. {
  562. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  563. // So far this is the best option to handle decision about probing
  564. auto obj = cb->getObj(exit.first, false);
  565. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  566. {
  567. if(exit.first != destinationTeleport)
  568. teleportChannelProbingList.push_back(exit.first);
  569. }
  570. }
  571. }
  572. requestActionASAP([=]()
  573. {
  574. answerQuery(askID, choosenExit);
  575. });
  576. }
  577. void VCAI::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  578. {
  579. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  580. NET_EVENT_HANDLER;
  581. std::string s1 = up ? up->nodeName() : "NONE";
  582. std::string s2 = down ? down->nodeName() : "NONE";
  583. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  584. //you can't request action from action-response thread
  585. requestActionASAP([=]()
  586. {
  587. if(removableUnits)
  588. pickBestCreatures(down, up);
  589. answerQuery(queryID, 0);
  590. });
  591. }
  592. void VCAI::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  593. {
  594. status.addQuery(askID, "Map object select query");
  595. requestActionASAP([=](){ answerQuery(askID, 0); });
  596. //TODO: Town portal destination selection goes here
  597. }
  598. void VCAI::saveGame(BinarySerializer & h, const int version)
  599. {
  600. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  601. NET_EVENT_HANDLER;
  602. validateVisitableObjs();
  603. #if 0
  604. //disabled due to issue 2890
  605. registerGoals(h);
  606. #endif // 0
  607. CAdventureAI::saveGame(h, version);
  608. serializeInternal(h, version);
  609. }
  610. void VCAI::loadGame(BinaryDeserializer & h, const int version)
  611. {
  612. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  613. NET_EVENT_HANDLER;
  614. #if 0
  615. //disabled due to issue 2890
  616. registerGoals(h);
  617. #endif // 0
  618. CAdventureAI::loadGame(h, version);
  619. serializeInternal(h, version);
  620. }
  621. void makePossibleUpgrades(const CArmedInstance * obj)
  622. {
  623. if(!obj)
  624. return;
  625. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  626. {
  627. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  628. {
  629. UpgradeInfo ui;
  630. cb->getUpgradeInfo(obj, SlotID(i), ui);
  631. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  632. {
  633. cb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  634. }
  635. }
  636. }
  637. }
  638. void VCAI::makeTurn()
  639. {
  640. logGlobal->info("Player %d (%s) starting turn", playerID, playerID.getStr());
  641. MAKING_TURN;
  642. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  643. setThreadName("VCAI::makeTurn");
  644. switch(cb->getDate(Date::DAY_OF_WEEK))
  645. {
  646. case 1:
  647. {
  648. townVisitsThisWeek.clear();
  649. std::vector<const CGObjectInstance *> objs;
  650. retrieveVisitableObjs(objs, true);
  651. for(const CGObjectInstance * obj : objs)
  652. {
  653. if(isWeeklyRevisitable(obj))
  654. {
  655. addVisitableObj(obj);
  656. vstd::erase_if_present(alreadyVisited, obj);
  657. }
  658. }
  659. break;
  660. }
  661. }
  662. markHeroAbleToExplore(primaryHero());
  663. makeTurnInternal();
  664. }
  665. /*This method defines core of AI behavior. It is not consistent system, just "a bit of everything for everyone" done in some example order.
  666. It is not supposed to work this way in final version of VCAI. It consists of few actions/loops done in particular order, hard parts are explained below with focus on explaining hero management logic*/
  667. void VCAI::makeTurnInternal()
  668. {
  669. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  670. for(const CGTownInstance * t : cb->getTownsInfo())
  671. moveCreaturesToHero(t);
  672. try
  673. {
  674. /*Below loop causes heroes with objects locked to them to keep trying to realize previous goal. By design when object is locked another heroes do not attempt to visit it.
  675. Object lock happens on turn when some hero gets assigned visit tile with appropiate map object. So basically all heroes that had VisitTile goal with object assigned and not completed
  676. will be in the loop. Sometimes heroes get assigned more important objectives, but still keep reserved objects for later. There is a problem with that - they have
  677. reserved objects in the list, so they fall to this loop at start of turn and visiting object isn't delayed. Comments for that function are supposed to help newer VCAI maintainers*/
  678. //Pick objects reserved in previous turn - we expect only nearby objects there
  679. auto reservedHeroesCopy = reservedHeroesMap; //work on copy => the map may be changed while iterating (eg because hero died when attempting a goal)
  680. for(auto hero : reservedHeroesCopy)
  681. {
  682. if(reservedHeroesMap.count(hero.first))
  683. continue; //hero might have been removed while we were in this loop
  684. if(!hero.first.validAndSet())
  685. {
  686. logAi->error("Hero %s present on reserved map. Shouldn't be.", hero.first.name);
  687. continue;
  688. }
  689. std::vector<const CGObjectInstance *> vec(hero.second.begin(), hero.second.end());
  690. boost::sort(vec, CDistanceSorter(hero.first.get()));
  691. for(auto obj : vec)
  692. {
  693. if(!obj || !cb->getObj(obj->id))
  694. {
  695. logAi->error("Error: there is wrong object on list for hero %s", hero.first->name);
  696. continue;
  697. }
  698. striveToGoal(sptr(Goals::VisitTile(obj->visitablePos()).sethero(hero.first)));
  699. }
  700. }
  701. //now try to win
  702. /*below line performs goal decomposition, result of the function is ONE goal for ONE hero to realize.*/
  703. striveToGoal(sptr(Goals::Win()));
  704. //TODO: add ResourceManager goals to the pool and process them all at once
  705. if (ah->hasTasksLeft())
  706. striveToGoal(ah->whatToDo());
  707. /*Explanation of below loop: At the time of writing this - goals get decomposited either to GatherArmy or Visit Tile.
  708. Visit tile that is about visiting object gets processed at beginning of MakeTurnInternal without re-evaluation.
  709. Rest of goals that got started via striveToGoal(sptr(Goals::Win())); in previous turns and not finished get continued here.
  710. Also they are subject for re-evaluation to see if there is better goal to start (still talking only about heroes that got goals started by via striveToGoal(sptr(Goals::Win())); in previous turns.*/
  711. //finally, continue our abstract long-term goals
  712. int oldMovement = 0;
  713. int newMovement = 0;
  714. while(true)
  715. {
  716. oldMovement = newMovement; //remember old value
  717. newMovement = 0;
  718. std::vector<std::pair<HeroPtr, Goals::TSubgoal>> safeCopy;
  719. for(auto mission : lockedHeroes)
  720. {
  721. fh->setPriority(mission.second); //re-evaluate
  722. if(canAct(mission.first))
  723. {
  724. newMovement += mission.first->movement;
  725. safeCopy.push_back(mission);
  726. }
  727. }
  728. if(newMovement == oldMovement) //means our heroes didn't move or didn't re-assign their goals
  729. {
  730. logAi->warn("Our heroes don't move anymore, exhaustive decomposition failed");
  731. break;
  732. }
  733. if(safeCopy.empty())
  734. {
  735. break; //all heroes exhausted their locked goals
  736. }
  737. else
  738. {
  739. typedef std::pair<HeroPtr, Goals::TSubgoal> TItrType;
  740. auto lockedHeroesSorter = [](TItrType m1, TItrType m2) -> bool
  741. {
  742. return m1.second->priority < m2.second->priority;
  743. };
  744. striveToGoal(boost::max_element(safeCopy, lockedHeroesSorter)->second);
  745. }
  746. }
  747. auto quests = myCb->getMyQuests();
  748. for(auto quest : quests)
  749. {
  750. striveToQuest(quest);
  751. }
  752. //TODO: striveToGoal
  753. striveToGoal(sptr(Goals::Build())); //TODO: smarter building management
  754. /*Below function is also responsible for hero movement via internal wander function. By design it is separate logic for heroes that have nothing to do.
  755. Heroes that were not picked by striveToGoal(sptr(Goals::Win())); recently (so they do not have new goals and cannot continue/reevaluate previously locked goals) will do logic in wander().*/
  756. performTypicalActions();
  757. //for debug purpose
  758. for(auto h : cb->getHeroesInfo())
  759. {
  760. if(h->movement)
  761. logAi->warn("Hero %s has %d MP left", h->name, h->movement);
  762. }
  763. }
  764. catch(boost::thread_interrupted & e)
  765. {
  766. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  767. return;
  768. }
  769. catch(std::exception & e)
  770. {
  771. logAi->debug("Making turn thread has caught an exception: %s", e.what());
  772. }
  773. endTurn();
  774. }
  775. bool VCAI::goVisitObj(const CGObjectInstance * obj, HeroPtr h)
  776. {
  777. int3 dst = obj->visitablePos();
  778. auto sm = getCachedSectorMap(h);
  779. logAi->debug("%s will try to visit %s at (%s)", h->name, obj->getObjectName(), dst.toString());
  780. int3 pos = sm->firstTileToGet(h, dst);
  781. if(!pos.valid()) //rare case when we are already standing on one of potential objects
  782. return false;
  783. return moveHeroToTile(pos, h);
  784. }
  785. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  786. {
  787. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->name % obj->getObjectName() % obj->pos.toString());
  788. switch(obj->ID)
  789. {
  790. case Obj::CREATURE_GENERATOR1:
  791. recruitCreatures(dynamic_cast<const CGDwelling *>(obj), h.get());
  792. checkHeroArmy(h);
  793. break;
  794. case Obj::TOWN:
  795. moveCreaturesToHero(dynamic_cast<const CGTownInstance *>(obj));
  796. if(h->visitedTown) //we are inside, not just attacking
  797. {
  798. townVisitsThisWeek[h].insert(h->visitedTown);
  799. if(!h->hasSpellbook() && ah->freeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  800. {
  801. if(h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  802. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  803. }
  804. }
  805. break;
  806. }
  807. completeGoal(sptr(Goals::GetObj(obj->id.getNum()).sethero(h)));
  808. }
  809. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  810. {
  811. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  812. {
  813. pickBestCreatures(t->visitingHero, t);
  814. }
  815. }
  816. bool VCAI::canGetArmy(const CGHeroInstance * army, const CGHeroInstance * source)
  817. {
  818. //TODO: merge with pickBestCreatures
  819. //if (ai->primaryHero().h == source)
  820. if(army->tempOwner != source->tempOwner)
  821. {
  822. logAi->error("Why are we even considering exchange between heroes from different players?");
  823. return false;
  824. }
  825. const CArmedInstance * armies[] = {army, source};
  826. //we calculate total strength for each creature type available in armies
  827. std::map<const CCreature *, int> creToPower;
  828. for(auto armyPtr : armies)
  829. {
  830. for(auto & i : armyPtr->Slots())
  831. {
  832. //TODO: allow splitting stacks?
  833. creToPower[i.second->type] += i.second->getPower();
  834. }
  835. }
  836. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  837. int armySize = creToPower.size();
  838. armySize = std::min((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  839. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  840. for(int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  841. {
  842. typedef const std::pair<const CCreature *, int> & CrePowerPair;
  843. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  844. {
  845. return lhs.second < rhs.second;
  846. });
  847. bestArmy.push_back(creIt->first);
  848. creToPower.erase(creIt);
  849. if(creToPower.empty())
  850. break;
  851. }
  852. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  853. for(int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  854. {
  855. for(auto armyPtr : armies)
  856. {
  857. for(int j = 0; j < GameConstants::ARMY_SIZE; j++)
  858. {
  859. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && armyPtr != army) //it's a searched creature not in dst ARMY
  860. {
  861. //FIXME: line below is useless when simulating exchange between two non-singular armies
  862. if(!(armyPtr->needsLastStack() && armyPtr->stacksCount() == 1)) //can't take away last creature
  863. return true; //at least one exchange will be performed
  864. else
  865. return false; //no further exchange possible
  866. }
  867. }
  868. }
  869. }
  870. return false;
  871. }
  872. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  873. {
  874. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  875. const CArmedInstance * armies[] = {army, source};
  876. //we calculate total strength for each creature type available in armies
  877. std::map<const CCreature *, int> creToPower;
  878. for(auto armyPtr : armies)
  879. {
  880. for(auto & i : armyPtr->Slots())
  881. {
  882. //TODO: allow splitting stacks?
  883. creToPower[i.second->type] += i.second->getPower();
  884. }
  885. }
  886. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  887. int armySize = creToPower.size();
  888. armySize = std::min((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  889. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  890. for(int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  891. {
  892. typedef const std::pair<const CCreature *, int> & CrePowerPair;
  893. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  894. {
  895. return lhs.second < rhs.second;
  896. });
  897. bestArmy.push_back(creIt->first);
  898. creToPower.erase(creIt);
  899. if(creToPower.empty())
  900. break;
  901. }
  902. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  903. for(int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  904. {
  905. for(auto armyPtr : armies)
  906. {
  907. for(int j = 0; j < GameConstants::ARMY_SIZE; j++)
  908. {
  909. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst SLOT
  910. {
  911. if(!(armyPtr->needsLastStack() && armyPtr->stacksCount() == 1)) //can't take away last creature
  912. cb->mergeOrSwapStacks(armyPtr, army, SlotID(j), SlotID(i));
  913. }
  914. }
  915. }
  916. }
  917. //TODO - having now strongest possible army, we may want to think about arranging stacks
  918. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  919. if(hero)
  920. checkHeroArmy(hero);
  921. }
  922. void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  923. {
  924. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  925. {
  926. bool changeMade = false;
  927. do
  928. {
  929. changeMade = false;
  930. //we collect gear always in same order
  931. std::vector<ArtifactLocation> allArtifacts;
  932. if(giveStuffToFirstHero)
  933. {
  934. for(auto p : h->artifactsWorn)
  935. {
  936. if(p.second.artifact)
  937. allArtifacts.push_back(ArtifactLocation(h, p.first));
  938. }
  939. }
  940. for(auto slot : h->artifactsInBackpack)
  941. allArtifacts.push_back(ArtifactLocation(h, h->getArtPos(slot.artifact)));
  942. if(otherh)
  943. {
  944. for(auto p : otherh->artifactsWorn)
  945. {
  946. if(p.second.artifact)
  947. allArtifacts.push_back(ArtifactLocation(otherh, p.first));
  948. }
  949. for(auto slot : otherh->artifactsInBackpack)
  950. allArtifacts.push_back(ArtifactLocation(otherh, otherh->getArtPos(slot.artifact)));
  951. }
  952. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  953. const CGHeroInstance * target = nullptr;
  954. if(giveStuffToFirstHero || !otherh)
  955. target = h;
  956. else
  957. target = otherh;
  958. for(auto location : allArtifacts)
  959. {
  960. if(location.relatedObj() == target && location.slot < ArtifactPosition::AFTER_LAST)
  961. continue; //don't reequip artifact we already wear
  962. if(location.slot == ArtifactPosition::MACH4) // don't attempt to move catapult
  963. continue;
  964. auto s = location.getSlot();
  965. if(!s || s->locked) //we can't move locks
  966. continue;
  967. auto artifact = s->artifact;
  968. if(!artifact)
  969. continue;
  970. //FIXME: why are the above possible to be null?
  971. bool emptySlotFound = false;
  972. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  973. {
  974. ArtifactLocation destLocation(target, slot);
  975. if(target->isPositionFree(slot) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  976. {
  977. cb->swapArtifacts(location, destLocation); //just put into empty slot
  978. emptySlotFound = true;
  979. changeMade = true;
  980. break;
  981. }
  982. }
  983. if(!emptySlotFound) //try to put that atifact in already occupied slot
  984. {
  985. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  986. {
  987. auto otherSlot = target->getSlot(slot);
  988. if(otherSlot && otherSlot->artifact) //we need to exchange artifact for better one
  989. {
  990. ArtifactLocation destLocation(target, slot);
  991. //if that artifact is better than what we have, pick it
  992. if(compareArtifacts(artifact, otherSlot->artifact) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  993. {
  994. cb->swapArtifacts(location, ArtifactLocation(target, target->getArtPos(otherSlot->artifact)));
  995. changeMade = true;
  996. break;
  997. }
  998. }
  999. }
  1000. }
  1001. if(changeMade)
  1002. break; //start evaluating artifacts from scratch
  1003. }
  1004. }
  1005. while(changeMade);
  1006. };
  1007. equipBest(h, other, true);
  1008. if(other)
  1009. equipBest(h, other, false);
  1010. }
  1011. void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  1012. {
  1013. //now used only for visited dwellings / towns, not BuyArmy goal
  1014. for(int i = 0; i < d->creatures.size(); i++)
  1015. {
  1016. if(!d->creatures[i].second.size())
  1017. continue;
  1018. int count = d->creatures[i].first;
  1019. CreatureID creID = d->creatures[i].second.back();
  1020. vstd::amin(count, ah->freeResources() / VLC->creh->creatures[creID]->cost);
  1021. if(count > 0)
  1022. cb->recruitCreatures(d, recruiter, creID, count, i);
  1023. }
  1024. }
  1025. bool VCAI::tryBuildThisStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays)
  1026. {
  1027. if(maxDays == 0)
  1028. {
  1029. logAi->warn("Request to build building %d in 0 days!", building.toEnum());
  1030. return false;
  1031. }
  1032. if(!vstd::contains(t->town->buildings, building))
  1033. return false; // no such building in town
  1034. if(t->hasBuilt(building)) //Already built? Shouldn't happen in general
  1035. return true;
  1036. const CBuilding * buildPtr = t->town->buildings.at(building);
  1037. auto toBuild = buildPtr->requirements.getFulfillmentCandidates([&](const BuildingID & buildID)
  1038. {
  1039. return t->hasBuilt(buildID);
  1040. });
  1041. toBuild.push_back(building);
  1042. for(BuildingID buildID : toBuild)
  1043. {
  1044. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  1045. if(canBuild == EBuildingState::HAVE_CAPITAL || canBuild == EBuildingState::FORBIDDEN || canBuild == EBuildingState::NO_WATER)
  1046. return false; //we won't be able to build this
  1047. }
  1048. if(maxDays && toBuild.size() > maxDays)
  1049. return false;
  1050. //TODO: calculate if we have enough resources to build it in maxDays?
  1051. for(const auto & buildID : toBuild)
  1052. {
  1053. const CBuilding * b = t->town->buildings.at(buildID);
  1054. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  1055. if (canBuild == EBuildingState::ALLOWED)
  1056. {
  1057. buildStructure(t, buildID);
  1058. return true;
  1059. }
  1060. else if (canBuild == EBuildingState::PREREQUIRES)
  1061. {
  1062. // can happen when dependencies have their own missing dependencies
  1063. if (tryBuildThisStructure(t, buildID, maxDays - 1))
  1064. return true;
  1065. }
  1066. else if (canBuild == EBuildingState::MISSING_BASE)
  1067. {
  1068. if (tryBuildThisStructure(t, b->upgrade, maxDays - 1))
  1069. return true;
  1070. }
  1071. else if (canBuild == EBuildingState::NO_RESOURCES)
  1072. {
  1073. //we may need to gather resources for those
  1074. PotentialBuilding pb;
  1075. pb.bid = buildID;
  1076. pb.price = t->getBuildingCost(buildID);
  1077. potentialBuildings.push_back(pb); //these are checked again in try
  1078. return false;
  1079. }
  1080. else
  1081. return false;
  1082. }
  1083. return false;
  1084. }
  1085. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  1086. {
  1087. for(const auto & building : buildList)
  1088. {
  1089. if(t->hasBuilt(building))
  1090. continue;
  1091. return tryBuildThisStructure(t, building, maxDays);
  1092. }
  1093. return false; //Can't build anything
  1094. }
  1095. BuildingID VCAI::canBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays) const
  1096. {
  1097. for(const auto & building : buildList)
  1098. {
  1099. if(t->hasBuilt(building))
  1100. continue;
  1101. if(cb->canBuildStructure(t, building))
  1102. return building;
  1103. }
  1104. return BuildingID::NONE; //Can't build anything
  1105. }
  1106. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  1107. {
  1108. for(const auto & building : buildList)
  1109. {
  1110. if(t->hasBuilt(building))
  1111. continue;
  1112. return tryBuildThisStructure(t, building, maxDays);
  1113. }
  1114. return false; //Nothing to build
  1115. }
  1116. void VCAI::buildStructure(const CGTownInstance * t, BuildingID building)
  1117. {
  1118. auto name = t->town->buildings.at(building)->Name();
  1119. logAi->debug("Player %d will build %s in town of %s at %s", playerID, name, t->name, t->pos.toString());
  1120. cb->buildBuilding(t, building); //just do this;
  1121. }
  1122. //Set of buildings for different goals. Does not include any prerequisites.
  1123. static const BuildingID essential[] = {BuildingID::TAVERN, BuildingID::TOWN_HALL};
  1124. static const BuildingID goldSource[] = {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL};
  1125. static const BuildingID capitolRequirements[] = { BuildingID::FORT, BuildingID::CITADEL };
  1126. static const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  1127. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  1128. static const BuildingID unitsUpgrade[] = { BuildingID::DWELL_LVL_1_UP, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP,
  1129. BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP};
  1130. static const BuildingID unitGrowth[] = { BuildingID::FORT, BuildingID::CITADEL, BuildingID::CASTLE, BuildingID::HORDE_1,
  1131. BuildingID::HORDE_1_UPGR, BuildingID::HORDE_2, BuildingID::HORDE_2_UPGR};
  1132. static const BuildingID _spells[] = {BuildingID::MAGES_GUILD_1, BuildingID::MAGES_GUILD_2, BuildingID::MAGES_GUILD_3,
  1133. BuildingID::MAGES_GUILD_4, BuildingID::MAGES_GUILD_5};
  1134. static const BuildingID extra[] = {BuildingID::RESOURCE_SILO, BuildingID::SPECIAL_1, BuildingID::SPECIAL_2, BuildingID::SPECIAL_3,
  1135. BuildingID::SPECIAL_4, BuildingID::SHIPYARD}; // all remaining buildings
  1136. bool VCAI::tryBuildStructure(const CGTownInstance * t)
  1137. {
  1138. //TODO make *real* town development system
  1139. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  1140. //TODO: build resource silo, defences when needed
  1141. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  1142. //below algorithm focuses on economy growth at start of the game.
  1143. TResources currentRes = cb->getResourceAmount();
  1144. TResources currentIncome = t->dailyIncome();
  1145. if(tryBuildAnyStructure(t, std::vector<BuildingID>(essential, essential + ARRAY_COUNT(essential))))
  1146. return true;
  1147. //the more gold the better and less problems later
  1148. if(tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1149. return true;
  1150. //workaround for mantis #2696 - build fort and citadel - building castle will be handled without bug
  1151. if(vstd::contains(t->builtBuildings, BuildingID::CITY_HALL) &&
  1152. cb->canBuildStructure(t, BuildingID::CAPITOL) != EBuildingState::HAVE_CAPITAL)
  1153. {
  1154. if(cb->canBuildStructure(t, BuildingID::CAPITOL) != EBuildingState::FORBIDDEN)
  1155. {
  1156. if(tryBuildNextStructure(t, std::vector<BuildingID>(capitolRequirements,
  1157. capitolRequirements + ARRAY_COUNT(capitolRequirements))))
  1158. return true;
  1159. }
  1160. }
  1161. //TODO: save money for capitol or city hall if capitol unavailable
  1162. //do not build other things (unless gold source buildings are disabled in map editor)
  1163. if(cb->getDate(Date::DAY_OF_WEEK) > 6) // last 2 days of week - try to focus on growth
  1164. {
  1165. if(tryBuildNextStructure(t, std::vector<BuildingID>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  1166. return true;
  1167. }
  1168. // first in-game week or second half of any week: try build dwellings
  1169. if(cb->getDate(Date::DAY) < 7 || cb->getDate(Date::DAY_OF_WEEK) > 3)
  1170. {
  1171. if(tryBuildAnyStructure(t, std::vector<BuildingID>(unitsSource,
  1172. unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK)))
  1173. return true;
  1174. }
  1175. //try to upgrade dwelling
  1176. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  1177. {
  1178. if(t->hasBuilt(unitsSource[i]) && !t->hasBuilt(unitsUpgrade[i]))
  1179. {
  1180. if(tryBuildThisStructure(t, unitsUpgrade[i]))
  1181. return true;
  1182. }
  1183. }
  1184. //remaining tasks
  1185. if(tryBuildNextStructure(t, std::vector<BuildingID>(_spells, _spells + ARRAY_COUNT(_spells))))
  1186. return true;
  1187. if(tryBuildAnyStructure(t, std::vector<BuildingID>(extra, extra + ARRAY_COUNT(extra))))
  1188. return true;
  1189. //at the end, try to get and build any extra buildings with nonstandard slots (for example HotA 3rd level dwelling)
  1190. std::vector<BuildingID> extraBuildings;
  1191. for(auto buildingInfo : t->town->buildings)
  1192. {
  1193. if(buildingInfo.first > 43)
  1194. extraBuildings.push_back(buildingInfo.first);
  1195. }
  1196. if(tryBuildAnyStructure(t, extraBuildings))
  1197. return true;
  1198. return false;
  1199. }
  1200. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, SectorMap & sm)
  1201. {
  1202. const int3 pos = obj->visitablePos();
  1203. const int3 targetPos = sm.firstTileToGet(h, pos);
  1204. if(!targetPos.valid())
  1205. return false;
  1206. if(!isTileNotReserved(h.get(), targetPos))
  1207. return false;
  1208. if(obj->wasVisited(playerID))
  1209. return false;
  1210. if(cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
  1211. return false; // Otherwise we flag or get weekly resources / creatures
  1212. if(!isSafeToVisit(h, pos))
  1213. return false;
  1214. if(!shouldVisit(h, obj))
  1215. return false;
  1216. if(vstd::contains(alreadyVisited, obj))
  1217. return false;
  1218. if(vstd::contains(reservedObjs, obj))
  1219. return false;
  1220. if(!isAccessibleForHero(targetPos, h))
  1221. return false;
  1222. const CGObjectInstance * topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
  1223. //we don't try visiting object on which allied or owned hero stands
  1224. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1225. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  1226. return false;
  1227. else
  1228. return true; //all of the following is met
  1229. }
  1230. bool VCAI::isTileNotReserved(const CGHeroInstance * h, int3 t)
  1231. {
  1232. if(t.valid())
  1233. {
  1234. auto obj = cb->getTopObj(t);
  1235. if(obj && vstd::contains(ai->reservedObjs, obj) && !vstd::contains(reservedHeroesMap[h], obj))
  1236. return false; //do not capture object reserved by another hero
  1237. else
  1238. return true;
  1239. }
  1240. else
  1241. {
  1242. return false;
  1243. }
  1244. }
  1245. bool VCAI::canRecruitAnyHero(const CGTownInstance * t) const
  1246. {
  1247. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  1248. if(!t)
  1249. t = findTownWithTavern();
  1250. if(!t)
  1251. return false;
  1252. if(cb->getResourceAmount(Res::GOLD) < GameConstants::HERO_GOLD_COST) //TODO: use ResourceManager
  1253. return false;
  1254. if(cb->getHeroesInfo().size() >= ALLOWED_ROAMING_HEROES)
  1255. return false;
  1256. if(!cb->getAvailableHeroes(t).size())
  1257. return false;
  1258. return true;
  1259. }
  1260. void VCAI::wander(HeroPtr h)
  1261. {
  1262. //unclaim objects that are now dangerous for us
  1263. auto reservedObjsSetCopy = reservedHeroesMap[h];
  1264. for(auto obj : reservedObjsSetCopy)
  1265. {
  1266. if(!isSafeToVisit(h, obj->visitablePos()))
  1267. unreserveObject(h, obj);
  1268. }
  1269. TimeCheck tc("looking for wander destination");
  1270. while(h->movement)
  1271. {
  1272. validateVisitableObjs();
  1273. std::vector<ObjectIdRef> dests;
  1274. auto sm = getCachedSectorMap(h);
  1275. //also visit our reserved objects - but they are not prioritized to avoid running back and forth
  1276. vstd::copy_if(reservedHeroesMap[h], std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1277. {
  1278. int3 pos = sm->firstTileToGet(h, obj->visitablePos());
  1279. if(pos.valid() && isAccessibleForHero(pos, h)) //even nearby objects could be blocked by other heroes :(
  1280. return true;
  1281. return false;
  1282. });
  1283. int pass = 0;
  1284. while(!dests.size() && pass < 3)
  1285. {
  1286. if(pass < 2) // optimization - first check objects in current sector; then in sectors around
  1287. {
  1288. auto objs = sm->getNearbyObjs(h, pass);
  1289. vstd::copy_if(objs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1290. {
  1291. return isGoodForVisit(obj, h, *sm);
  1292. });
  1293. }
  1294. else // we only check full objects list if for some reason there are no objects in closest sectors
  1295. {
  1296. vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1297. {
  1298. return isGoodForVisit(obj, h, *sm);
  1299. });
  1300. }
  1301. pass++;
  1302. }
  1303. vstd::erase_if(dests, [&](ObjectIdRef obj) -> bool
  1304. {
  1305. return !isSafeToVisit(h, sm->firstTileToGet(h, obj->visitablePos()));
  1306. });
  1307. if(!dests.size())
  1308. {
  1309. if(cb->getVisitableObjs(h->visitablePos()).size() > 1)
  1310. moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
  1311. auto compareReinforcements = [h](const CGTownInstance * lhs, const CGTownInstance * rhs) -> bool
  1312. {
  1313. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1314. };
  1315. std::vector<const CGTownInstance *> townsReachable;
  1316. std::vector<const CGTownInstance *> townsNotReachable;
  1317. for(const CGTownInstance * t : cb->getTownsInfo())
  1318. {
  1319. if(!t->visitingHero && howManyReinforcementsCanGet(h, t) && !vstd::contains(townVisitsThisWeek[h], t))
  1320. {
  1321. if(isAccessibleForHero(t->visitablePos(), h))
  1322. townsReachable.push_back(t);
  1323. else
  1324. townsNotReachable.push_back(t);
  1325. }
  1326. }
  1327. if(townsReachable.size())
  1328. {
  1329. boost::sort(townsReachable, compareReinforcements);
  1330. dests.push_back(townsReachable.back());
  1331. }
  1332. else if(townsNotReachable.size())
  1333. {
  1334. //TODO pick the truly best
  1335. const CGTownInstance * t = *boost::max_element(townsNotReachable, compareReinforcements);
  1336. logAi->debug("%s can't reach any town, we'll try to make our way to %s at %s", h->name, t->name, t->visitablePos().toString());
  1337. int3 pos1 = h->pos;
  1338. striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h)));
  1339. //if out hero is stuck, we may need to request another hero to clear the way we see
  1340. if(pos1 == h->pos && h == primaryHero()) //hero can't move
  1341. {
  1342. if(canRecruitAnyHero(t))
  1343. recruitHero(t);
  1344. }
  1345. break;
  1346. }
  1347. else if(cb->getResourceAmount(Res::GOLD) >= GameConstants::HERO_GOLD_COST)
  1348. {
  1349. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1350. vstd::erase_if(towns, [](const CGTownInstance * t) -> bool
  1351. {
  1352. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1353. {
  1354. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1355. return true;
  1356. }
  1357. return false;
  1358. });
  1359. if (towns.size())
  1360. {
  1361. recruitHero(*boost::max_element(towns, compareArmyStrength));
  1362. }
  1363. break;
  1364. }
  1365. else
  1366. {
  1367. logAi->debug("Nowhere more to go...");
  1368. break;
  1369. }
  1370. }
  1371. //end of objs empty
  1372. if(dests.size()) //performance improvement
  1373. {
  1374. const ObjectIdRef & dest = *boost::min_element(dests, CDistanceSorter(h.get())); //find next closest one
  1375. //wander should not cause heroes to be reserved - they are always considered free
  1376. logAi->debug("Of all %d destinations, object oid=%d seems nice", dests.size(), dest.id.getNum());
  1377. if(!goVisitObj(dest, h))
  1378. {
  1379. if(!dest)
  1380. {
  1381. logAi->debug("Visit attempt made the object (id=%d) gone...", dest.id.getNum());
  1382. }
  1383. else
  1384. {
  1385. logAi->debug("Hero %s apparently used all MPs (%d left)", h->name, h->movement);
  1386. return;
  1387. }
  1388. }
  1389. }
  1390. if(h->visitedTown)
  1391. {
  1392. townVisitsThisWeek[h].insert(h->visitedTown);
  1393. buildArmyIn(h->visitedTown);
  1394. }
  1395. }
  1396. }
  1397. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1398. {
  1399. if(goal->invalid())
  1400. {
  1401. vstd::erase_if_present(lockedHeroes, h);
  1402. }
  1403. else
  1404. {
  1405. lockedHeroes[h] = goal;
  1406. goal->setisElementar(false); //Force always evaluate goals before realizing
  1407. }
  1408. }
  1409. void VCAI::evaluateGoal(HeroPtr h)
  1410. {
  1411. if(vstd::contains(lockedHeroes, h))
  1412. fh->setPriority(lockedHeroes[h]);
  1413. }
  1414. void VCAI::completeGoal(Goals::TSubgoal goal)
  1415. {
  1416. logAi->trace("Completing goal: %s", goal->name());
  1417. ah->notifyGoalCompleted(goal);
  1418. if(const CGHeroInstance * h = goal->hero.get(true))
  1419. {
  1420. auto it = lockedHeroes.find(h);
  1421. if(it != lockedHeroes.end())
  1422. {
  1423. if(it->second == goal || it->second->fulfillsMe(goal)) //FIXME this is overspecified, fulfillsMe shoudl be complete
  1424. {
  1425. logAi->debug(goal->completeMessage());
  1426. lockedHeroes.erase(it); //goal fulfilled, free hero
  1427. }
  1428. }
  1429. }
  1430. else //complete goal for all heroes maybe?
  1431. {
  1432. vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
  1433. {
  1434. if(p.second == goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1435. {
  1436. logAi->debug(p.second->completeMessage());
  1437. return true;
  1438. }
  1439. return false;
  1440. });
  1441. }
  1442. }
  1443. void VCAI::battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side)
  1444. {
  1445. NET_EVENT_HANDLER;
  1446. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1447. status.setBattle(ONGOING_BATTLE);
  1448. const CGObjectInstance * presumedEnemy = vstd::backOrNull(cb->getVisitableObjs(tile)); //may be nullptr in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
  1449. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile.toString());
  1450. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1451. }
  1452. void VCAI::battleEnd(const BattleResult * br)
  1453. {
  1454. NET_EVENT_HANDLER;
  1455. assert(status.getBattle() == ONGOING_BATTLE);
  1456. status.setBattle(ENDING_BATTLE);
  1457. bool won = br->winner == myCb->battleGetMySide();
  1458. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.getStr(), (won ? "won" : "lost"), battlename);
  1459. battlename.clear();
  1460. CAdventureAI::battleEnd(br);
  1461. }
  1462. void VCAI::waitTillFree()
  1463. {
  1464. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  1465. status.waitTillFree();
  1466. }
  1467. void VCAI::markObjectVisited(const CGObjectInstance * obj)
  1468. {
  1469. if(!obj)
  1470. return;
  1471. if(dynamic_cast<const CGVisitableOPH *>(obj)) //we may want to visit it with another hero
  1472. return;
  1473. if(dynamic_cast<const CGBonusingObject *>(obj)) //or another time
  1474. return;
  1475. if(obj->ID == Obj::MONSTER)
  1476. return;
  1477. alreadyVisited.insert(obj);
  1478. }
  1479. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance * obj)
  1480. {
  1481. reservedObjs.insert(obj);
  1482. reservedHeroesMap[h].insert(obj);
  1483. logAi->debug("reserved object id=%d; address=%p; name=%s", obj->id, obj, obj->getObjectName());
  1484. }
  1485. void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance * obj)
  1486. {
  1487. vstd::erase_if_present(reservedObjs, obj); //unreserve objects
  1488. vstd::erase_if_present(reservedHeroesMap[h], obj);
  1489. }
  1490. void VCAI::markHeroUnableToExplore(HeroPtr h)
  1491. {
  1492. heroesUnableToExplore.insert(h);
  1493. }
  1494. void VCAI::markHeroAbleToExplore(HeroPtr h)
  1495. {
  1496. vstd::erase_if_present(heroesUnableToExplore, h);
  1497. }
  1498. bool VCAI::isAbleToExplore(HeroPtr h)
  1499. {
  1500. return !vstd::contains(heroesUnableToExplore, h);
  1501. }
  1502. void VCAI::clearPathsInfo()
  1503. {
  1504. heroesUnableToExplore.clear();
  1505. cachedSectorMaps.clear();
  1506. }
  1507. void VCAI::validateVisitableObjs()
  1508. {
  1509. std::string errorMsg;
  1510. auto shouldBeErased = [&](const CGObjectInstance * obj) -> bool
  1511. {
  1512. if(obj)
  1513. return !cb->getObj(obj->id, false); // no verbose output needed as we check object visibility
  1514. else
  1515. return true;
  1516. };
  1517. //errorMsg is captured by ref so lambda will take the new text
  1518. errorMsg = " shouldn't be on the visitable objects list!";
  1519. vstd::erase_if(visitableObjs, shouldBeErased);
  1520. //FIXME: how comes our own heroes become inaccessible?
  1521. vstd::erase_if(reservedHeroesMap, [](std::pair<HeroPtr, std::set<const CGObjectInstance *>> hp) -> bool
  1522. {
  1523. return !hp.first.get(true);
  1524. });
  1525. for(auto & p : reservedHeroesMap)
  1526. {
  1527. errorMsg = " shouldn't be on list for hero " + p.first->name + "!";
  1528. vstd::erase_if(p.second, shouldBeErased);
  1529. }
  1530. errorMsg = " shouldn't be on the reserved objs list!";
  1531. vstd::erase_if(reservedObjs, shouldBeErased);
  1532. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1533. errorMsg = " shouldn't be on the already visited objs list!";
  1534. vstd::erase_if(alreadyVisited, shouldBeErased);
  1535. }
  1536. void VCAI::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
  1537. {
  1538. foreach_tile_pos([&](const int3 & pos)
  1539. {
  1540. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1541. {
  1542. if(includeOwned || obj->tempOwner != playerID)
  1543. out.push_back(obj);
  1544. }
  1545. });
  1546. }
  1547. void VCAI::retrieveVisitableObjs()
  1548. {
  1549. foreach_tile_pos([&](const int3 & pos)
  1550. {
  1551. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1552. {
  1553. if(obj->tempOwner != playerID)
  1554. addVisitableObj(obj);
  1555. }
  1556. });
  1557. }
  1558. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1559. {
  1560. std::vector<const CGObjectInstance *> ret;
  1561. for(const CGObjectInstance * obj : visitableObjs)
  1562. {
  1563. if(obj->tempOwner == playerID)
  1564. ret.push_back(obj);
  1565. }
  1566. return ret;
  1567. }
  1568. void VCAI::addVisitableObj(const CGObjectInstance * obj)
  1569. {
  1570. visitableObjs.insert(obj);
  1571. helperObjInfo[obj] = ObjInfo(obj);
  1572. // All teleport objects seen automatically assigned to appropriate channels
  1573. auto teleportObj = dynamic_cast<const CGTeleport *>(obj);
  1574. if(teleportObj)
  1575. CGTeleport::addToChannel(knownTeleportChannels, teleportObj);
  1576. }
  1577. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1578. {
  1579. for(const CGObjectInstance * obj : ai->visitableObjs)
  1580. {
  1581. if(obj->ID == Obj::ARTIFACT && obj->subID == aid)
  1582. return obj;
  1583. }
  1584. return nullptr;
  1585. //TODO what if more than one artifact is available? return them all or some slection criteria
  1586. }
  1587. bool VCAI::isAccessible(const int3 & pos)
  1588. {
  1589. //TODO precalculate for speed
  1590. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1591. {
  1592. if(isAccessibleForHero(pos, h))
  1593. return true;
  1594. }
  1595. return false;
  1596. }
  1597. HeroPtr VCAI::getHeroWithGrail() const
  1598. {
  1599. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1600. {
  1601. if(h->hasArt(2)) //grail
  1602. return h;
  1603. }
  1604. return nullptr;
  1605. }
  1606. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate)
  1607. {
  1608. //TODO smarter definition of unvisited
  1609. for(const CGObjectInstance * obj : visitableObjs)
  1610. {
  1611. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1612. return obj;
  1613. }
  1614. return nullptr;
  1615. }
  1616. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies) const
  1617. {
  1618. // Don't visit tile occupied by allied hero
  1619. if(!includeAllies)
  1620. {
  1621. for(auto obj : cb->getVisitableObjs(pos))
  1622. {
  1623. if(obj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES)
  1624. {
  1625. if(obj != h.get())
  1626. return false;
  1627. }
  1628. }
  1629. }
  1630. return cb->getPathsInfo(h.get())->getPathInfo(pos)->reachable();
  1631. }
  1632. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1633. {
  1634. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  1635. auto afterMovementCheck = [&]() -> void
  1636. {
  1637. waitTillFree(); //movement may cause battle or blocking dialog
  1638. if(!h)
  1639. {
  1640. lostHero(h);
  1641. teleportChannelProbingList.clear();
  1642. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  1643. status.setChannelProbing(false);
  1644. throw cannotFulfillGoalException("Hero was lost!");
  1645. }
  1646. };
  1647. logAi->debug("Moving hero %s to tile %s", h->name, dst.toString());
  1648. int3 startHpos = h->visitablePos();
  1649. bool ret = false;
  1650. if(startHpos == dst)
  1651. {
  1652. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1653. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1654. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1655. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  1656. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1657. ret = true;
  1658. }
  1659. else
  1660. {
  1661. CGPath path;
  1662. cb->getPathsInfo(h.get())->getPath(path, dst);
  1663. if(path.nodes.empty())
  1664. {
  1665. logAi->error("Hero %s cannot reach %s.", h->name, dst.toString());
  1666. throw goalFulfilledException(sptr(Goals::VisitTile(dst).sethero(h)));
  1667. }
  1668. int i = path.nodes.size() - 1;
  1669. auto getObj = [&](int3 coord, bool ignoreHero)
  1670. {
  1671. auto tile = cb->getTile(coord, false);
  1672. assert(tile);
  1673. return tile->topVisitableObj(ignoreHero);
  1674. //return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
  1675. };
  1676. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  1677. {
  1678. if(action != CGPathNode::TELEPORT_NORMAL && action != CGPathNode::TELEPORT_BLOCKING_VISIT)
  1679. {
  1680. if(action != CGPathNode::TELEPORT_BATTLE)
  1681. {
  1682. return false;
  1683. }
  1684. }
  1685. return true;
  1686. };
  1687. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1688. {
  1689. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1690. return nextObjectTop;
  1691. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1692. {
  1693. if(CGTeleport::isConnected(currentObject, nextObject))
  1694. return nextObject;
  1695. }
  1696. return nullptr;
  1697. };
  1698. auto doMovement = [&](int3 dst, bool transit)
  1699. {
  1700. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true), transit);
  1701. };
  1702. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1703. {
  1704. destinationTeleport = exitId;
  1705. if(exitPos.valid())
  1706. destinationTeleportPos = CGHeroInstance::convertPosition(exitPos, true);
  1707. cb->moveHero(*h, h->pos);
  1708. destinationTeleport = ObjectInstanceID();
  1709. destinationTeleportPos = int3(-1);
  1710. afterMovementCheck();
  1711. };
  1712. auto doChannelProbing = [&]() -> void
  1713. {
  1714. auto currentPos = CGHeroInstance::convertPosition(h->pos, false);
  1715. auto currentExit = getObj(currentPos, true)->id;
  1716. status.setChannelProbing(true);
  1717. for(auto exit : teleportChannelProbingList)
  1718. doTeleportMovement(exit, int3(-1));
  1719. teleportChannelProbingList.clear();
  1720. status.setChannelProbing(false);
  1721. doTeleportMovement(currentExit, currentPos);
  1722. };
  1723. for(; i > 0; i--)
  1724. {
  1725. int3 currentCoord = path.nodes[i].coord;
  1726. int3 nextCoord = path.nodes[i - 1].coord;
  1727. auto currentObject = getObj(currentCoord, currentCoord == CGHeroInstance::convertPosition(h->pos, false));
  1728. auto nextObjectTop = getObj(nextCoord, false);
  1729. auto nextObject = getObj(nextCoord, true);
  1730. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1731. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1732. {
  1733. //we use special login if hero standing on teleporter it's mean we need
  1734. doTeleportMovement(destTeleportObj->id, nextCoord);
  1735. if(teleportChannelProbingList.size())
  1736. doChannelProbing();
  1737. markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1738. continue;
  1739. }
  1740. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1741. if(path.nodes[i - 1].turns)
  1742. {
  1743. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1744. break;
  1745. }
  1746. int3 endpos = path.nodes[i - 1].coord;
  1747. if(endpos == h->visitablePos())
  1748. continue;
  1749. bool isConnected = false;
  1750. bool isNextObjectTeleport = false;
  1751. // Check there is node after next one; otherwise transit is pointless
  1752. if(i - 2 >= 0)
  1753. {
  1754. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1755. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1756. }
  1757. if(isConnected || isNextObjectTeleport)
  1758. {
  1759. // Hero should be able to go through object if it's allow transit
  1760. doMovement(endpos, true);
  1761. }
  1762. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1763. {
  1764. doMovement(endpos, true);
  1765. }
  1766. else
  1767. {
  1768. doMovement(endpos, false);
  1769. }
  1770. afterMovementCheck();
  1771. if(teleportChannelProbingList.size())
  1772. doChannelProbing();
  1773. }
  1774. }
  1775. if(h)
  1776. {
  1777. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1778. {
  1779. if(visitedObject != *h)
  1780. performObjectInteraction(visitedObject, h);
  1781. }
  1782. }
  1783. if(h) //we could have lost hero after last move
  1784. {
  1785. completeGoal(sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
  1786. completeGoal(sptr(Goals::ClearWayTo(dst).sethero(h)));
  1787. ret = (dst == h->visitablePos());
  1788. if(!ret) //reserve object we are heading towards
  1789. {
  1790. auto obj = vstd::frontOrNull(cb->getVisitableObjs(dst));
  1791. if(obj && obj != *h)
  1792. reserveObject(h, obj);
  1793. }
  1794. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1795. {
  1796. vstd::erase_if_present(lockedHeroes, h); //hero seemingly is confused
  1797. throw cannotFulfillGoalException("Invalid path found!"); //FIXME: should never happen
  1798. }
  1799. evaluateGoal(h); //new hero position means new game situation
  1800. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->name, startHpos.toString(), h->visitablePos().toString(), ret);
  1801. }
  1802. return ret;
  1803. }
  1804. void VCAI::tryRealize(Goals::Explore & g)
  1805. {
  1806. throw cannotFulfillGoalException("EXPLORE is not an elementar goal!");
  1807. }
  1808. void VCAI::tryRealize(Goals::RecruitHero & g)
  1809. {
  1810. if(const CGTownInstance * t = findTownWithTavern())
  1811. {
  1812. recruitHero(t, true);
  1813. //TODO try to free way to blocked town
  1814. //TODO: adventure map tavern or prison?
  1815. }
  1816. }
  1817. void VCAI::tryRealize(Goals::VisitTile & g)
  1818. {
  1819. if(!g.hero->movement)
  1820. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1821. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1822. {
  1823. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->name, g.tile.toString());
  1824. throw goalFulfilledException(sptr(g));
  1825. }
  1826. if(ai->moveHeroToTile(g.tile, g.hero.get()))
  1827. {
  1828. throw goalFulfilledException(sptr(g));
  1829. }
  1830. }
  1831. void VCAI::tryRealize(Goals::VisitHero & g)
  1832. {
  1833. if(!g.hero->movement)
  1834. throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
  1835. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
  1836. if(obj)
  1837. {
  1838. if(ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
  1839. {
  1840. throw goalFulfilledException(sptr(g));
  1841. }
  1842. }
  1843. else
  1844. {
  1845. throw cannotFulfillGoalException("Cannot visit hero: object not found!");
  1846. }
  1847. }
  1848. void VCAI::tryRealize(Goals::BuildThis & g)
  1849. {
  1850. auto b = BuildingID(g.bid);
  1851. auto t = g.town;
  1852. if (t)
  1853. {
  1854. if (cb->canBuildStructure(t, b) == EBuildingState::ALLOWED)
  1855. {
  1856. logAi->debug("Player %d will build %s in town of %s at %s",
  1857. playerID, t->town->buildings.at(b)->Name(), t->name, t->pos.toString());
  1858. cb->buildBuilding(t, b);
  1859. throw goalFulfilledException(sptr(g));
  1860. }
  1861. }
  1862. throw cannotFulfillGoalException("Cannot build a given structure!");
  1863. }
  1864. void VCAI::tryRealize(Goals::DigAtTile & g)
  1865. {
  1866. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1867. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1868. {
  1869. cb->dig(g.hero.get());
  1870. completeGoal(sptr(g)); // finished digging
  1871. }
  1872. else
  1873. {
  1874. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1875. throw cannotFulfillGoalException("A hero can't dig!\n");
  1876. }
  1877. }
  1878. void VCAI::tryRealize(Goals::CollectRes & g) //trade
  1879. {
  1880. if(ah->freeResources()[g.resID] >= g.value) //goal is already fulfilled. Why we need this chek, anyway?
  1881. throw goalFulfilledException(sptr(g));
  1882. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1883. {
  1884. if(const IMarket * m = IMarket::castFrom(obj, false))
  1885. {
  1886. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1887. {
  1888. if(i == g.resID) //sell any other resource
  1889. continue;
  1890. //TODO: check all our reserved resources and avoid them
  1891. int toGive, toGet;
  1892. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1893. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1894. //TODO trade only as much as needed
  1895. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1896. if (ah->freeResources()[g.resID] >= g.value)
  1897. throw goalFulfilledException(sptr(g));
  1898. }
  1899. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1900. }
  1901. else
  1902. {
  1903. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1904. }
  1905. }
  1906. else
  1907. {
  1908. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1909. }
  1910. }
  1911. void VCAI::tryRealize(Goals::Build & g)
  1912. {
  1913. bool didWeBuildSomething = false;
  1914. for(const CGTownInstance * t : cb->getTownsInfo())
  1915. {
  1916. logAi->debug("Looking into %s", t->name);
  1917. potentialBuildings.clear(); //start fresh with every town
  1918. if (tryBuildStructure(t))
  1919. didWeBuildSomething = true;
  1920. else if (potentialBuildings.size())
  1921. {
  1922. auto pb = potentialBuildings.front(); //gather resources for any we can't afford
  1923. auto goal = ah->whatToDo(pb.price, sptr(Goals::BuildThis(pb.bid, t)));
  1924. if (goal->goalType == Goals::BUILD_STRUCTURE)
  1925. {
  1926. logAi->error("We were supposed to NOT afford any building");
  1927. buildStructure(t, pb.bid); //do it right now
  1928. didWeBuildSomething = true;
  1929. }
  1930. else
  1931. {
  1932. //TODO: right now we do that for every town in order. Consider comparison of all potential goals.
  1933. striveToGoal(goal); //gather resources, or something else?
  1934. }
  1935. }
  1936. }
  1937. if (!didWeBuildSomething)
  1938. throw cannotFulfillGoalException("BUILD has been realized as much as possible."); //who catches it and what for?
  1939. }
  1940. void VCAI::tryRealize(Goals::BuyArmy & g)
  1941. {
  1942. auto t = g.town;
  1943. ui64 valueBought = 0;
  1944. //buy the stacks with largest AI value
  1945. while (valueBought < g.value)
  1946. {
  1947. auto res = ah->allResources();
  1948. std::vector<creInfo> creaturesInDwellings;
  1949. for (int i = 0; i < t->creatures.size(); i++)
  1950. {
  1951. auto ci = infoFromDC(t->creatures[i]);
  1952. ci.level = i; //this is important for Dungeon Summoning Portal
  1953. creaturesInDwellings.push_back(ci);
  1954. }
  1955. vstd::erase_if(creaturesInDwellings, [](const creInfo & ci) -> bool
  1956. {
  1957. return !ci.count || ci.creID == -1;
  1958. });
  1959. if (creaturesInDwellings.empty())
  1960. throw cannotFulfillGoalException("Can't buy any more creatures!");
  1961. creInfo ci =
  1962. *boost::max_element(creaturesInDwellings, [&res](const creInfo & lhs, const creInfo & rhs)
  1963. {
  1964. //max value of creatures we can buy with our res
  1965. int value1 = lhs.cre->AIValue * (std::min(lhs.count, res / lhs.cre->cost)),
  1966. value2 = rhs.cre->AIValue * (std::min(rhs.count, res / rhs.cre->cost));
  1967. return value1 < value2;
  1968. });
  1969. vstd::amin(ci.count, res / ci.cre->cost); //max count we can afford
  1970. if (ci.count > 0)
  1971. {
  1972. cb->recruitCreatures(t, t->getUpperArmy(), ci.creID, ci.count, ci.level);
  1973. valueBought += ci.count * ci.cre->AIValue;
  1974. }
  1975. else
  1976. throw cannotFulfillGoalException("Can't buy any more creatures!");
  1977. }
  1978. throw goalFulfilledException(sptr(g)); //we bought as many creatures as we wanted
  1979. }
  1980. void VCAI::tryRealize(Goals::Invalid & g)
  1981. {
  1982. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1983. }
  1984. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1985. {
  1986. logAi->debug("Attempting realizing goal with code %s", g.name());
  1987. throw cannotFulfillGoalException("Unknown type of goal !");
  1988. }
  1989. const CGTownInstance * VCAI::findTownWithTavern() const
  1990. {
  1991. for(const CGTownInstance * t : cb->getTownsInfo())
  1992. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1993. return t;
  1994. return nullptr;
  1995. }
  1996. Goals::TSubgoal VCAI::getGoal(HeroPtr h) const
  1997. {
  1998. auto it = lockedHeroes.find(h);
  1999. if(it != lockedHeroes.end())
  2000. return it->second;
  2001. else
  2002. return sptr(Goals::Invalid());
  2003. }
  2004. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  2005. {
  2006. std::vector<HeroPtr> ret;
  2007. for(auto h : cb->getHeroesInfo())
  2008. {
  2009. //&& !vstd::contains(lockedHeroes, h)
  2010. //at this point we assume heroes exhausted their locked goals
  2011. if(canAct(h))
  2012. ret.push_back(h);
  2013. }
  2014. return ret;
  2015. }
  2016. bool VCAI::canAct(HeroPtr h) const
  2017. {
  2018. auto mission = lockedHeroes.find(h);
  2019. if(mission != lockedHeroes.end())
  2020. {
  2021. //FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
  2022. if(mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
  2023. return false;
  2024. }
  2025. return h->movement;
  2026. }
  2027. HeroPtr VCAI::primaryHero() const
  2028. {
  2029. auto hs = cb->getHeroesInfo();
  2030. if (hs.empty())
  2031. return nullptr;
  2032. else
  2033. return *boost::max_element(hs, compareHeroStrength);
  2034. }
  2035. void VCAI::endTurn()
  2036. {
  2037. logAi->info("Player %d (%s) ends turn", playerID, playerID.getStr());
  2038. if(!status.haveTurn())
  2039. {
  2040. logAi->error("Not having turn at the end of turn???");
  2041. }
  2042. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  2043. do
  2044. {
  2045. cb->endTurn();
  2046. }
  2047. while(status.haveTurn()); //for some reasons, our request may fail -> stop requesting end of turn only after we've received a confirmation that it's over
  2048. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.getStr());
  2049. }
  2050. void VCAI::striveToGoal(Goals::TSubgoal ultimateGoal)
  2051. {
  2052. if(ultimateGoal->invalid())
  2053. return;
  2054. //we are looking for abstract goals
  2055. auto abstractGoal = striveToGoalInternal(ultimateGoal, false);
  2056. if(abstractGoal->invalid())
  2057. return;
  2058. //we received abstract goal, need to find concrete goals
  2059. striveToGoalInternal(abstractGoal, true);
  2060. //TODO: save abstract goals not related to hero
  2061. }
  2062. Goals::TSubgoal VCAI::striveToGoalInternal(Goals::TSubgoal ultimateGoal, bool onlyAbstract)
  2063. {
  2064. const int searchDepth = 30;
  2065. const int searchDepth2 = searchDepth - 2;
  2066. Goals::TSubgoal abstractGoal = sptr(Goals::Invalid());
  2067. while(1)
  2068. {
  2069. Goals::TSubgoal goal = ultimateGoal;
  2070. logAi->debug("Striving to goal of type %s", ultimateGoal->name());
  2071. int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
  2072. while(!goal->isElementar && maxGoals && (onlyAbstract || !goal->isAbstract))
  2073. {
  2074. logAi->debug("Considering goal %s", goal->name());
  2075. try
  2076. {
  2077. boost::this_thread::interruption_point();
  2078. goal = goal->whatToDoToAchieve();
  2079. --maxGoals;
  2080. if(goal == ultimateGoal) //compare objects by value
  2081. throw cannotFulfillGoalException("Goal dependency loop detected!");
  2082. }
  2083. catch(goalFulfilledException & e)
  2084. {
  2085. //it is impossible to continue some goals (like exploration, for example)
  2086. completeGoal(goal);
  2087. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", goal->name());
  2088. return sptr(Goals::Invalid());
  2089. }
  2090. catch(std::exception & e)
  2091. {
  2092. logAi->debug("Goal %s decomposition failed: %s", goal->name(), e.what());
  2093. return sptr(Goals::Invalid());
  2094. }
  2095. }
  2096. try
  2097. {
  2098. boost::this_thread::interruption_point();
  2099. if(!maxGoals) //we counted down to 0 and found no solution
  2100. {
  2101. if(ultimateGoal->hero) // we seemingly don't know what to do with hero, free him
  2102. vstd::erase_if_present(lockedHeroes, ultimateGoal->hero);
  2103. throw (std::runtime_error("Too many subgoals, don't know what to do"));
  2104. }
  2105. else //we found elementar goal and can proceed
  2106. {
  2107. if(goal->hero) //lock this hero to fulfill ultimate goal
  2108. {
  2109. setGoal(goal->hero, goal);
  2110. }
  2111. }
  2112. if(goal->isAbstract)
  2113. {
  2114. abstractGoal = goal; //allow only one abstract goal per call
  2115. logAi->debug("Choosing abstract goal %s", goal->name());
  2116. break;
  2117. }
  2118. else //try realize
  2119. {
  2120. logAi->debug("Trying to realize %s (value %2.3f)", goal->name(), goal->priority);
  2121. goal->accept(this);
  2122. }
  2123. boost::this_thread::interruption_point();
  2124. }
  2125. catch(boost::thread_interrupted & e)
  2126. {
  2127. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  2128. throw; //rethrow, we want to truly end this thread
  2129. }
  2130. catch(goalFulfilledException & e)
  2131. {
  2132. //the sub-goal was completed successfully
  2133. completeGoal(e.goal);
  2134. //local goal was also completed... TODO: or not?
  2135. completeGoal(goal);
  2136. //completed goal was main goal //TODO: find better condition
  2137. if(ultimateGoal->fulfillsMe(goal) || maxGoals > searchDepth2)
  2138. return sptr(Goals::Invalid());
  2139. }
  2140. catch(std::exception & e)
  2141. {
  2142. logAi->debug("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goal->name(), ultimateGoal->name());
  2143. logAi->debug("The error message was: %s", e.what());
  2144. break;
  2145. }
  2146. }
  2147. return abstractGoal;
  2148. }
  2149. void VCAI::striveToQuest(const QuestInfo & q)
  2150. {
  2151. if(q.quest->missionType && q.quest->progress != CQuest::COMPLETE)
  2152. {
  2153. MetaString ms;
  2154. q.quest->getRolloverText(ms, false);
  2155. logAi->debug("Trying to realize quest: %s", ms.toString());
  2156. auto heroes = cb->getHeroesInfo();
  2157. switch(q.quest->missionType)
  2158. {
  2159. case CQuest::MISSION_ART:
  2160. {
  2161. for(auto hero : heroes) //TODO: remove duplicated code?
  2162. {
  2163. if(q.quest->checkQuest(hero))
  2164. {
  2165. striveToGoal(sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  2166. return;
  2167. }
  2168. }
  2169. for(auto art : q.quest->m5arts)
  2170. {
  2171. striveToGoal(sptr(Goals::GetArtOfType(art))); //TODO: transport?
  2172. }
  2173. break;
  2174. }
  2175. case CQuest::MISSION_HERO:
  2176. {
  2177. //striveToGoal (CGoal(RECRUIT_HERO));
  2178. for(auto hero : heroes)
  2179. {
  2180. if(q.quest->checkQuest(hero))
  2181. {
  2182. striveToGoal(sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  2183. return;
  2184. }
  2185. }
  2186. striveToGoal(sptr(Goals::FindObj(Obj::PRISON))); //rule of a thumb - quest heroes usually are locked in prisons
  2187. //BNLOG ("Don't know how to recruit hero with id %d\n", q.quest->m13489val);
  2188. break;
  2189. }
  2190. case CQuest::MISSION_ARMY:
  2191. {
  2192. for(auto hero : heroes)
  2193. {
  2194. if(q.quest->checkQuest(hero)) //very bad info - stacks can be split between multiple heroes :(
  2195. {
  2196. striveToGoal(sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  2197. return;
  2198. }
  2199. }
  2200. for(auto creature : q.quest->m6creatures)
  2201. {
  2202. striveToGoal(sptr(Goals::GatherTroops(creature.type->idNumber, creature.count)));
  2203. }
  2204. //TODO: exchange armies... oh my
  2205. //BNLOG ("Don't know how to recruit %d of %s\n", (int)(creature.count) % creature.type->namePl);
  2206. break;
  2207. }
  2208. case CQuest::MISSION_RESOURCES:
  2209. {
  2210. if(heroes.size())
  2211. {
  2212. if(q.quest->checkQuest(heroes.front())) //it doesn't matter which hero it is
  2213. {
  2214. striveToGoal(sptr(Goals::GetObj(q.obj->id.getNum())));
  2215. }
  2216. else
  2217. {
  2218. for(int i = 0; i < q.quest->m7resources.size(); ++i)
  2219. {
  2220. if(q.quest->m7resources[i])
  2221. striveToGoal(sptr(Goals::CollectRes(i, q.quest->m7resources[i])));
  2222. }
  2223. }
  2224. }
  2225. else
  2226. striveToGoal(sptr(Goals::RecruitHero())); //FIXME: checkQuest requires any hero belonging to player :(
  2227. break;
  2228. }
  2229. case CQuest::MISSION_KILL_HERO:
  2230. case CQuest::MISSION_KILL_CREATURE:
  2231. {
  2232. auto obj = cb->getObjByQuestIdentifier(q.quest->m13489val);
  2233. if(obj)
  2234. striveToGoal(sptr(Goals::GetObj(obj->id.getNum())));
  2235. else
  2236. striveToGoal(sptr(Goals::GetObj(q.obj->id.getNum()))); //visit seer hut
  2237. break;
  2238. }
  2239. case CQuest::MISSION_PRIMARY_STAT:
  2240. {
  2241. auto heroes = cb->getHeroesInfo();
  2242. for(auto hero : heroes)
  2243. {
  2244. if(q.quest->checkQuest(hero))
  2245. {
  2246. striveToGoal(sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  2247. return;
  2248. }
  2249. }
  2250. for(int i = 0; i < q.quest->m2stats.size(); ++i)
  2251. {
  2252. logAi->debug("Don't know how to increase primary stat %d", i);
  2253. }
  2254. break;
  2255. }
  2256. case CQuest::MISSION_LEVEL:
  2257. {
  2258. auto heroes = cb->getHeroesInfo();
  2259. for(auto hero : heroes)
  2260. {
  2261. if(q.quest->checkQuest(hero))
  2262. {
  2263. striveToGoal(sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero))); //TODO: causes infinite loop :/
  2264. return;
  2265. }
  2266. }
  2267. logAi->debug("Don't know how to reach hero level %d", q.quest->m13489val);
  2268. break;
  2269. }
  2270. case CQuest::MISSION_PLAYER:
  2271. {
  2272. if(playerID.getNum() != q.quest->m13489val)
  2273. logAi->debug("Can't be player of color %d", q.quest->m13489val);
  2274. break;
  2275. }
  2276. case CQuest::MISSION_KEYMASTER:
  2277. {
  2278. striveToGoal(sptr(Goals::FindObj(Obj::KEYMASTER, q.obj->subID)));
  2279. break;
  2280. }
  2281. }
  2282. }
  2283. }
  2284. void VCAI::performTypicalActions()
  2285. {
  2286. for(auto h : getUnblockedHeroes())
  2287. {
  2288. if(!h) //hero might be lost. getUnblockedHeroes() called once on start of turn
  2289. continue;
  2290. logAi->debug("Looking into %s, MP=%d", h->name.c_str(), h->movement);
  2291. makePossibleUpgrades(*h);
  2292. pickBestArtifacts(*h);
  2293. try
  2294. {
  2295. wander(h);
  2296. }
  2297. catch(std::exception & e)
  2298. {
  2299. logAi->debug("Cannot use this hero anymore, received exception: %s", e.what());
  2300. continue;
  2301. }
  2302. }
  2303. }
  2304. void VCAI::buildArmyIn(const CGTownInstance * t)
  2305. {
  2306. makePossibleUpgrades(t->visitingHero);
  2307. makePossibleUpgrades(t);
  2308. recruitCreatures(t, t->getUpperArmy());
  2309. moveCreaturesToHero(t);
  2310. }
  2311. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  2312. {
  2313. std::map<int3, int> dstToRevealedTiles;
  2314. for(crint3 dir : int3::getDirs())
  2315. {
  2316. int3 tile = hpos + dir;
  2317. if(cb->isInTheMap(tile))
  2318. {
  2319. if(isBlockVisitObj(tile))
  2320. continue;
  2321. if(isSafeToVisit(h, tile) && isAccessibleForHero(tile, h))
  2322. {
  2323. auto distance = hpos.dist2d(tile); // diagonal movement opens more tiles but spends more mp
  2324. dstToRevealedTiles[tile] = howManyTilesWillBeDiscovered(tile, radius, cb.get(), h) / distance;
  2325. }
  2326. }
  2327. }
  2328. if(dstToRevealedTiles.empty()) //yes, it DID happen!
  2329. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2330. auto best = dstToRevealedTiles.begin();
  2331. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  2332. {
  2333. const CGPathNode * pn = cb->getPathsInfo(h.get())->getPathInfo(i->first);
  2334. //const TerrainTile *t = cb->getTile(i->first);
  2335. if(best->second < i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  2336. best = i;
  2337. }
  2338. if(best->second)
  2339. return best->first;
  2340. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2341. }
  2342. int3 VCAI::explorationNewPoint(HeroPtr h)
  2343. {
  2344. int radius = h->getSightRadius();
  2345. CCallback * cbp = cb.get();
  2346. const CGHeroInstance * hero = h.get();
  2347. std::vector<std::vector<int3>> tiles; //tiles[distance_to_fow]
  2348. tiles.resize(radius);
  2349. foreach_tile_pos([&](const int3 & pos)
  2350. {
  2351. if(!cbp->isVisible(pos))
  2352. tiles[0].push_back(pos);
  2353. });
  2354. float bestValue = 0; //discovered tile to node distance ratio
  2355. int3 bestTile(-1, -1, -1);
  2356. int3 ourPos = h->convertPosition(h->pos, false);
  2357. for(int i = 1; i < radius; i++)
  2358. {
  2359. getVisibleNeighbours(tiles[i - 1], tiles[i]);
  2360. vstd::removeDuplicates(tiles[i]);
  2361. for(const int3 & tile : tiles[i])
  2362. {
  2363. if(tile == ourPos) //shouldn't happen, but it does
  2364. continue;
  2365. if(!cb->getPathsInfo(hero)->getPathInfo(tile)->reachable()) //this will remove tiles that are guarded by monsters (or removable objects)
  2366. continue;
  2367. CGPath path;
  2368. cb->getPathsInfo(hero)->getPath(path, tile);
  2369. float ourValue = (float)howManyTilesWillBeDiscovered(tile, radius, cbp, h) / (path.nodes.size() + 1); //+1 prevents erratic jumps
  2370. if(ourValue > bestValue) //avoid costly checks of tiles that don't reveal much
  2371. {
  2372. if(isSafeToVisit(h, tile))
  2373. {
  2374. if(isBlockVisitObj(tile)) //we can't stand on that object
  2375. continue;
  2376. bestTile = tile;
  2377. bestValue = ourValue;
  2378. }
  2379. }
  2380. }
  2381. }
  2382. return bestTile;
  2383. }
  2384. int3 VCAI::explorationDesperate(HeroPtr h)
  2385. {
  2386. auto sm = getCachedSectorMap(h);
  2387. int radius = h->getSightRadius();
  2388. std::vector<std::vector<int3>> tiles; //tiles[distance_to_fow]
  2389. tiles.resize(radius);
  2390. CCallback * cbp = cb.get();
  2391. foreach_tile_pos([&](const int3 & pos)
  2392. {
  2393. if(!cbp->isVisible(pos))
  2394. tiles[0].push_back(pos);
  2395. });
  2396. ui64 lowestDanger = -1;
  2397. int3 bestTile(-1, -1, -1);
  2398. for(int i = 1; i < radius; i++)
  2399. {
  2400. getVisibleNeighbours(tiles[i - 1], tiles[i]);
  2401. vstd::removeDuplicates(tiles[i]);
  2402. for(const int3 & tile : tiles[i])
  2403. {
  2404. if(cbp->getTile(tile)->blocked) //does it shorten the time?
  2405. continue;
  2406. if(!howManyTilesWillBeDiscovered(tile, radius, cbp, h)) //avoid costly checks of tiles that don't reveal much
  2407. continue;
  2408. auto t = sm->firstTileToGet(h, tile);
  2409. if(t.valid())
  2410. {
  2411. ui64 ourDanger = evaluateDanger(t, h.h);
  2412. if(ourDanger < lowestDanger)
  2413. {
  2414. if(!isBlockVisitObj(t))
  2415. {
  2416. if(!ourDanger) //at least one safe place found
  2417. return t;
  2418. bestTile = t;
  2419. lowestDanger = ourDanger;
  2420. }
  2421. }
  2422. }
  2423. }
  2424. }
  2425. return bestTile;
  2426. }
  2427. void VCAI::checkHeroArmy(HeroPtr h)
  2428. {
  2429. auto it = lockedHeroes.find(h);
  2430. if(it != lockedHeroes.end())
  2431. {
  2432. if(it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  2433. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  2434. }
  2435. }
  2436. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2437. {
  2438. logAi->debug("Trying to recruit a hero in %s at %s", t->name, t->visitablePos().toString());
  2439. auto heroes = cb->getAvailableHeroes(t);
  2440. if(heroes.size())
  2441. {
  2442. auto hero = heroes[0];
  2443. if(heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
  2444. {
  2445. if(heroes[1]->getTotalStrength() > hero->getTotalStrength())
  2446. hero = heroes[1];
  2447. }
  2448. cb->recruitHero(t, hero);
  2449. throw goalFulfilledException(sptr(Goals::RecruitHero().settown(t)));
  2450. }
  2451. else if(throwing)
  2452. {
  2453. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2454. }
  2455. }
  2456. void VCAI::finish()
  2457. {
  2458. if(makingTurn)
  2459. {
  2460. makingTurn->interrupt();
  2461. makingTurn->join();
  2462. makingTurn.reset();
  2463. }
  2464. }
  2465. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  2466. {
  2467. boost::thread newThread([this, whatToDo]()
  2468. {
  2469. setThreadName("VCAI::requestActionASAP::whatToDo");
  2470. SET_GLOBAL_STATE(this);
  2471. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  2472. whatToDo();
  2473. });
  2474. }
  2475. void VCAI::lostHero(HeroPtr h)
  2476. {
  2477. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
  2478. vstd::erase_if_present(lockedHeroes, h);
  2479. for(auto obj : reservedHeroesMap[h])
  2480. {
  2481. vstd::erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2482. }
  2483. vstd::erase_if_present(reservedHeroesMap, h);
  2484. vstd::erase_if_present(cachedSectorMaps, h);
  2485. }
  2486. void VCAI::answerQuery(QueryID queryID, int selection)
  2487. {
  2488. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  2489. if(queryID != QueryID(-1))
  2490. {
  2491. cb->selectionMade(selection, queryID);
  2492. }
  2493. else
  2494. {
  2495. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2496. //do nothing
  2497. }
  2498. }
  2499. void VCAI::requestSent(const CPackForServer * pack, int requestID)
  2500. {
  2501. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2502. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  2503. {
  2504. status.attemptedAnsweringQuery(reply->qid, requestID);
  2505. }
  2506. }
  2507. std::string VCAI::getBattleAIName() const
  2508. {
  2509. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  2510. return settings["server"]["enemyAI"].String();
  2511. else
  2512. return "BattleAI";
  2513. }
  2514. void VCAI::validateObject(const CGObjectInstance * obj)
  2515. {
  2516. validateObject(obj->id);
  2517. }
  2518. void VCAI::validateObject(ObjectIdRef obj)
  2519. {
  2520. auto matchesId = [&](const CGObjectInstance * hlpObj) -> bool
  2521. {
  2522. return hlpObj->id == obj.id;
  2523. };
  2524. if(!obj)
  2525. {
  2526. vstd::erase_if(visitableObjs, matchesId);
  2527. for(auto & p : reservedHeroesMap)
  2528. vstd::erase_if(p.second, matchesId);
  2529. vstd::erase_if(reservedObjs, matchesId);
  2530. }
  2531. }
  2532. std::shared_ptr<SectorMap> VCAI::getCachedSectorMap(HeroPtr h)
  2533. {
  2534. auto it = cachedSectorMaps.find(h);
  2535. if(it != cachedSectorMaps.end())
  2536. {
  2537. return it->second;
  2538. }
  2539. else
  2540. {
  2541. cachedSectorMaps[h] = std::make_shared<SectorMap>(h);
  2542. return cachedSectorMaps[h];
  2543. }
  2544. }
  2545. AIStatus::AIStatus()
  2546. {
  2547. battle = NO_BATTLE;
  2548. havingTurn = false;
  2549. ongoingHeroMovement = false;
  2550. ongoingChannelProbing = false;
  2551. }
  2552. AIStatus::~AIStatus()
  2553. {
  2554. }
  2555. void AIStatus::setBattle(BattleState BS)
  2556. {
  2557. boost::unique_lock<boost::mutex> lock(mx);
  2558. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2559. battle = BS;
  2560. cv.notify_all();
  2561. }
  2562. BattleState AIStatus::getBattle()
  2563. {
  2564. boost::unique_lock<boost::mutex> lock(mx);
  2565. return battle;
  2566. }
  2567. void AIStatus::addQuery(QueryID ID, std::string description)
  2568. {
  2569. if(ID == QueryID(-1))
  2570. {
  2571. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  2572. return;
  2573. }
  2574. assert(ID.getNum() >= 0);
  2575. boost::unique_lock<boost::mutex> lock(mx);
  2576. assert(!vstd::contains(remainingQueries, ID));
  2577. remainingQueries[ID] = description;
  2578. cv.notify_all();
  2579. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2580. }
  2581. void AIStatus::removeQuery(QueryID ID)
  2582. {
  2583. boost::unique_lock<boost::mutex> lock(mx);
  2584. assert(vstd::contains(remainingQueries, ID));
  2585. std::string description = remainingQueries[ID];
  2586. remainingQueries.erase(ID);
  2587. cv.notify_all();
  2588. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2589. }
  2590. int AIStatus::getQueriesCount()
  2591. {
  2592. boost::unique_lock<boost::mutex> lock(mx);
  2593. return remainingQueries.size();
  2594. }
  2595. void AIStatus::startedTurn()
  2596. {
  2597. boost::unique_lock<boost::mutex> lock(mx);
  2598. havingTurn = true;
  2599. cv.notify_all();
  2600. }
  2601. void AIStatus::madeTurn()
  2602. {
  2603. boost::unique_lock<boost::mutex> lock(mx);
  2604. havingTurn = false;
  2605. cv.notify_all();
  2606. }
  2607. void AIStatus::waitTillFree()
  2608. {
  2609. boost::unique_lock<boost::mutex> lock(mx);
  2610. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2611. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  2612. }
  2613. bool AIStatus::haveTurn()
  2614. {
  2615. boost::unique_lock<boost::mutex> lock(mx);
  2616. return havingTurn;
  2617. }
  2618. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2619. {
  2620. boost::unique_lock<boost::mutex> lock(mx);
  2621. assert(vstd::contains(remainingQueries, queryID));
  2622. std::string description = remainingQueries[queryID];
  2623. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  2624. requestToQueryID[answerRequestID] = queryID;
  2625. }
  2626. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2627. {
  2628. assert(vstd::contains(requestToQueryID, answerRequestID));
  2629. QueryID query = requestToQueryID[answerRequestID];
  2630. assert(vstd::contains(remainingQueries, query));
  2631. requestToQueryID.erase(answerRequestID);
  2632. if(result)
  2633. {
  2634. removeQuery(query);
  2635. }
  2636. else
  2637. {
  2638. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  2639. //TODO safely retry
  2640. }
  2641. }
  2642. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  2643. {
  2644. boost::unique_lock<boost::mutex> lock(mx);
  2645. if(started)
  2646. {
  2647. objectsBeingVisited.push_back(obj);
  2648. }
  2649. else
  2650. {
  2651. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2652. // causing visit to hero on the other side.
  2653. // However, we are guaranteed that start/end visit notification maintain stack order.
  2654. assert(!objectsBeingVisited.empty());
  2655. objectsBeingVisited.pop_back();
  2656. }
  2657. cv.notify_all();
  2658. }
  2659. void AIStatus::setMove(bool ongoing)
  2660. {
  2661. boost::unique_lock<boost::mutex> lock(mx);
  2662. ongoingHeroMovement = ongoing;
  2663. cv.notify_all();
  2664. }
  2665. void AIStatus::setChannelProbing(bool ongoing)
  2666. {
  2667. boost::unique_lock<boost::mutex> lock(mx);
  2668. ongoingChannelProbing = ongoing;
  2669. cv.notify_all();
  2670. }
  2671. bool AIStatus::channelProbing()
  2672. {
  2673. return ongoingChannelProbing;
  2674. }
  2675. SectorMap::SectorMap()
  2676. {
  2677. update();
  2678. }
  2679. SectorMap::SectorMap(HeroPtr h)
  2680. {
  2681. update();
  2682. makeParentBFS(h->visitablePos());
  2683. }
  2684. bool SectorMap::markIfBlocked(TSectorID & sec, crint3 pos, const TerrainTile * t)
  2685. {
  2686. if(t->blocked && !t->visitable)
  2687. {
  2688. sec = NOT_AVAILABLE;
  2689. return true;
  2690. }
  2691. return false;
  2692. }
  2693. bool SectorMap::markIfBlocked(TSectorID & sec, crint3 pos)
  2694. {
  2695. return markIfBlocked(sec, pos, getTile(pos));
  2696. }
  2697. void SectorMap::update()
  2698. {
  2699. visibleTiles = cb->getAllVisibleTiles();
  2700. auto shape = visibleTiles->shape();
  2701. sector.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
  2702. clear();
  2703. int curSector = 3; //0 is invisible, 1 is not explored
  2704. CCallback * cbp = cb.get(); //optimization
  2705. foreach_tile_pos([&](crint3 pos)
  2706. {
  2707. if(retrieveTile(pos) == NOT_CHECKED)
  2708. {
  2709. if(!markIfBlocked(retrieveTile(pos), pos))
  2710. exploreNewSector(pos, curSector++, cbp);
  2711. }
  2712. });
  2713. valid = true;
  2714. }
  2715. SectorMap::TSectorID & SectorMap::retrieveTileN(SectorMap::TSectorArray & a, const int3 & pos)
  2716. {
  2717. return a[pos.x][pos.y][pos.z];
  2718. }
  2719. const SectorMap::TSectorID & SectorMap::retrieveTileN(const SectorMap::TSectorArray & a, const int3 & pos)
  2720. {
  2721. return a[pos.x][pos.y][pos.z];
  2722. }
  2723. void SectorMap::clear()
  2724. {
  2725. //TODO: rotate to [z][x][y]
  2726. auto fow = cb->getVisibilityMap();
  2727. //TODO: any magic to automate this? will need array->array conversion
  2728. //std::transform(fow.begin(), fow.end(), sector.begin(), [](const ui8 &f) -> unsigned short
  2729. //{
  2730. // return f; //type conversion
  2731. //});
  2732. auto width = fow.size();
  2733. auto height = fow.front().size();
  2734. auto depth = fow.front().front().size();
  2735. for(size_t x = 0; x < width; x++)
  2736. {
  2737. for(size_t y = 0; y < height; y++)
  2738. {
  2739. for(size_t z = 0; z < depth; z++)
  2740. sector[x][y][z] = fow[x][y][z];
  2741. }
  2742. }
  2743. valid = false;
  2744. }
  2745. void SectorMap::exploreNewSector(crint3 pos, int num, CCallback * cbp)
  2746. {
  2747. Sector & s = infoOnSectors[num];
  2748. s.id = num;
  2749. s.water = getTile(pos)->isWater();
  2750. std::queue<int3> toVisit;
  2751. toVisit.push(pos);
  2752. while(!toVisit.empty())
  2753. {
  2754. int3 curPos = toVisit.front();
  2755. toVisit.pop();
  2756. TSectorID & sec = retrieveTile(curPos);
  2757. if(sec == NOT_CHECKED)
  2758. {
  2759. const TerrainTile * t = getTile(curPos);
  2760. if(!markIfBlocked(sec, curPos, t))
  2761. {
  2762. if(t->isWater() == s.water) //sector is only-water or only-land
  2763. {
  2764. sec = num;
  2765. s.tiles.push_back(curPos);
  2766. foreach_neighbour(cbp, curPos, [&](CCallback * cbp, crint3 neighPos)
  2767. {
  2768. if(retrieveTile(neighPos) == NOT_CHECKED)
  2769. {
  2770. toVisit.push(neighPos);
  2771. //parent[neighPos] = curPos;
  2772. }
  2773. const TerrainTile * nt = getTile(neighPos);
  2774. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt, s.water))
  2775. {
  2776. s.embarkmentPoints.push_back(neighPos);
  2777. }
  2778. });
  2779. if(t->visitable)
  2780. {
  2781. auto obj = t->visitableObjects.front();
  2782. if(cb->getObj(obj->id, false)) // FIXME: we have to filter invisible objcts like events, but probably TerrainTile shouldn't be used in SectorMap at all
  2783. s.visitableObjs.push_back(obj);
  2784. }
  2785. }
  2786. }
  2787. }
  2788. }
  2789. vstd::removeDuplicates(s.embarkmentPoints);
  2790. }
  2791. void SectorMap::write(crstring fname)
  2792. {
  2793. std::ofstream out(fname);
  2794. for(int k = 0; k < cb->getMapSize().z; k++)
  2795. {
  2796. for(int j = 0; j < cb->getMapSize().y; j++)
  2797. {
  2798. for(int i = 0; i < cb->getMapSize().x; i++)
  2799. {
  2800. out << (int)sector[i][j][k] << '\t';
  2801. }
  2802. out << std::endl;
  2803. }
  2804. out << std::endl;
  2805. }
  2806. }
  2807. bool isWeeklyRevisitable(const CGObjectInstance * obj)
  2808. {
  2809. //TODO: allow polling of remaining creatures in dwelling
  2810. if(dynamic_cast<const CGVisitableOPW *>(obj)) // ensures future compatibility, unlike IDs
  2811. return true;
  2812. if(dynamic_cast<const CGDwelling *>(obj))
  2813. return true;
  2814. if(dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2815. return true;
  2816. switch(obj->ID)
  2817. {
  2818. case Obj::STABLES:
  2819. case Obj::MAGIC_WELL:
  2820. case Obj::HILL_FORT:
  2821. return true;
  2822. case Obj::BORDER_GATE:
  2823. case Obj::BORDERGUARD:
  2824. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  2825. }
  2826. return false;
  2827. }
  2828. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2829. {
  2830. switch(obj->ID)
  2831. {
  2832. case Obj::TOWN:
  2833. case Obj::HERO: //never visit our heroes at random
  2834. return obj->tempOwner != h->tempOwner; //do not visit our towns at random
  2835. case Obj::BORDER_GATE:
  2836. {
  2837. for(auto q : ai->myCb->getMyQuests())
  2838. {
  2839. if(q.obj == obj)
  2840. {
  2841. return false; // do not visit guards or gates when wandering
  2842. }
  2843. }
  2844. return true; //we don't have this quest yet
  2845. }
  2846. case Obj::BORDERGUARD: //open borderguard if possible
  2847. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  2848. case Obj::SEER_HUT:
  2849. case Obj::QUEST_GUARD:
  2850. {
  2851. for(auto q : ai->myCb->getMyQuests())
  2852. {
  2853. if(q.obj == obj)
  2854. {
  2855. if(q.quest->checkQuest(h.h))
  2856. return true; //we completed the quest
  2857. else
  2858. return false; //we can't complete this quest
  2859. }
  2860. }
  2861. return true; //we don't have this quest yet
  2862. }
  2863. case Obj::CREATURE_GENERATOR1:
  2864. {
  2865. if(obj->tempOwner != h->tempOwner)
  2866. return true; //flag just in case
  2867. bool canRecruitCreatures = false;
  2868. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2869. for(auto level : d->creatures)
  2870. {
  2871. for(auto c : level.second)
  2872. {
  2873. if(h->getSlotFor(CreatureID(c)) != SlotID())
  2874. canRecruitCreatures = true;
  2875. }
  2876. }
  2877. return canRecruitCreatures;
  2878. }
  2879. case Obj::HILL_FORT:
  2880. {
  2881. for(auto slot : h->Slots())
  2882. {
  2883. if(slot.second->type->upgrades.size())
  2884. return true; //TODO: check price?
  2885. }
  2886. return false;
  2887. }
  2888. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2889. case Obj::MONOLITH_ONE_WAY_EXIT:
  2890. case Obj::MONOLITH_TWO_WAY:
  2891. case Obj::WHIRLPOOL:
  2892. return false;
  2893. case Obj::SCHOOL_OF_MAGIC:
  2894. case Obj::SCHOOL_OF_WAR:
  2895. {
  2896. if (ah->freeGold() < 1000)
  2897. return false;
  2898. break;
  2899. }
  2900. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2901. if(h->level < 12)
  2902. return false;
  2903. break;
  2904. case Obj::TREE_OF_KNOWLEDGE:
  2905. {
  2906. TResources myRes = ah->freeResources();
  2907. if(myRes[Res::GOLD] < 2000 || myRes[Res::GEMS] < 10)
  2908. return false;
  2909. break;
  2910. }
  2911. case Obj::MAGIC_WELL:
  2912. return h->mana < h->manaLimit();
  2913. case Obj::PRISON:
  2914. return ai->myCb->getHeroesInfo().size() < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER;
  2915. case Obj::TAVERN:
  2916. {
  2917. //TODO: make AI actually recruit heroes
  2918. //TODO: only on request
  2919. if(ai->myCb->getHeroesInfo().size() >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)
  2920. return false;
  2921. else if(ah->freeGold() < GameConstants::HERO_GOLD_COST)
  2922. return false;
  2923. break;
  2924. }
  2925. case Obj::BOAT:
  2926. return false;
  2927. //Boats are handled by pathfinder
  2928. case Obj::EYE_OF_MAGI:
  2929. return false; //this object is useless to visit, but could be visited indefinitely
  2930. }
  2931. if(obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2932. return false;
  2933. return true;
  2934. }
  2935. /*
  2936. this functions returns one target tile or invalid tile. We will use it to poll possible destinations
  2937. For ship construction etc, another function (goal?) is needed
  2938. */
  2939. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  2940. {
  2941. int3 ret(-1, -1, -1);
  2942. int sourceSector = retrieveTile(h->visitablePos());
  2943. int destinationSector = retrieveTile(dst);
  2944. const Sector * src = &infoOnSectors[sourceSector];
  2945. const Sector * dest = &infoOnSectors[destinationSector];
  2946. if(sourceSector != destinationSector) //use ships, shipyards etc..
  2947. {
  2948. if(ai->isAccessibleForHero(dst, h)) //pathfinder can find a way using ships and gates if tile is not blocked by objects
  2949. return dst;
  2950. std::map<const Sector *, const Sector *> preds;
  2951. std::queue<const Sector *> sectorQueue;
  2952. sectorQueue.push(src);
  2953. while(!sectorQueue.empty())
  2954. {
  2955. const Sector * s = sectorQueue.front();
  2956. sectorQueue.pop();
  2957. for(int3 ep : s->embarkmentPoints)
  2958. {
  2959. Sector * neigh = &infoOnSectors[retrieveTile(ep)];
  2960. //preds[s].push_back(neigh);
  2961. if(!preds[neigh])
  2962. {
  2963. preds[neigh] = s;
  2964. sectorQueue.push(neigh);
  2965. }
  2966. }
  2967. }
  2968. if(!preds[dest])
  2969. {
  2970. //write("test.txt");
  2971. return ret;
  2972. //throw cannotFulfillGoalException(boost::str(boost::format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  2973. }
  2974. std::vector<const Sector *> toTraverse;
  2975. toTraverse.push_back(dest);
  2976. while(toTraverse.back() != src)
  2977. {
  2978. toTraverse.push_back(preds[toTraverse.back()]);
  2979. }
  2980. if(preds[dest])
  2981. {
  2982. //TODO: would be nice to find sectors in loop
  2983. const Sector * sectorToReach = toTraverse.at(toTraverse.size() - 2);
  2984. if(!src->water && sectorToReach->water) //embark
  2985. {
  2986. //embark on ship -> look for an EP with a boat
  2987. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  2988. {
  2989. const TerrainTile * t = getTile(pos);
  2990. if(t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT)
  2991. {
  2992. if(retrieveTile(pos) == sectorToReach->id)
  2993. return true;
  2994. }
  2995. return false;
  2996. });
  2997. if(firstEP != src->embarkmentPoints.end())
  2998. {
  2999. return *firstEP;
  3000. }
  3001. else
  3002. {
  3003. //we need to find a shipyard with an access to the desired sector's EP
  3004. //TODO what about Summon Boat spell?
  3005. std::vector<const IShipyard *> shipyards;
  3006. for(const CGTownInstance * t : cb->getTownsInfo())
  3007. {
  3008. if(t->hasBuilt(BuildingID::SHIPYARD))
  3009. shipyards.push_back(t);
  3010. }
  3011. for(const CGObjectInstance * obj : ai->getFlaggedObjects())
  3012. {
  3013. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  3014. {
  3015. if(const IShipyard * shipyard = IShipyard::castFrom(obj))
  3016. shipyards.push_back(shipyard);
  3017. }
  3018. }
  3019. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard * shipyard) -> bool
  3020. {
  3021. return shipyard->shipyardStatus() != 0 || retrieveTile(shipyard->bestLocation()) != sectorToReach->id;
  3022. }), shipyards.end());
  3023. if(!shipyards.size())
  3024. {
  3025. //TODO consider possibility of building shipyard in a town
  3026. return ret;
  3027. //throw cannotFulfillGoalException("There is no known shipyard!");
  3028. }
  3029. //we have only shipyards that possibly can build ships onto the appropriate EP
  3030. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard * s) -> bool
  3031. {
  3032. return s->o->tempOwner == ai->playerID;
  3033. });
  3034. if(ownedGoodShipyard != shipyards.end())
  3035. {
  3036. const IShipyard * s = *ownedGoodShipyard;
  3037. TResources shipCost;
  3038. s->getBoatCost(shipCost);
  3039. if(cb->getResourceAmount().canAfford(shipCost))
  3040. {
  3041. int3 ret = s->bestLocation();
  3042. cb->buildBoat(s); //TODO: move actions elsewhere
  3043. return ret;
  3044. }
  3045. else
  3046. {
  3047. //TODO gather res
  3048. return ret;
  3049. //throw cannotFulfillGoalException("Not enough resources to build a boat");
  3050. }
  3051. }
  3052. else
  3053. {
  3054. //TODO pick best shipyard to take over
  3055. return shipyards.front()->o->visitablePos();
  3056. }
  3057. }
  3058. }
  3059. else if(src->water && !sectorToReach->water)
  3060. {
  3061. //TODO
  3062. //disembark
  3063. return ret;
  3064. }
  3065. else //use subterranean gates - not needed since gates are now handled via Pathfinder
  3066. {
  3067. return ret;
  3068. //throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  3069. }
  3070. }
  3071. else
  3072. {
  3073. return ret;
  3074. //throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  3075. }
  3076. }
  3077. else
  3078. {
  3079. return findFirstVisitableTile(h, dst);
  3080. }
  3081. }
  3082. int3 SectorMap::findFirstVisitableTile(HeroPtr h, crint3 dst)
  3083. {
  3084. int3 ret(-1, -1, -1);
  3085. int3 curtile = dst;
  3086. while(curtile != h->visitablePos())
  3087. {
  3088. auto topObj = cb->getTopObj(curtile);
  3089. if(topObj && topObj->ID == Obj::HERO && topObj != h.h)
  3090. {
  3091. if(cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  3092. {
  3093. logAi->warn("Another allied hero stands in our way");
  3094. return ret;
  3095. }
  3096. }
  3097. if(ai->myCb->getPathsInfo(h.get())->getPathInfo(curtile)->reachable())
  3098. {
  3099. return curtile;
  3100. }
  3101. else
  3102. {
  3103. auto i = parent.find(curtile);
  3104. if(i != parent.end())
  3105. {
  3106. assert(curtile != i->second);
  3107. curtile = i->second;
  3108. }
  3109. else
  3110. {
  3111. return ret;
  3112. //throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  3113. }
  3114. }
  3115. }
  3116. return ret;
  3117. }
  3118. void SectorMap::makeParentBFS(crint3 source)
  3119. {
  3120. parent.clear();
  3121. int mySector = retrieveTile(source);
  3122. std::queue<int3> toVisit;
  3123. toVisit.push(source);
  3124. while(!toVisit.empty())
  3125. {
  3126. int3 curPos = toVisit.front();
  3127. toVisit.pop();
  3128. TSectorID & sec = retrieveTile(curPos);
  3129. assert(sec == mySector); //consider only tiles from the same sector
  3130. UNUSED(sec);
  3131. foreach_neighbour(curPos, [&](crint3 neighPos)
  3132. {
  3133. if(retrieveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  3134. {
  3135. if(cb->canMoveBetween(curPos, neighPos))
  3136. {
  3137. toVisit.push(neighPos);
  3138. parent[neighPos] = curPos;
  3139. }
  3140. }
  3141. });
  3142. }
  3143. }
  3144. SectorMap::TSectorID & SectorMap::retrieveTile(crint3 pos)
  3145. {
  3146. return retrieveTileN(sector, pos);
  3147. }
  3148. TerrainTile * SectorMap::getTile(crint3 pos) const
  3149. {
  3150. //out of bounds access should be handled by boost::multi_array
  3151. //still we cached this array to avoid any checks
  3152. return visibleTiles->operator[](pos.x)[pos.y][pos.z];
  3153. }
  3154. std::vector<const CGObjectInstance *> SectorMap::getNearbyObjs(HeroPtr h, bool sectorsAround)
  3155. {
  3156. const Sector * heroSector = &infoOnSectors[retrieveTile(h->visitablePos())];
  3157. if(sectorsAround)
  3158. {
  3159. std::vector<const CGObjectInstance *> ret;
  3160. for(auto embarkPoint : heroSector->embarkmentPoints)
  3161. {
  3162. const Sector * embarkSector = &infoOnSectors[retrieveTile(embarkPoint)];
  3163. range::copy(embarkSector->visitableObjs, std::back_inserter(ret));
  3164. }
  3165. return ret;
  3166. }
  3167. return heroSector->visitableObjs;
  3168. }