VCAI.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059
  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 "FuzzyHelper.h"
  13. #include "ResourceManager.h"
  14. #include "BuildingManager.h"
  15. #include "Goals/Goals.h"
  16. #include "../../lib/UnlockGuard.h"
  17. #include "../../lib/mapObjects/MapObjects.h"
  18. #include "../../lib/CConfigHandler.h"
  19. #include "../../lib/CHeroHandler.h"
  20. #include "../../lib/CModHandler.h"
  21. #include "../../lib/CGameState.h"
  22. #include "../../lib/NetPacks.h"
  23. #include "../../lib/serializer/CTypeList.h"
  24. #include "../../lib/serializer/BinarySerializer.h"
  25. #include "../../lib/serializer/BinaryDeserializer.h"
  26. #include "AIhelper.h"
  27. extern FuzzyHelper * fh;
  28. class CGVisitableOPW;
  29. const double SAFE_ATTACK_CONSTANT = 1.5;
  30. //one thread may be turn of AI and another will be handling a side effect for AI2
  31. boost::thread_specific_ptr<CCallback> cb;
  32. boost::thread_specific_ptr<VCAI> ai;
  33. //std::map<int, std::map<int, int> > HeroView::infosCount;
  34. //helper RAII to manage global ai/cb ptrs
  35. struct SetGlobalState
  36. {
  37. SetGlobalState(VCAI * AI)
  38. {
  39. assert(!ai.get());
  40. assert(!cb.get());
  41. ai.reset(AI);
  42. cb.reset(AI->myCb.get());
  43. }
  44. ~SetGlobalState()
  45. {
  46. //TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
  47. //TODO: to ensure that, make rm unique_ptr
  48. ai.release();
  49. cb.release();
  50. }
  51. };
  52. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  53. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  54. #define MAKING_TURN SET_GLOBAL_STATE(this)
  55. void foreach_tile(std::vector<std::vector<std::vector<unsigned char>>> & vectors, std::function<void(unsigned char & in)> foo)
  56. {
  57. for(auto & vector : vectors)
  58. {
  59. for(auto j = vector.begin(); j != vector.end(); j++)
  60. {
  61. for(auto & elem : *j)
  62. foo(elem);
  63. }
  64. }
  65. }
  66. struct ObjInfo
  67. {
  68. int3 pos;
  69. std::string name;
  70. ObjInfo(){}
  71. ObjInfo(const CGObjectInstance * obj)
  72. : pos(obj->pos), name(obj->getObjectName())
  73. {
  74. }
  75. };
  76. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  77. VCAI::VCAI()
  78. {
  79. LOG_TRACE(logAi);
  80. makingTurn = nullptr;
  81. destinationTeleport = ObjectInstanceID();
  82. destinationTeleportPos = int3(-1);
  83. ah = new AIhelper();
  84. ah->setAI(this);
  85. }
  86. VCAI::~VCAI()
  87. {
  88. delete ah;
  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. ah->resetPaths();
  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::VisitObj(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. if (visitedObj->ID == Obj::HERO)
  234. {
  235. visitedHeroes[visitor].insert(HeroPtr(dynamic_cast<const CGHeroInstance *>(visitedObj)));
  236. }
  237. }
  238. status.heroVisit(visitedObj, start);
  239. }
  240. void VCAI::availableArtifactsChanged(const CGBlackMarket * bm)
  241. {
  242. LOG_TRACE(logAi);
  243. NET_EVENT_HANDLER;
  244. }
  245. void VCAI::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
  246. {
  247. LOG_TRACE(logAi);
  248. NET_EVENT_HANDLER;
  249. //buildArmyIn(town);
  250. //moveCreaturesToHero(town);
  251. }
  252. void VCAI::tileHidden(const std::unordered_set<int3, ShashInt3> & pos)
  253. {
  254. LOG_TRACE(logAi);
  255. NET_EVENT_HANDLER;
  256. validateVisitableObjs();
  257. clearPathsInfo();
  258. }
  259. void VCAI::tileRevealed(const std::unordered_set<int3, ShashInt3> & pos)
  260. {
  261. LOG_TRACE(logAi);
  262. NET_EVENT_HANDLER;
  263. for(int3 tile : pos)
  264. {
  265. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  266. addVisitableObj(obj);
  267. }
  268. clearPathsInfo();
  269. }
  270. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  271. {
  272. LOG_TRACE(logAi);
  273. NET_EVENT_HANDLER;
  274. auto firstHero = cb->getHero(hero1);
  275. auto secondHero = cb->getHero(hero2);
  276. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->name % firstHero->tempOwner % secondHero->name % secondHero->tempOwner));
  277. requestActionASAP([=]()
  278. {
  279. float goalpriority1 = 0, goalpriority2 = 0;
  280. auto firstGoal = getGoal(firstHero);
  281. if(firstGoal->goalType == Goals::GATHER_ARMY)
  282. goalpriority1 = firstGoal->priority;
  283. auto secondGoal = getGoal(secondHero);
  284. if(secondGoal->goalType == Goals::GATHER_ARMY)
  285. goalpriority2 = secondGoal->priority;
  286. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  287. {
  288. this->pickBestCreatures(h1, h2);
  289. this->pickBestArtifacts(h1, h2);
  290. };
  291. //Do not attempt army or artifacts exchange if we visited ally player
  292. //Visits can still be useful if hero have skills like Scholar
  293. if(firstHero->tempOwner != secondHero->tempOwner)
  294. {
  295. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  296. }
  297. else if(goalpriority1 > goalpriority2)
  298. {
  299. transferFrom2to1(firstHero, secondHero);
  300. }
  301. else if(goalpriority1 < goalpriority2)
  302. {
  303. transferFrom2to1(secondHero, firstHero);
  304. }
  305. else //regular criteria
  306. {
  307. if(firstHero->getFightingStrength() > secondHero->getFightingStrength() && canGetArmy(firstHero, secondHero))
  308. transferFrom2to1(firstHero, secondHero);
  309. else if(canGetArmy(secondHero, firstHero))
  310. transferFrom2to1(secondHero, firstHero);
  311. }
  312. completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
  313. completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
  314. answerQuery(query, 0);
  315. });
  316. }
  317. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  318. {
  319. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  320. NET_EVENT_HANDLER;
  321. }
  322. void VCAI::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level)
  323. {
  324. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  325. NET_EVENT_HANDLER;
  326. }
  327. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  328. {
  329. LOG_TRACE(logAi);
  330. NET_EVENT_HANDLER;
  331. }
  332. void VCAI::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  333. {
  334. LOG_TRACE(logAi);
  335. NET_EVENT_HANDLER;
  336. }
  337. void VCAI::newObject(const CGObjectInstance * obj)
  338. {
  339. LOG_TRACE(logAi);
  340. NET_EVENT_HANDLER;
  341. if(obj->isVisitable())
  342. addVisitableObj(obj);
  343. ah->resetPaths();
  344. }
  345. //to prevent AI from accessing objects that got deleted while they became invisible (Cover of Darkness, enemy hero moved etc.) below code allows AI to know deletion of objects out of sight
  346. //see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
  347. void VCAI::objectRemoved(const CGObjectInstance * obj)
  348. {
  349. LOG_TRACE(logAi);
  350. NET_EVENT_HANDLER;
  351. vstd::erase_if_present(visitableObjs, obj);
  352. vstd::erase_if_present(alreadyVisited, obj);
  353. for(auto h : cb->getHeroesInfo())
  354. unreserveObject(h, obj);
  355. std::function<bool(const Goals::TSubgoal &)> checkRemovalValidity = [&](const Goals::TSubgoal & x) -> bool
  356. {
  357. if((x->goalType == Goals::VISIT_OBJ) && (x->objid == obj->id.getNum()))
  358. return true;
  359. else if(x->parent && checkRemovalValidity(x->parent)) //repeat this lambda check recursively on parent goal
  360. return true;
  361. else
  362. return false;
  363. };
  364. //clear VCAI / main loop caches
  365. vstd::erase_if(lockedHeroes, [&](const std::pair<HeroPtr, Goals::TSubgoal> & x) -> bool
  366. {
  367. return checkRemovalValidity(x.second);
  368. });
  369. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  370. {
  371. return checkRemovalValidity(x.first);
  372. });
  373. vstd::erase_if(basicGoals, checkRemovalValidity);
  374. vstd::erase_if(goalsToAdd, checkRemovalValidity);
  375. vstd::erase_if(goalsToRemove, checkRemovalValidity);
  376. for(auto goal : ultimateGoalsFromBasic)
  377. vstd::erase_if(goal.second, checkRemovalValidity);
  378. //clear resource manager goal cache
  379. ah->removeOutdatedObjectives(checkRemovalValidity);
  380. //TODO: Find better way to handle hero boat removal
  381. if(auto hero = dynamic_cast<const CGHeroInstance *>(obj))
  382. {
  383. if(hero->boat)
  384. {
  385. vstd::erase_if_present(visitableObjs, hero->boat);
  386. vstd::erase_if_present(alreadyVisited, hero->boat);
  387. for(auto h : cb->getHeroesInfo())
  388. unreserveObject(h, hero->boat);
  389. }
  390. }
  391. ah->resetPaths();
  392. //TODO
  393. //there are other places where CGObjectinstance ptrs are stored...
  394. //
  395. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  396. {
  397. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  398. }
  399. }
  400. void VCAI::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  401. {
  402. LOG_TRACE(logAi);
  403. NET_EVENT_HANDLER;
  404. requestActionASAP([=]()
  405. {
  406. makePossibleUpgrades(visitor);
  407. });
  408. }
  409. void VCAI::playerBonusChanged(const Bonus & bonus, bool gain)
  410. {
  411. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  412. NET_EVENT_HANDLER;
  413. }
  414. void VCAI::heroCreated(const CGHeroInstance * h)
  415. {
  416. LOG_TRACE(logAi);
  417. if(h->visitedTown)
  418. townVisitsThisWeek[HeroPtr(h)].insert(h->visitedTown);
  419. NET_EVENT_HANDLER;
  420. }
  421. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  422. {
  423. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  424. NET_EVENT_HANDLER;
  425. }
  426. void VCAI::showInfoDialog(const std::string & text, const std::vector<Component> & components, int soundID)
  427. {
  428. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  429. NET_EVENT_HANDLER;
  430. }
  431. void VCAI::requestRealized(PackageApplied * pa)
  432. {
  433. LOG_TRACE(logAi);
  434. NET_EVENT_HANDLER;
  435. if(status.haveTurn())
  436. {
  437. if(pa->packType == typeList.getTypeID<EndTurn>())
  438. {
  439. if(pa->result)
  440. status.madeTurn();
  441. }
  442. }
  443. if(pa->packType == typeList.getTypeID<QueryReply>())
  444. {
  445. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  446. }
  447. }
  448. void VCAI::receivedResource()
  449. {
  450. LOG_TRACE(logAi);
  451. NET_EVENT_HANDLER;
  452. }
  453. void VCAI::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor)
  454. {
  455. LOG_TRACE(logAi);
  456. NET_EVENT_HANDLER;
  457. }
  458. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  459. {
  460. LOG_TRACE(logAi);
  461. NET_EVENT_HANDLER;
  462. }
  463. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  464. {
  465. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  466. NET_EVENT_HANDLER;
  467. }
  468. void VCAI::battleResultsApplied()
  469. {
  470. LOG_TRACE(logAi);
  471. NET_EVENT_HANDLER;
  472. assert(status.getBattle() == ENDING_BATTLE);
  473. status.setBattle(NO_BATTLE);
  474. }
  475. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  476. {
  477. LOG_TRACE(logAi);
  478. NET_EVENT_HANDLER;
  479. if(sop->what == ObjProperty::OWNER)
  480. {
  481. if(myCb->getPlayerRelations(playerID, (PlayerColor)sop->val) == PlayerRelations::ENEMIES)
  482. {
  483. //we want to visit objects owned by oppponents
  484. auto obj = myCb->getObj(sop->id, false);
  485. if(obj)
  486. {
  487. addVisitableObj(obj); // TODO: Remove once save compatability broken. In past owned objects were removed from this set
  488. vstd::erase_if_present(alreadyVisited, obj);
  489. }
  490. }
  491. }
  492. }
  493. void VCAI::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  494. {
  495. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  496. NET_EVENT_HANDLER;
  497. if(town->getOwner() == playerID && what == 1) //built
  498. completeGoal(sptr(Goals::BuildThis(buildingID, town)));
  499. }
  500. void VCAI::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  501. {
  502. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  503. NET_EVENT_HANDLER;
  504. }
  505. void VCAI::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor)
  506. {
  507. LOG_TRACE(logAi);
  508. NET_EVENT_HANDLER;
  509. }
  510. void VCAI::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions)
  511. {
  512. //TODO: AI support for ViewXXX spell
  513. LOG_TRACE(logAi);
  514. NET_EVENT_HANDLER;
  515. }
  516. void VCAI::init(std::shared_ptr<CCallback> CB)
  517. {
  518. LOG_TRACE(logAi);
  519. myCb = CB;
  520. cbc = CB;
  521. ah->init(CB.get());
  522. NET_EVENT_HANDLER; //sets ah->rm->cb
  523. playerID = *myCb->getMyColor();
  524. myCb->waitTillRealize = true;
  525. myCb->unlockGsWhenWaiting = true;
  526. if(!fh)
  527. fh = new FuzzyHelper();
  528. retrieveVisitableObjs();
  529. }
  530. void VCAI::yourTurn()
  531. {
  532. LOG_TRACE(logAi);
  533. NET_EVENT_HANDLER;
  534. status.startedTurn();
  535. makingTurn = make_unique<boost::thread>(&VCAI::makeTurn, this);
  536. }
  537. void VCAI::heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  538. {
  539. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  540. NET_EVENT_HANDLER;
  541. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  542. requestActionASAP([=](){ answerQuery(queryID, 0); });
  543. }
  544. void VCAI::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  545. {
  546. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  547. NET_EVENT_HANDLER;
  548. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  549. requestActionASAP([=](){ answerQuery(queryID, 0); });
  550. }
  551. void VCAI::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel)
  552. {
  553. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  554. NET_EVENT_HANDLER;
  555. int sel = 0;
  556. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  557. % components.size() % text));
  558. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  559. sel = components.size();
  560. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  561. sel = 1;
  562. requestActionASAP([=]()
  563. {
  564. answerQuery(askID, sel);
  565. });
  566. }
  567. void VCAI::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  568. {
  569. // LOG_TRACE_PARAMS(logAi, "askID '%i', exits '%s'", askID % exits);
  570. NET_EVENT_HANDLER;
  571. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits")
  572. % exits.size()));
  573. int choosenExit = -1;
  574. if(impassable)
  575. {
  576. knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  577. }
  578. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.valid())
  579. {
  580. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  581. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  582. choosenExit = vstd::find_pos(exits, neededExit);
  583. }
  584. for(auto exit : exits)
  585. {
  586. if(status.channelProbing() && exit.first == destinationTeleport)
  587. {
  588. choosenExit = vstd::find_pos(exits, exit);
  589. break;
  590. }
  591. else
  592. {
  593. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  594. // So far this is the best option to handle decision about probing
  595. auto obj = cb->getObj(exit.first, false);
  596. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  597. {
  598. if(exit.first != destinationTeleport)
  599. teleportChannelProbingList.push_back(exit.first);
  600. }
  601. }
  602. }
  603. requestActionASAP([=]()
  604. {
  605. answerQuery(askID, choosenExit);
  606. });
  607. }
  608. void VCAI::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  609. {
  610. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  611. NET_EVENT_HANDLER;
  612. std::string s1 = up ? up->nodeName() : "NONE";
  613. std::string s2 = down ? down->nodeName() : "NONE";
  614. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  615. //you can't request action from action-response thread
  616. requestActionASAP([=]()
  617. {
  618. if(removableUnits)
  619. pickBestCreatures(down, up);
  620. answerQuery(queryID, 0);
  621. });
  622. }
  623. void VCAI::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  624. {
  625. NET_EVENT_HANDLER;
  626. status.addQuery(askID, "Map object select query");
  627. requestActionASAP([=](){ answerQuery(askID, 0); });
  628. //TODO: Town portal destination selection goes here
  629. }
  630. void VCAI::saveGame(BinarySerializer & h, const int version)
  631. {
  632. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  633. NET_EVENT_HANDLER;
  634. validateVisitableObjs();
  635. #if 0
  636. //disabled due to issue 2890
  637. registerGoals(h);
  638. #endif // 0
  639. CAdventureAI::saveGame(h, version);
  640. serializeInternal(h, version);
  641. }
  642. void VCAI::loadGame(BinaryDeserializer & h, const int version)
  643. {
  644. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  645. //NET_EVENT_HANDLER;
  646. #if 0
  647. //disabled due to issue 2890
  648. registerGoals(h);
  649. #endif // 0
  650. CAdventureAI::loadGame(h, version);
  651. serializeInternal(h, version);
  652. }
  653. void makePossibleUpgrades(const CArmedInstance * obj)
  654. {
  655. if(!obj)
  656. return;
  657. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  658. {
  659. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  660. {
  661. UpgradeInfo ui;
  662. cb->getUpgradeInfo(obj, SlotID(i), ui);
  663. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  664. {
  665. cb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  666. }
  667. }
  668. }
  669. }
  670. void VCAI::makeTurn()
  671. {
  672. MAKING_TURN;
  673. auto day = cb->getDate(Date::EDateType::DAY);
  674. logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.getStr(), day);
  675. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  676. setThreadName("VCAI::makeTurn");
  677. switch(cb->getDate(Date::DAY_OF_WEEK))
  678. {
  679. case 1:
  680. {
  681. townVisitsThisWeek.clear();
  682. std::vector<const CGObjectInstance *> objs;
  683. retrieveVisitableObjs(objs, true);
  684. for(const CGObjectInstance * obj : objs)
  685. {
  686. if(isWeeklyRevisitable(obj))
  687. {
  688. addVisitableObj(obj);
  689. vstd::erase_if_present(alreadyVisited, obj);
  690. }
  691. }
  692. break;
  693. }
  694. }
  695. markHeroAbleToExplore(primaryHero());
  696. visitedHeroes.clear();
  697. ai->ah->resetPaths();
  698. try
  699. {
  700. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  701. for (const CGTownInstance * t : cb->getTownsInfo())
  702. moveCreaturesToHero(t);
  703. mainLoop();
  704. /*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.
  705. 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().*/
  706. performTypicalActions();
  707. //for debug purpose
  708. for (auto h : cb->getHeroesInfo())
  709. {
  710. if (h->movement)
  711. logAi->warn("Hero %s has %d MP left", h->name, h->movement);
  712. }
  713. }
  714. catch (boost::thread_interrupted & e)
  715. {
  716. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  717. return;
  718. }
  719. catch (std::exception & e)
  720. {
  721. logAi->debug("Making turn thread has caught an exception: %s", e.what());
  722. }
  723. endTurn();
  724. }
  725. void VCAI::mainLoop()
  726. {
  727. std::vector<Goals::TSubgoal> elementarGoals; //no duplicates allowed (operator ==)
  728. basicGoals.clear();
  729. //get all potential and saved goals
  730. //TODO: not lose
  731. basicGoals.push_back(sptr(Goals::Win()));
  732. for (auto goalPair : lockedHeroes)
  733. {
  734. fh->setPriority(goalPair.second); //re-evaluate, as heroes moved in the meantime
  735. basicGoals.push_back(goalPair.second);
  736. }
  737. if (ah->hasTasksLeft())
  738. basicGoals.push_back(ah->whatToDo());
  739. for (auto quest : myCb->getMyQuests())
  740. {
  741. basicGoals.push_back(sptr(Goals::CompleteQuest(quest)));
  742. }
  743. basicGoals.push_back(sptr(Goals::Build()));
  744. invalidPathHeroes.clear();
  745. while (basicGoals.size())
  746. {
  747. vstd::removeDuplicates(basicGoals); //TODO: container which does this automagically without has would be nice
  748. goalsToAdd.clear();
  749. goalsToRemove.clear();
  750. elementarGoals.clear();
  751. ultimateGoalsFromBasic.clear();
  752. logAi->debug("Main loop: decomposing %i basic goals", basicGoals.size());
  753. for (auto basicGoal : basicGoals)
  754. {
  755. logAi->debug("Main loop: decomposing basic goal %s", basicGoal->name());
  756. auto goalToDecompose = basicGoal;
  757. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  758. int maxAbstractGoals = 10;
  759. while (!elementarGoal->isElementar && maxAbstractGoals)
  760. {
  761. try
  762. {
  763. elementarGoal = decomposeGoal(goalToDecompose);
  764. }
  765. catch (goalFulfilledException & e)
  766. {
  767. //it is impossible to continue some goals (like exploration, for example)
  768. //complete abstract goal for now, but maybe main goal finds another path
  769. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  770. completeGoal(e.goal); //put in goalsToRemove
  771. break;
  772. }
  773. catch(cannotFulfillGoalException & e)
  774. {
  775. //it is impossible to continue some goals (like exploration, for example)
  776. //complete abstract goal for now, but maybe main goal finds another path
  777. goalsToRemove.push_back(basicGoal);
  778. logAi->debug("Goal %s decomposition failed: %s", goalToDecompose->name(), e.what());
  779. break;
  780. }
  781. catch (std::exception & e) //decomposition failed, which means we can't decompose entire tree
  782. {
  783. goalsToRemove.push_back(basicGoal);
  784. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  785. break;
  786. }
  787. if (elementarGoal->isAbstract) //we can decompose it further
  788. {
  789. goalsToAdd.push_back(elementarGoal);
  790. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  791. goalToDecompose = elementarGoal;
  792. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  793. maxAbstractGoals--;
  794. }
  795. else if (elementarGoal->isElementar) //should be
  796. {
  797. logAi->debug("Found elementar goal %s", elementarGoal->name());
  798. elementarGoals.push_back(elementarGoal);
  799. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  800. break;
  801. }
  802. else //should never be here
  803. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  804. }
  805. }
  806. logAi->trace("Main loop: selecting best elementar goal");
  807. //now choose one elementar goal to realize
  808. Goals::TGoalVec possibleGoals(elementarGoals.begin(), elementarGoals.end()); //copy to vector
  809. Goals::TSubgoal goalToRealize = sptr(Goals::Invalid());
  810. while (possibleGoals.size())
  811. {
  812. //allow assign goals to heroes with 0 movement, but don't realize them
  813. //maybe there are beter ones left
  814. auto bestGoal = fh->chooseSolution(possibleGoals);
  815. if (bestGoal->hero) //lock this hero to fulfill goal
  816. {
  817. setGoal(bestGoal->hero, bestGoal);
  818. if (!bestGoal->hero->movement || vstd::contains(invalidPathHeroes, bestGoal->hero))
  819. {
  820. if (!vstd::erase_if_present(possibleGoals, bestGoal))
  821. {
  822. logAi->error("erase_if_preset failed? Something very wrong!");
  823. break;
  824. }
  825. continue; //chose next from the list
  826. }
  827. }
  828. goalToRealize = bestGoal; //we found our goal to execute
  829. break;
  830. }
  831. //realize best goal
  832. if (!goalToRealize->invalid())
  833. {
  834. logAi->debug("Trying to realize %s (value %2.3f)", goalToRealize->name(), goalToRealize->priority);
  835. try
  836. {
  837. boost::this_thread::interruption_point();
  838. goalToRealize->accept(this); //visitor pattern
  839. boost::this_thread::interruption_point();
  840. }
  841. catch (boost::thread_interrupted & e)
  842. {
  843. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  844. throw; //rethrow, we want to truly end this thread
  845. }
  846. catch (goalFulfilledException & e)
  847. {
  848. //the sub-goal was completed successfully
  849. completeGoal(e.goal);
  850. //local goal was also completed?
  851. completeGoal(goalToRealize);
  852. // remove abstract visit tile if we completed the elementar one
  853. vstd::erase_if_present(goalsToAdd, goalToRealize);
  854. }
  855. catch (std::exception & e)
  856. {
  857. logAi->debug("Failed to realize subgoal of type %s, I will stop.", goalToRealize->name());
  858. logAi->debug("The error message was: %s", e.what());
  859. //erase base goal if we failed to execute decomposed goal
  860. for (auto basicGoal : ultimateGoalsFromBasic[goalToRealize])
  861. goalsToRemove.push_back(basicGoal);
  862. // sometimes resource manager contains an elementar goal which is not able to execute anymore and just fails each turn.
  863. ai->ah->notifyGoalCompleted(goalToRealize);
  864. //we failed to realize best goal, but maybe others are still possible?
  865. }
  866. //remove goals we couldn't decompose
  867. for (auto goal : goalsToRemove)
  868. vstd::erase_if_present(basicGoals, goal);
  869. //add abstract goals
  870. boost::sort(goalsToAdd, [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  871. {
  872. return lhs->priority > rhs->priority; //highest priority at the beginning
  873. });
  874. //max number of goals = 10
  875. int i = 0;
  876. while (basicGoals.size() < 10 && goalsToAdd.size() > i)
  877. {
  878. if (!vstd::contains(basicGoals, goalsToAdd[i])) //don't add duplicates
  879. basicGoals.push_back(goalsToAdd[i]);
  880. i++;
  881. }
  882. }
  883. else //no elementar goals possible
  884. {
  885. logAi->debug("Goal decomposition exhausted");
  886. break;
  887. }
  888. }
  889. }
  890. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  891. {
  892. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->name % obj->getObjectName() % obj->pos.toString());
  893. switch(obj->ID)
  894. {
  895. case Obj::CREATURE_GENERATOR1:
  896. recruitCreatures(dynamic_cast<const CGDwelling *>(obj), h.get());
  897. checkHeroArmy(h);
  898. break;
  899. case Obj::TOWN:
  900. moveCreaturesToHero(dynamic_cast<const CGTownInstance *>(obj));
  901. if(h->visitedTown) //we are inside, not just attacking
  902. {
  903. townVisitsThisWeek[h].insert(h->visitedTown);
  904. if(!h->hasSpellbook() && ah->freeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  905. {
  906. if(h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  907. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  908. }
  909. }
  910. break;
  911. }
  912. completeGoal(sptr(Goals::VisitObj(obj->id.getNum()).sethero(h)));
  913. }
  914. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  915. {
  916. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  917. {
  918. pickBestCreatures(t->visitingHero, t);
  919. }
  920. }
  921. bool VCAI::canGetArmy(const CGHeroInstance * army, const CGHeroInstance * source)
  922. {
  923. //TODO: merge with pickBestCreatures
  924. //if (ai->primaryHero().h == source)
  925. if(army->tempOwner != source->tempOwner)
  926. {
  927. logAi->error("Why are we even considering exchange between heroes from different players?");
  928. return false;
  929. }
  930. const CArmedInstance * armies[] = {army, source};
  931. //we calculate total strength for each creature type available in armies
  932. std::map<const CCreature *, int> creToPower;
  933. for(auto armyPtr : armies)
  934. {
  935. for(auto & i : armyPtr->Slots())
  936. {
  937. //TODO: allow splitting stacks?
  938. creToPower[i.second->type] += i.second->getPower();
  939. }
  940. }
  941. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  942. int armySize = creToPower.size();
  943. armySize = std::min((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  944. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  945. for(int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  946. {
  947. typedef const std::pair<const CCreature *, int> & CrePowerPair;
  948. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  949. {
  950. return lhs.second < rhs.second;
  951. });
  952. bestArmy.push_back(creIt->first);
  953. creToPower.erase(creIt);
  954. if(creToPower.empty())
  955. break;
  956. }
  957. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  958. for(int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  959. {
  960. for(auto armyPtr : armies)
  961. {
  962. for(int j = 0; j < GameConstants::ARMY_SIZE; j++)
  963. {
  964. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && armyPtr != army) //it's a searched creature not in dst ARMY
  965. {
  966. //FIXME: line below is useless when simulating exchange between two non-singular armies
  967. if(!(armyPtr->needsLastStack() && armyPtr->stacksCount() == 1)) //can't take away last creature
  968. return true; //at least one exchange will be performed
  969. else
  970. return false; //no further exchange possible
  971. }
  972. }
  973. }
  974. }
  975. return false;
  976. }
  977. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  978. {
  979. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  980. const CArmedInstance * armies[] = {army, source};
  981. //we calculate total strength for each creature type available in armies
  982. std::map<const CCreature *, int> creToPower;
  983. for(auto armyPtr : armies)
  984. {
  985. for(auto & i : armyPtr->Slots())
  986. {
  987. //TODO: allow splitting stacks?
  988. creToPower[i.second->type] += i.second->getPower();
  989. }
  990. }
  991. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  992. int armySize = creToPower.size();
  993. armySize = std::min((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  994. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  995. for(int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  996. {
  997. typedef const std::pair<const CCreature *, int> & CrePowerPair;
  998. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  999. {
  1000. return lhs.second < rhs.second;
  1001. });
  1002. bestArmy.push_back(creIt->first);
  1003. creToPower.erase(creIt);
  1004. if(creToPower.empty())
  1005. break;
  1006. }
  1007. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  1008. for(int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  1009. {
  1010. for(auto armyPtr : armies)
  1011. {
  1012. for(int j = 0; j < GameConstants::ARMY_SIZE; j++)
  1013. {
  1014. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst SLOT
  1015. {
  1016. if(!(armyPtr->needsLastStack() && armyPtr->stacksCount() == 1)) //can't take away last creature
  1017. cb->mergeOrSwapStacks(armyPtr, army, SlotID(j), SlotID(i));
  1018. }
  1019. }
  1020. }
  1021. }
  1022. //TODO - having now strongest possible army, we may want to think about arranging stacks
  1023. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  1024. if(hero)
  1025. checkHeroArmy(hero);
  1026. }
  1027. void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  1028. {
  1029. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  1030. {
  1031. bool changeMade = false;
  1032. do
  1033. {
  1034. changeMade = false;
  1035. //we collect gear always in same order
  1036. std::vector<ArtifactLocation> allArtifacts;
  1037. if(giveStuffToFirstHero)
  1038. {
  1039. for(auto p : h->artifactsWorn)
  1040. {
  1041. if(p.second.artifact)
  1042. allArtifacts.push_back(ArtifactLocation(h, p.first));
  1043. }
  1044. }
  1045. for(auto slot : h->artifactsInBackpack)
  1046. allArtifacts.push_back(ArtifactLocation(h, h->getArtPos(slot.artifact)));
  1047. if(otherh)
  1048. {
  1049. for(auto p : otherh->artifactsWorn)
  1050. {
  1051. if(p.second.artifact)
  1052. allArtifacts.push_back(ArtifactLocation(otherh, p.first));
  1053. }
  1054. for(auto slot : otherh->artifactsInBackpack)
  1055. allArtifacts.push_back(ArtifactLocation(otherh, otherh->getArtPos(slot.artifact)));
  1056. }
  1057. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  1058. const CGHeroInstance * target = nullptr;
  1059. if(giveStuffToFirstHero || !otherh)
  1060. target = h;
  1061. else
  1062. target = otherh;
  1063. for(auto location : allArtifacts)
  1064. {
  1065. if(location.relatedObj() == target && location.slot < ArtifactPosition::AFTER_LAST)
  1066. continue; //don't reequip artifact we already wear
  1067. if(location.slot == ArtifactPosition::MACH4) // don't attempt to move catapult
  1068. continue;
  1069. auto s = location.getSlot();
  1070. if(!s || s->locked) //we can't move locks
  1071. continue;
  1072. auto artifact = s->artifact;
  1073. if(!artifact)
  1074. continue;
  1075. //FIXME: why are the above possible to be null?
  1076. bool emptySlotFound = false;
  1077. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  1078. {
  1079. ArtifactLocation destLocation(target, slot);
  1080. if(target->isPositionFree(slot) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  1081. {
  1082. cb->swapArtifacts(location, destLocation); //just put into empty slot
  1083. emptySlotFound = true;
  1084. changeMade = true;
  1085. break;
  1086. }
  1087. }
  1088. if(!emptySlotFound) //try to put that atifact in already occupied slot
  1089. {
  1090. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  1091. {
  1092. auto otherSlot = target->getSlot(slot);
  1093. if(otherSlot && otherSlot->artifact) //we need to exchange artifact for better one
  1094. {
  1095. ArtifactLocation destLocation(target, slot);
  1096. //if that artifact is better than what we have, pick it
  1097. if(compareArtifacts(artifact, otherSlot->artifact) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  1098. {
  1099. cb->swapArtifacts(location, ArtifactLocation(target, target->getArtPos(otherSlot->artifact)));
  1100. changeMade = true;
  1101. break;
  1102. }
  1103. }
  1104. }
  1105. }
  1106. if(changeMade)
  1107. break; //start evaluating artifacts from scratch
  1108. }
  1109. }
  1110. while(changeMade);
  1111. };
  1112. equipBest(h, other, true);
  1113. if(other)
  1114. equipBest(h, other, false);
  1115. }
  1116. void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  1117. {
  1118. //now used only for visited dwellings / towns, not BuyArmy goal
  1119. for(int i = 0; i < d->creatures.size(); i++)
  1120. {
  1121. if(!d->creatures[i].second.size())
  1122. continue;
  1123. int count = d->creatures[i].first;
  1124. CreatureID creID = d->creatures[i].second.back();
  1125. vstd::amin(count, ah->freeResources() / VLC->creh->creatures[creID]->cost);
  1126. if(count > 0)
  1127. cb->recruitCreatures(d, recruiter, creID, count, i);
  1128. }
  1129. }
  1130. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, boost::optional<uint32_t> movementCostLimit)
  1131. {
  1132. int3 op = obj->visitablePos();
  1133. auto paths = ah->getPathsToTile(h, op);
  1134. for(auto path : paths)
  1135. {
  1136. if(movementCostLimit && movementCostLimit.get() < path.movementCost())
  1137. return false;
  1138. if(ai->isGoodForVisit(obj, h, path))
  1139. return true;
  1140. }
  1141. return false;
  1142. }
  1143. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const
  1144. {
  1145. const int3 pos = obj->visitablePos();
  1146. const int3 targetPos = path.firstTileToGet();
  1147. if (!targetPos.valid())
  1148. return false;
  1149. if (!isTileNotReserved(h.get(), targetPos))
  1150. return false;
  1151. if (obj->wasVisited(playerID))
  1152. return false;
  1153. if (cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
  1154. return false; // Otherwise we flag or get weekly resources / creatures
  1155. if (!isSafeToVisit(h, pos))
  1156. return false;
  1157. if (!shouldVisit(h, obj))
  1158. return false;
  1159. if (vstd::contains(alreadyVisited, obj))
  1160. return false;
  1161. if (vstd::contains(reservedObjs, obj))
  1162. return false;
  1163. // TODO: looks extra if we already have AIPath
  1164. //if (!isAccessibleForHero(targetPos, h))
  1165. // return false;
  1166. const CGObjectInstance * topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
  1167. //we don't try visiting object on which allied or owned hero stands
  1168. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1169. if (topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  1170. return false;
  1171. else
  1172. return true; //all of the following is met
  1173. }
  1174. bool VCAI::isTileNotReserved(const CGHeroInstance * h, int3 t) const
  1175. {
  1176. if(t.valid())
  1177. {
  1178. auto obj = cb->getTopObj(t);
  1179. if(obj && vstd::contains(ai->reservedObjs, obj)
  1180. && vstd::contains(reservedHeroesMap, h)
  1181. && !vstd::contains(reservedHeroesMap.at(h), obj))
  1182. return false; //do not capture object reserved by another hero
  1183. else
  1184. return true;
  1185. }
  1186. else
  1187. {
  1188. return false;
  1189. }
  1190. }
  1191. bool VCAI::canRecruitAnyHero(const CGTownInstance * t) const
  1192. {
  1193. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  1194. if(!t)
  1195. t = findTownWithTavern();
  1196. if(!t)
  1197. return false;
  1198. if(cb->getResourceAmount(Res::GOLD) < GameConstants::HERO_GOLD_COST) //TODO: use ResourceManager
  1199. return false;
  1200. if(cb->getHeroesInfo().size() >= ALLOWED_ROAMING_HEROES)
  1201. return false;
  1202. if(!cb->getAvailableHeroes(t).size())
  1203. return false;
  1204. return true;
  1205. }
  1206. void VCAI::wander(HeroPtr h)
  1207. {
  1208. auto visitTownIfAny = [this](HeroPtr h) -> bool
  1209. {
  1210. if (h->visitedTown)
  1211. {
  1212. townVisitsThisWeek[h].insert(h->visitedTown);
  1213. buildArmyIn(h->visitedTown);
  1214. return true;
  1215. }
  1216. return false;
  1217. };
  1218. //unclaim objects that are now dangerous for us
  1219. auto reservedObjsSetCopy = reservedHeroesMap[h];
  1220. for(auto obj : reservedObjsSetCopy)
  1221. {
  1222. if(!isSafeToVisit(h, obj->visitablePos()))
  1223. unreserveObject(h, obj);
  1224. }
  1225. TimeCheck tc("looking for wander destination");
  1226. while(h->movement)
  1227. {
  1228. validateVisitableObjs();
  1229. std::vector<ObjectIdRef> dests;
  1230. //also visit our reserved objects - but they are not prioritized to avoid running back and forth
  1231. vstd::copy_if(reservedHeroesMap[h], std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1232. {
  1233. return ah->getPathsToTile(h, obj->visitablePos()).size();
  1234. });
  1235. int pass = 0;
  1236. std::vector<boost::optional<ui32>> distanceLimits = {
  1237. h->movement,
  1238. h->movement + h->maxMovePoints(true),
  1239. boost::none
  1240. };
  1241. while(!dests.size() && pass < distanceLimits.size())
  1242. {
  1243. boost::optional<ui32> distanceLimit = distanceLimits[pass];
  1244. logAi->debug("Looking for wander destination pass=%i, distance limit=%i", pass, distanceLimit.get_value_or(-1));
  1245. vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1246. {
  1247. return isGoodForVisit(obj, h, distanceLimit);
  1248. });
  1249. pass++;
  1250. }
  1251. if(!dests.size())
  1252. {
  1253. logAi->debug("Looking for town destination");
  1254. if(cb->getVisitableObjs(h->visitablePos()).size() > 1)
  1255. moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
  1256. auto compareReinforcements = [h](const CGTownInstance * lhs, const CGTownInstance * rhs) -> bool
  1257. {
  1258. const CGHeroInstance * hptr = h.get();
  1259. auto r1 = howManyReinforcementsCanGet(hptr, lhs),
  1260. r2 = howManyReinforcementsCanGet(hptr, rhs);
  1261. if (r1 != r2)
  1262. return r1 < r2;
  1263. else
  1264. return howManyReinforcementsCanBuy(hptr, lhs) < howManyReinforcementsCanBuy(hptr, rhs);
  1265. };
  1266. std::vector<const CGTownInstance *> townsReachable;
  1267. std::vector<const CGTownInstance *> townsNotReachable;
  1268. for(const CGTownInstance * t : cb->getTownsInfo())
  1269. {
  1270. if(!t->visitingHero && !vstd::contains(townVisitsThisWeek[h], t))
  1271. {
  1272. if(isAccessibleForHero(t->visitablePos(), h))
  1273. townsReachable.push_back(t);
  1274. else
  1275. townsNotReachable.push_back(t);
  1276. }
  1277. }
  1278. if(townsReachable.size()) //travel to town with largest garrison, or empty - better than nothing
  1279. {
  1280. dests.push_back(*boost::max_element(townsReachable, compareReinforcements));
  1281. }
  1282. else if(townsNotReachable.size())
  1283. {
  1284. //TODO pick the truly best
  1285. const CGTownInstance * t = *boost::max_element(townsNotReachable, compareReinforcements);
  1286. 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());
  1287. int3 pos1 = h->pos;
  1288. striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h))); //TODO: drop "strive", add to mainLoop
  1289. //if out hero is stuck, we may need to request another hero to clear the way we see
  1290. if(pos1 == h->pos && h == primaryHero()) //hero can't move
  1291. {
  1292. if(canRecruitAnyHero(t))
  1293. recruitHero(t);
  1294. }
  1295. break;
  1296. }
  1297. else if(cb->getResourceAmount(Res::GOLD) >= GameConstants::HERO_GOLD_COST)
  1298. {
  1299. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1300. vstd::erase_if(towns, [](const CGTownInstance * t) -> bool
  1301. {
  1302. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1303. {
  1304. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1305. return true;
  1306. }
  1307. return false;
  1308. });
  1309. if (towns.size())
  1310. {
  1311. recruitHero(*boost::max_element(towns, compareArmyStrength));
  1312. }
  1313. break;
  1314. }
  1315. else
  1316. {
  1317. logAi->debug("Nowhere more to go...");
  1318. break;
  1319. }
  1320. }
  1321. //end of objs empty
  1322. if(dests.size()) //performance improvement
  1323. {
  1324. Goals::TGoalVec targetObjectGoals;
  1325. for(auto destination : dests)
  1326. {
  1327. vstd::concatenate(targetObjectGoals, ah->howToVisitObj(h, destination, false));
  1328. }
  1329. auto bestObjectGoal = fh->chooseSolution(targetObjectGoals);
  1330. //wander should not cause heroes to be reserved - they are always considered free
  1331. if(bestObjectGoal->goalType == Goals::VISIT_OBJ)
  1332. {
  1333. auto chosenObject = cb->getObjInstance(ObjectInstanceID(bestObjectGoal->objid));
  1334. if(chosenObject != nullptr)
  1335. logAi->debug("Of all %d destinations, object %s at pos=%s seems nice", dests.size(), chosenObject->getObjectName(), chosenObject->pos.toString());
  1336. }
  1337. else
  1338. logAi->debug("Trying to realize goal of type %s as part of wandering.", bestObjectGoal->name());
  1339. try
  1340. {
  1341. decomposeGoal(bestObjectGoal)->accept(this);
  1342. }
  1343. catch(const goalFulfilledException & e)
  1344. {
  1345. if(e.goal->goalType == Goals::EGoals::VISIT_TILE || e.goal->goalType == Goals::EGoals::VISIT_OBJ)
  1346. continue;
  1347. throw e;
  1348. }
  1349. visitTownIfAny(h);
  1350. }
  1351. }
  1352. visitTownIfAny(h); //in case hero is just sitting in town
  1353. }
  1354. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1355. {
  1356. if(goal->invalid())
  1357. {
  1358. vstd::erase_if_present(lockedHeroes, h);
  1359. }
  1360. else
  1361. {
  1362. lockedHeroes[h] = goal;
  1363. goal->setisElementar(false); //Force always evaluate goals before realizing
  1364. }
  1365. }
  1366. void VCAI::evaluateGoal(HeroPtr h)
  1367. {
  1368. if(vstd::contains(lockedHeroes, h))
  1369. fh->setPriority(lockedHeroes[h]);
  1370. }
  1371. void VCAI::completeGoal(Goals::TSubgoal goal)
  1372. {
  1373. if (goal->goalType == Goals::WIN) //we can never complete this goal - unless we already won
  1374. return;
  1375. logAi->debug("Completing goal: %s", goal->name());
  1376. //notify Managers
  1377. ah->notifyGoalCompleted(goal);
  1378. //notify mainLoop()
  1379. goalsToRemove.push_back(goal); //will be removed from mainLoop() goals
  1380. for (auto basicGoal : basicGoals) //we could luckily fulfill any of our goals
  1381. {
  1382. if (basicGoal->fulfillsMe(goal))
  1383. goalsToRemove.push_back(basicGoal);
  1384. }
  1385. //unreserve heroes
  1386. if(const CGHeroInstance * h = goal->hero.get(true))
  1387. {
  1388. auto it = lockedHeroes.find(h);
  1389. if(it != lockedHeroes.end())
  1390. {
  1391. if(it->second == goal || it->second->fulfillsMe(goal)) //FIXME this is overspecified, fulfillsMe shoudl be complete
  1392. {
  1393. logAi->debug(goal->completeMessage());
  1394. lockedHeroes.erase(it); //goal fulfilled, free hero
  1395. }
  1396. }
  1397. }
  1398. else //complete goal for all heroes maybe?
  1399. {
  1400. vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
  1401. {
  1402. if(p.second == goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1403. {
  1404. logAi->debug(p.second->completeMessage());
  1405. return true;
  1406. }
  1407. return false;
  1408. });
  1409. }
  1410. }
  1411. void VCAI::battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side)
  1412. {
  1413. NET_EVENT_HANDLER;
  1414. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1415. status.setBattle(ONGOING_BATTLE);
  1416. 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
  1417. 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());
  1418. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1419. }
  1420. void VCAI::battleEnd(const BattleResult * br)
  1421. {
  1422. NET_EVENT_HANDLER;
  1423. assert(status.getBattle() == ONGOING_BATTLE);
  1424. status.setBattle(ENDING_BATTLE);
  1425. bool won = br->winner == myCb->battleGetMySide();
  1426. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.getStr(), (won ? "won" : "lost"), battlename);
  1427. battlename.clear();
  1428. CAdventureAI::battleEnd(br);
  1429. }
  1430. void VCAI::waitTillFree()
  1431. {
  1432. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  1433. status.waitTillFree();
  1434. }
  1435. void VCAI::markObjectVisited(const CGObjectInstance * obj)
  1436. {
  1437. if(!obj)
  1438. return;
  1439. if(dynamic_cast<const CGVisitableOPH *>(obj)) //we may want to visit it with another hero
  1440. return;
  1441. if(dynamic_cast<const CGBonusingObject *>(obj)) //or another time
  1442. return;
  1443. if(obj->ID == Obj::MONSTER)
  1444. return;
  1445. alreadyVisited.insert(obj);
  1446. }
  1447. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance * obj)
  1448. {
  1449. reservedObjs.insert(obj);
  1450. reservedHeroesMap[h].insert(obj);
  1451. logAi->debug("reserved object id=%d; address=%p; name=%s", obj->id, obj, obj->getObjectName());
  1452. }
  1453. void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance * obj)
  1454. {
  1455. vstd::erase_if_present(reservedObjs, obj); //unreserve objects
  1456. vstd::erase_if_present(reservedHeroesMap[h], obj);
  1457. }
  1458. void VCAI::markHeroUnableToExplore(HeroPtr h)
  1459. {
  1460. heroesUnableToExplore.insert(h);
  1461. }
  1462. void VCAI::markHeroAbleToExplore(HeroPtr h)
  1463. {
  1464. vstd::erase_if_present(heroesUnableToExplore, h);
  1465. }
  1466. bool VCAI::isAbleToExplore(HeroPtr h)
  1467. {
  1468. return !vstd::contains(heroesUnableToExplore, h);
  1469. }
  1470. void VCAI::clearPathsInfo()
  1471. {
  1472. heroesUnableToExplore.clear();
  1473. ah->resetPaths();
  1474. }
  1475. void VCAI::validateVisitableObjs()
  1476. {
  1477. std::string errorMsg;
  1478. auto shouldBeErased = [&](const CGObjectInstance * obj) -> bool
  1479. {
  1480. if(obj)
  1481. return !cb->getObj(obj->id, false); // no verbose output needed as we check object visibility
  1482. else
  1483. return true;
  1484. };
  1485. //errorMsg is captured by ref so lambda will take the new text
  1486. errorMsg = " shouldn't be on the visitable objects list!";
  1487. vstd::erase_if(visitableObjs, shouldBeErased);
  1488. //FIXME: how comes our own heroes become inaccessible?
  1489. vstd::erase_if(reservedHeroesMap, [](std::pair<HeroPtr, std::set<const CGObjectInstance *>> hp) -> bool
  1490. {
  1491. return !hp.first.get(true);
  1492. });
  1493. for(auto & p : reservedHeroesMap)
  1494. {
  1495. errorMsg = " shouldn't be on list for hero " + p.first->name + "!";
  1496. vstd::erase_if(p.second, shouldBeErased);
  1497. }
  1498. errorMsg = " shouldn't be on the reserved objs list!";
  1499. vstd::erase_if(reservedObjs, shouldBeErased);
  1500. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1501. errorMsg = " shouldn't be on the already visited objs list!";
  1502. vstd::erase_if(alreadyVisited, shouldBeErased);
  1503. }
  1504. void VCAI::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
  1505. {
  1506. foreach_tile_pos([&](const int3 & pos)
  1507. {
  1508. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1509. {
  1510. if(includeOwned || obj->tempOwner != playerID)
  1511. out.push_back(obj);
  1512. }
  1513. });
  1514. }
  1515. void VCAI::retrieveVisitableObjs()
  1516. {
  1517. foreach_tile_pos([&](const int3 & pos)
  1518. {
  1519. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1520. {
  1521. if(obj->tempOwner != playerID)
  1522. addVisitableObj(obj);
  1523. }
  1524. });
  1525. }
  1526. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1527. {
  1528. std::vector<const CGObjectInstance *> ret;
  1529. for(const CGObjectInstance * obj : visitableObjs)
  1530. {
  1531. if(obj->tempOwner == playerID)
  1532. ret.push_back(obj);
  1533. }
  1534. return ret;
  1535. }
  1536. void VCAI::addVisitableObj(const CGObjectInstance * obj)
  1537. {
  1538. visitableObjs.insert(obj);
  1539. helperObjInfo[obj] = ObjInfo(obj);
  1540. // All teleport objects seen automatically assigned to appropriate channels
  1541. auto teleportObj = dynamic_cast<const CGTeleport *>(obj);
  1542. if(teleportObj)
  1543. CGTeleport::addToChannel(knownTeleportChannels, teleportObj);
  1544. }
  1545. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1546. {
  1547. for(const CGObjectInstance * obj : ai->visitableObjs)
  1548. {
  1549. if(obj->ID == Obj::ARTIFACT && obj->subID == aid)
  1550. return obj;
  1551. }
  1552. return nullptr;
  1553. //TODO what if more than one artifact is available? return them all or some slection criteria
  1554. }
  1555. bool VCAI::isAccessible(const int3 & pos) const
  1556. {
  1557. //TODO precalculate for speed
  1558. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1559. {
  1560. if(isAccessibleForHero(pos, h))
  1561. return true;
  1562. }
  1563. return false;
  1564. }
  1565. HeroPtr VCAI::getHeroWithGrail() const
  1566. {
  1567. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1568. {
  1569. if(h->hasArt(2)) //grail
  1570. return h;
  1571. }
  1572. return nullptr;
  1573. }
  1574. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate)
  1575. {
  1576. //TODO smarter definition of unvisited
  1577. for(const CGObjectInstance * obj : visitableObjs)
  1578. {
  1579. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1580. return obj;
  1581. }
  1582. return nullptr;
  1583. }
  1584. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies) const
  1585. {
  1586. // Don't visit tile occupied by allied hero
  1587. if(!includeAllies)
  1588. {
  1589. for(auto obj : cb->getVisitableObjs(pos))
  1590. {
  1591. if(obj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES)
  1592. {
  1593. if(obj != h.get())
  1594. return false;
  1595. }
  1596. }
  1597. }
  1598. return cb->getPathsInfo(h.get())->getPathInfo(pos)->reachable();
  1599. }
  1600. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1601. {
  1602. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  1603. auto afterMovementCheck = [&]() -> void
  1604. {
  1605. waitTillFree(); //movement may cause battle or blocking dialog
  1606. if(!h)
  1607. {
  1608. lostHero(h);
  1609. teleportChannelProbingList.clear();
  1610. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  1611. status.setChannelProbing(false);
  1612. throw cannotFulfillGoalException("Hero was lost!");
  1613. }
  1614. };
  1615. logAi->debug("Moving hero %s to tile %s", h->name, dst.toString());
  1616. int3 startHpos = h->visitablePos();
  1617. bool ret = false;
  1618. if(startHpos == dst)
  1619. {
  1620. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1621. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1622. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1623. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  1624. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1625. ret = true;
  1626. }
  1627. else
  1628. {
  1629. CGPath path;
  1630. cb->getPathsInfo(h.get())->getPath(path, dst);
  1631. if(path.nodes.empty())
  1632. {
  1633. logAi->error("Hero %s cannot reach %s.", h->name, dst.toString());
  1634. throw goalFulfilledException(sptr(Goals::VisitTile(dst).sethero(h)));
  1635. }
  1636. int i = path.nodes.size() - 1;
  1637. auto getObj = [&](int3 coord, bool ignoreHero)
  1638. {
  1639. auto tile = cb->getTile(coord, false);
  1640. assert(tile);
  1641. return tile->topVisitableObj(ignoreHero);
  1642. //return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
  1643. };
  1644. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  1645. {
  1646. if(action != CGPathNode::TELEPORT_NORMAL && action != CGPathNode::TELEPORT_BLOCKING_VISIT)
  1647. {
  1648. if(action != CGPathNode::TELEPORT_BATTLE)
  1649. {
  1650. return false;
  1651. }
  1652. }
  1653. return true;
  1654. };
  1655. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1656. {
  1657. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1658. return nextObjectTop;
  1659. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1660. {
  1661. if(CGTeleport::isConnected(currentObject, nextObject))
  1662. return nextObject;
  1663. }
  1664. return nullptr;
  1665. };
  1666. auto doMovement = [&](int3 dst, bool transit)
  1667. {
  1668. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true), transit);
  1669. };
  1670. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1671. {
  1672. destinationTeleport = exitId;
  1673. if(exitPos.valid())
  1674. destinationTeleportPos = CGHeroInstance::convertPosition(exitPos, true);
  1675. cb->moveHero(*h, h->pos);
  1676. destinationTeleport = ObjectInstanceID();
  1677. destinationTeleportPos = int3(-1);
  1678. afterMovementCheck();
  1679. };
  1680. auto doChannelProbing = [&]() -> void
  1681. {
  1682. auto currentPos = CGHeroInstance::convertPosition(h->pos, false);
  1683. auto currentExit = getObj(currentPos, true)->id;
  1684. status.setChannelProbing(true);
  1685. for(auto exit : teleportChannelProbingList)
  1686. doTeleportMovement(exit, int3(-1));
  1687. teleportChannelProbingList.clear();
  1688. status.setChannelProbing(false);
  1689. doTeleportMovement(currentExit, currentPos);
  1690. };
  1691. for(; i > 0; i--)
  1692. {
  1693. int3 currentCoord = path.nodes[i].coord;
  1694. int3 nextCoord = path.nodes[i - 1].coord;
  1695. auto currentObject = getObj(currentCoord, currentCoord == CGHeroInstance::convertPosition(h->pos, false));
  1696. auto nextObjectTop = getObj(nextCoord, false);
  1697. auto nextObject = getObj(nextCoord, true);
  1698. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1699. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1700. {
  1701. //we use special login if hero standing on teleporter it's mean we need
  1702. doTeleportMovement(destTeleportObj->id, nextCoord);
  1703. if(teleportChannelProbingList.size())
  1704. doChannelProbing();
  1705. markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1706. continue;
  1707. }
  1708. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1709. if(path.nodes[i - 1].turns)
  1710. {
  1711. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1712. break;
  1713. }
  1714. int3 endpos = path.nodes[i - 1].coord;
  1715. if(endpos == h->visitablePos())
  1716. continue;
  1717. bool isConnected = false;
  1718. bool isNextObjectTeleport = false;
  1719. // Check there is node after next one; otherwise transit is pointless
  1720. if(i - 2 >= 0)
  1721. {
  1722. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1723. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1724. }
  1725. if(isConnected || isNextObjectTeleport)
  1726. {
  1727. // Hero should be able to go through object if it's allow transit
  1728. doMovement(endpos, true);
  1729. }
  1730. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1731. {
  1732. doMovement(endpos, true);
  1733. }
  1734. else
  1735. {
  1736. doMovement(endpos, false);
  1737. }
  1738. afterMovementCheck();
  1739. if(teleportChannelProbingList.size())
  1740. doChannelProbing();
  1741. }
  1742. if(path.nodes[0].action == CGPathNode::BLOCKING_VISIT)
  1743. {
  1744. ret = h && i == 0; // when we take resource we do not reach its position. We even might not move
  1745. }
  1746. }
  1747. if(h)
  1748. {
  1749. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1750. {
  1751. if(visitedObject != *h)
  1752. performObjectInteraction(visitedObject, h);
  1753. }
  1754. }
  1755. if(h) //we could have lost hero after last move
  1756. {
  1757. completeGoal(sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
  1758. completeGoal(sptr(Goals::ClearWayTo(dst).sethero(h)));
  1759. ret = ret || (dst == h->visitablePos());
  1760. if(!ret) //reserve object we are heading towards
  1761. {
  1762. auto obj = vstd::frontOrNull(cb->getVisitableObjs(dst));
  1763. if(obj && obj != *h)
  1764. reserveObject(h, obj);
  1765. }
  1766. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1767. {
  1768. vstd::erase_if_present(lockedHeroes, h); //hero seemingly is confused or has only 95mp which is not enough to move
  1769. invalidPathHeroes.insert(h);
  1770. throw cannotFulfillGoalException("Invalid path found!");
  1771. }
  1772. evaluateGoal(h); //new hero position means new game situation
  1773. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->name, startHpos.toString(), h->visitablePos().toString(), ret);
  1774. }
  1775. return ret;
  1776. }
  1777. void VCAI::buildStructure(const CGTownInstance * t, BuildingID building)
  1778. {
  1779. auto name = t->town->buildings.at(building)->Name();
  1780. logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->name, t->pos.toString());
  1781. cb->buildBuilding(t, building); //just do this;
  1782. }
  1783. void VCAI::tryRealize(Goals::Explore & g)
  1784. {
  1785. throw cannotFulfillGoalException("EXPLORE is not an elementar goal!");
  1786. }
  1787. void VCAI::tryRealize(Goals::RecruitHero & g)
  1788. {
  1789. if(const CGTownInstance * t = findTownWithTavern())
  1790. {
  1791. recruitHero(t, true);
  1792. //TODO try to free way to blocked town
  1793. //TODO: adventure map tavern or prison?
  1794. }
  1795. else
  1796. {
  1797. throw cannotFulfillGoalException("No town to recruit hero!");
  1798. }
  1799. }
  1800. void VCAI::tryRealize(Goals::VisitTile & g)
  1801. {
  1802. if(!g.hero->movement)
  1803. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1804. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1805. {
  1806. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->name, g.tile.toString());
  1807. throw goalFulfilledException(sptr(g));
  1808. }
  1809. if(ai->moveHeroToTile(g.tile, g.hero.get()))
  1810. {
  1811. throw goalFulfilledException(sptr(g));
  1812. }
  1813. }
  1814. void VCAI::tryRealize(Goals::VisitObj & g)
  1815. {
  1816. auto position = g.tile;
  1817. if(!g.hero->movement)
  1818. throw cannotFulfillGoalException("Cannot visit object: hero is out of MPs!");
  1819. if(position == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1820. {
  1821. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->name, g.tile.toString());
  1822. throw goalFulfilledException(sptr(g));
  1823. }
  1824. if(ai->moveHeroToTile(position, g.hero.get()))
  1825. {
  1826. throw goalFulfilledException(sptr(g));
  1827. }
  1828. }
  1829. void VCAI::tryRealize(Goals::VisitHero & g)
  1830. {
  1831. if(!g.hero->movement)
  1832. throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
  1833. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
  1834. if(obj)
  1835. {
  1836. if(ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
  1837. {
  1838. throw goalFulfilledException(sptr(g));
  1839. }
  1840. }
  1841. else
  1842. {
  1843. throw cannotFulfillGoalException("Cannot visit hero: object not found!");
  1844. }
  1845. }
  1846. void VCAI::tryRealize(Goals::BuildThis & g)
  1847. {
  1848. auto b = BuildingID(g.bid);
  1849. auto t = g.town;
  1850. if (t)
  1851. {
  1852. if (cb->canBuildStructure(t, b) == EBuildingState::ALLOWED)
  1853. {
  1854. logAi->debug("Player %d will build %s in town of %s at %s",
  1855. playerID, t->town->buildings.at(b)->Name(), t->name, t->pos.toString());
  1856. cb->buildBuilding(t, b);
  1857. throw goalFulfilledException(sptr(g));
  1858. }
  1859. }
  1860. throw cannotFulfillGoalException("Cannot build a given structure!");
  1861. }
  1862. void VCAI::tryRealize(Goals::DigAtTile & g)
  1863. {
  1864. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1865. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1866. {
  1867. cb->dig(g.hero.get());
  1868. completeGoal(sptr(g)); // finished digging
  1869. }
  1870. else
  1871. {
  1872. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1873. throw cannotFulfillGoalException("A hero can't dig!\n");
  1874. }
  1875. }
  1876. void VCAI::tryRealize(Goals::Trade & g) //trade
  1877. {
  1878. if(ah->freeResources()[g.resID] >= g.value) //goal is already fulfilled. Why we need this check, anyway?
  1879. throw goalFulfilledException(sptr(g));
  1880. int accquiredResources = 0;
  1881. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1882. {
  1883. if(const IMarket * m = IMarket::castFrom(obj, false))
  1884. {
  1885. auto freeRes = ah->freeResources(); //trade only resources which are not reserved
  1886. for(auto it = Res::ResourceSet::nziterator(freeRes); it.valid(); it++)
  1887. {
  1888. auto res = it->resType;
  1889. if(res == g.resID) //sell any other resource
  1890. continue;
  1891. int toGive, toGet;
  1892. m->getOffer(res, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1893. toGive = toGive * (it->resVal / toGive); //round down
  1894. //TODO trade only as much as needed
  1895. if (toGive) //don't try to sell 0 resources
  1896. {
  1897. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, res, g.resID, toGive);
  1898. accquiredResources = toGet * (it->resVal / toGive);
  1899. logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, accquiredResources, g.resID, obj->getObjectName());
  1900. }
  1901. if (ah->freeResources()[g.resID] >= g.value)
  1902. throw goalFulfilledException(sptr(g)); //we traded all we needed
  1903. }
  1904. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1905. }
  1906. else
  1907. {
  1908. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1909. }
  1910. }
  1911. else
  1912. {
  1913. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1914. }
  1915. }
  1916. void VCAI::tryRealize(Goals::BuyArmy & g)
  1917. {
  1918. auto t = g.town;
  1919. ui64 valueBought = 0;
  1920. //buy the stacks with largest AI value
  1921. makePossibleUpgrades(t);
  1922. while (valueBought < g.value)
  1923. {
  1924. auto res = ah->allResources();
  1925. std::vector<creInfo> creaturesInDwellings;
  1926. for (int i = 0; i < t->creatures.size(); i++)
  1927. {
  1928. auto ci = infoFromDC(t->creatures[i]);
  1929. if(!ci.count
  1930. || ci.creID == -1
  1931. || (g.objid != -1 && ci.creID != g.objid)
  1932. || t->getUpperArmy()->getSlotFor(ci.creID) == SlotID())
  1933. continue;
  1934. vstd::amin(ci.count, res / ci.cre->cost); //max count we can afford
  1935. if(!ci.count)
  1936. continue;
  1937. ci.level = i; //this is important for Dungeon Summoning Portal
  1938. creaturesInDwellings.push_back(ci);
  1939. }
  1940. if (creaturesInDwellings.empty())
  1941. throw cannotFulfillGoalException("Can't buy any more creatures!");
  1942. creInfo ci =
  1943. *boost::max_element(creaturesInDwellings, [&res](const creInfo & lhs, const creInfo & rhs)
  1944. {
  1945. //max value of creatures we can buy with our res
  1946. int value1 = lhs.cre->AIValue * lhs.count,
  1947. value2 = rhs.cre->AIValue * rhs.count;
  1948. return value1 < value2;
  1949. });
  1950. cb->recruitCreatures(t, t->getUpperArmy(), ci.creID, ci.count, ci.level);
  1951. valueBought += ci.count * ci.cre->AIValue;
  1952. }
  1953. throw goalFulfilledException(sptr(g)); //we bought as many creatures as we wanted
  1954. }
  1955. void VCAI::tryRealize(Goals::Invalid & g)
  1956. {
  1957. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1958. }
  1959. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1960. {
  1961. logAi->debug("Attempting realizing goal with code %s", g.name());
  1962. throw cannotFulfillGoalException("Unknown type of goal !");
  1963. }
  1964. const CGTownInstance * VCAI::findTownWithTavern() const
  1965. {
  1966. for(const CGTownInstance * t : cb->getTownsInfo())
  1967. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1968. return t;
  1969. return nullptr;
  1970. }
  1971. Goals::TSubgoal VCAI::getGoal(HeroPtr h) const
  1972. {
  1973. auto it = lockedHeroes.find(h);
  1974. if(it != lockedHeroes.end())
  1975. return it->second;
  1976. else
  1977. return sptr(Goals::Invalid());
  1978. }
  1979. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1980. {
  1981. std::vector<HeroPtr> ret;
  1982. for(auto h : cb->getHeroesInfo())
  1983. {
  1984. //&& !vstd::contains(lockedHeroes, h)
  1985. //at this point we assume heroes exhausted their locked goals
  1986. if(canAct(h))
  1987. ret.push_back(h);
  1988. }
  1989. return ret;
  1990. }
  1991. bool VCAI::canAct(HeroPtr h) const
  1992. {
  1993. auto mission = lockedHeroes.find(h);
  1994. if(mission != lockedHeroes.end())
  1995. {
  1996. //FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
  1997. if(mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
  1998. return false;
  1999. }
  2000. return h->movement;
  2001. }
  2002. HeroPtr VCAI::primaryHero() const
  2003. {
  2004. auto hs = cb->getHeroesInfo();
  2005. if (hs.empty())
  2006. return nullptr;
  2007. else
  2008. return *boost::max_element(hs, compareHeroStrength);
  2009. }
  2010. void VCAI::endTurn()
  2011. {
  2012. logAi->info("Player %d (%s) ends turn", playerID, playerID.getStr());
  2013. if(!status.haveTurn())
  2014. {
  2015. logAi->error("Not having turn at the end of turn???");
  2016. }
  2017. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  2018. do
  2019. {
  2020. cb->endTurn();
  2021. }
  2022. 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
  2023. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.getStr());
  2024. }
  2025. void VCAI::striveToGoal(Goals::TSubgoal basicGoal)
  2026. {
  2027. //TODO: this function is deprecated and should be dropped altogether
  2028. auto goalToDecompose = basicGoal;
  2029. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  2030. int maxAbstractGoals = 10;
  2031. while (!elementarGoal->isElementar && maxAbstractGoals)
  2032. {
  2033. try
  2034. {
  2035. elementarGoal = decomposeGoal(goalToDecompose);
  2036. }
  2037. catch (goalFulfilledException & e)
  2038. {
  2039. //it is impossible to continue some goals (like exploration, for example)
  2040. completeGoal(e.goal); //put in goalsToRemove
  2041. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  2042. return;
  2043. }
  2044. catch (std::exception & e)
  2045. {
  2046. goalsToRemove.push_back(basicGoal);
  2047. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  2048. return;
  2049. }
  2050. if (elementarGoal->isAbstract) //we can decompose it further
  2051. {
  2052. goalsToAdd.push_back(elementarGoal);
  2053. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  2054. goalToDecompose = elementarGoal;
  2055. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  2056. maxAbstractGoals--;
  2057. }
  2058. else if (elementarGoal->isElementar) //should be
  2059. {
  2060. logAi->debug("Found elementar goal %s", elementarGoal->name());
  2061. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  2062. break;
  2063. }
  2064. else //should never be here
  2065. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  2066. }
  2067. //realize best goal
  2068. if (!elementarGoal->invalid())
  2069. {
  2070. logAi->debug("Trying to realize %s (value %2.3f)", elementarGoal->name(), elementarGoal->priority);
  2071. try
  2072. {
  2073. boost::this_thread::interruption_point();
  2074. elementarGoal->accept(this); //visitor pattern
  2075. boost::this_thread::interruption_point();
  2076. }
  2077. catch (boost::thread_interrupted & e)
  2078. {
  2079. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  2080. throw; //rethrow, we want to truly end this thread
  2081. }
  2082. catch (goalFulfilledException & e)
  2083. {
  2084. //the sub-goal was completed successfully
  2085. completeGoal(e.goal);
  2086. //local goal was also completed
  2087. completeGoal(elementarGoal);
  2088. }
  2089. catch (std::exception & e)
  2090. {
  2091. logAi->debug("Failed to realize subgoal of type %s, I will stop.", elementarGoal->name());
  2092. logAi->debug("The error message was: %s", e.what());
  2093. //erase base goal if we failed to execute decomposed goal
  2094. for (auto basicGoalToRemove : ultimateGoalsFromBasic[elementarGoal])
  2095. goalsToRemove.push_back(basicGoalToRemove);
  2096. }
  2097. }
  2098. }
  2099. Goals::TSubgoal VCAI::decomposeGoal(Goals::TSubgoal ultimateGoal)
  2100. {
  2101. if(ultimateGoal->isElementar)
  2102. {
  2103. logAi->warn("Trying to decompose elementar goal %s", ultimateGoal->name());
  2104. return ultimateGoal;
  2105. }
  2106. const int searchDepth = 30;
  2107. Goals::TSubgoal goal = ultimateGoal;
  2108. logAi->debug("Decomposing goal %s", ultimateGoal->name());
  2109. int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
  2110. while (maxGoals)
  2111. {
  2112. boost::this_thread::interruption_point();
  2113. goal = goal->whatToDoToAchieve(); //may throw if decomposition fails
  2114. --maxGoals;
  2115. if (goal == ultimateGoal) //compare objects by value
  2116. if (goal->isElementar == ultimateGoal->isElementar)
  2117. throw cannotFulfillGoalException((boost::format("Goal dependency loop detected for %s!")
  2118. % ultimateGoal->name()).str());
  2119. if (goal->isAbstract || goal->isElementar)
  2120. return goal;
  2121. else
  2122. logAi->debug("Considering: %s", goal->name());
  2123. }
  2124. throw cannotFulfillGoalException("Too many subgoals, don't know what to do");
  2125. }
  2126. void VCAI::performTypicalActions()
  2127. {
  2128. for(auto h : getUnblockedHeroes())
  2129. {
  2130. if(!h) //hero might be lost. getUnblockedHeroes() called once on start of turn
  2131. continue;
  2132. logAi->debug("Hero %s started wandering, MP=%d", h->name.c_str(), h->movement);
  2133. makePossibleUpgrades(*h);
  2134. pickBestArtifacts(*h);
  2135. try
  2136. {
  2137. wander(h);
  2138. }
  2139. catch(std::exception & e)
  2140. {
  2141. logAi->debug("Cannot use this hero anymore, received exception: %s", e.what());
  2142. continue;
  2143. }
  2144. }
  2145. }
  2146. void VCAI::buildArmyIn(const CGTownInstance * t)
  2147. {
  2148. makePossibleUpgrades(t->visitingHero);
  2149. makePossibleUpgrades(t);
  2150. recruitCreatures(t, t->getUpperArmy());
  2151. moveCreaturesToHero(t);
  2152. }
  2153. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  2154. {
  2155. std::map<int3, int> dstToRevealedTiles;
  2156. for(crint3 dir : int3::getDirs())
  2157. {
  2158. int3 tile = hpos + dir;
  2159. if(cb->isInTheMap(tile))
  2160. {
  2161. if(isBlockVisitObj(tile))
  2162. continue;
  2163. if(isSafeToVisit(h, tile) && isAccessibleForHero(tile, h))
  2164. {
  2165. auto distance = hpos.dist2d(tile); // diagonal movement opens more tiles but spends more mp
  2166. dstToRevealedTiles[tile] = howManyTilesWillBeDiscovered(tile, radius, cb.get(), h) / distance;
  2167. }
  2168. }
  2169. }
  2170. if(dstToRevealedTiles.empty()) //yes, it DID happen!
  2171. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2172. auto best = dstToRevealedTiles.begin();
  2173. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  2174. {
  2175. const CGPathNode * pn = cb->getPathsInfo(h.get())->getPathInfo(i->first);
  2176. //const TerrainTile *t = cb->getTile(i->first);
  2177. if(best->second < i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  2178. best = i;
  2179. }
  2180. if(best->second)
  2181. return best->first;
  2182. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2183. }
  2184. int3 VCAI::explorationNewPoint(HeroPtr h)
  2185. {
  2186. int radius = h->getSightRadius();
  2187. CCallback * cbp = cb.get();
  2188. const CGHeroInstance * hero = h.get();
  2189. std::vector<std::vector<int3>> tiles; //tiles[distance_to_fow]
  2190. tiles.resize(radius);
  2191. foreach_tile_pos([&](const int3 & pos)
  2192. {
  2193. if(!cbp->isVisible(pos))
  2194. tiles[0].push_back(pos);
  2195. });
  2196. float bestValue = 0; //discovered tile to node distance ratio
  2197. int3 bestTile(-1, -1, -1);
  2198. int3 ourPos = h->convertPosition(h->pos, false);
  2199. for(int i = 1; i < radius; i++)
  2200. {
  2201. getVisibleNeighbours(tiles[i - 1], tiles[i]);
  2202. vstd::removeDuplicates(tiles[i]);
  2203. for(const int3 & tile : tiles[i])
  2204. {
  2205. if(tile == ourPos) //shouldn't happen, but it does
  2206. continue;
  2207. if(!cb->getPathsInfo(hero)->getPathInfo(tile)->reachable()) //this will remove tiles that are guarded by monsters (or removable objects)
  2208. continue;
  2209. CGPath path;
  2210. cb->getPathsInfo(hero)->getPath(path, tile);
  2211. float ourValue = (float)howManyTilesWillBeDiscovered(tile, radius, cbp, h) / (path.nodes.size() + 1); //+1 prevents erratic jumps
  2212. if(ourValue > bestValue) //avoid costly checks of tiles that don't reveal much
  2213. {
  2214. auto obj = cb->getTopObj(tile);
  2215. if (obj)
  2216. if (obj->blockVisit && !isObjectRemovable(obj)) //we can't stand on that object
  2217. continue;
  2218. if(isSafeToVisit(h, tile))
  2219. {
  2220. bestTile = tile;
  2221. bestValue = ourValue;
  2222. }
  2223. }
  2224. }
  2225. }
  2226. return bestTile;
  2227. }
  2228. int3 VCAI::explorationDesperate(HeroPtr h)
  2229. {
  2230. int radius = h->getSightRadius();
  2231. std::vector<std::vector<int3>> tiles; //tiles[distance_to_fow]
  2232. tiles.resize(radius);
  2233. CCallback * cbp = cb.get();
  2234. foreach_tile_pos([&](const int3 & pos)
  2235. {
  2236. if(!cbp->isVisible(pos))
  2237. tiles[0].push_back(pos);
  2238. });
  2239. ui64 lowestDanger = -1;
  2240. int3 bestTile(-1, -1, -1);
  2241. for(int i = 1; i < radius; i++)
  2242. {
  2243. getVisibleNeighbours(tiles[i - 1], tiles[i]);
  2244. vstd::removeDuplicates(tiles[i]);
  2245. for(const int3 & tile : tiles[i])
  2246. {
  2247. if(cbp->getTile(tile)->blocked) //does it shorten the time?
  2248. continue;
  2249. if(!howManyTilesWillBeDiscovered(tile, radius, cbp, h)) //avoid costly checks of tiles that don't reveal much
  2250. continue;
  2251. auto paths = ah->getPathsToTile(h, tile);
  2252. for(auto path : paths)
  2253. {
  2254. auto t = path.firstTileToGet();
  2255. if(t == bestTile)
  2256. continue;
  2257. auto obj = cb->getTopObj(t);
  2258. if (obj)
  2259. if (obj->blockVisit && !isObjectRemovable(obj)) //we can't stand on object or remove it
  2260. continue;
  2261. ui64 ourDanger = path.getTotalDanger(h);
  2262. if(ourDanger < lowestDanger)
  2263. {
  2264. if(!ourDanger) //at least one safe place found
  2265. return t;
  2266. bestTile = t;
  2267. lowestDanger = ourDanger;
  2268. }
  2269. }
  2270. }
  2271. }
  2272. return bestTile;
  2273. }
  2274. void VCAI::checkHeroArmy(HeroPtr h)
  2275. {
  2276. auto it = lockedHeroes.find(h);
  2277. if(it != lockedHeroes.end())
  2278. {
  2279. if(it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  2280. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  2281. }
  2282. }
  2283. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2284. {
  2285. logAi->debug("Trying to recruit a hero in %s at %s", t->name, t->visitablePos().toString());
  2286. auto heroes = cb->getAvailableHeroes(t);
  2287. if(heroes.size())
  2288. {
  2289. auto hero = heroes[0];
  2290. if(heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
  2291. {
  2292. if(heroes[1]->getTotalStrength() > hero->getTotalStrength())
  2293. hero = heroes[1];
  2294. }
  2295. cb->recruitHero(t, hero);
  2296. throw goalFulfilledException(sptr(Goals::RecruitHero().settown(t)));
  2297. }
  2298. else if(throwing)
  2299. {
  2300. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2301. }
  2302. }
  2303. void VCAI::finish()
  2304. {
  2305. if(makingTurn)
  2306. {
  2307. makingTurn->interrupt();
  2308. makingTurn->join();
  2309. makingTurn.reset();
  2310. }
  2311. }
  2312. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  2313. {
  2314. boost::thread newThread([this, whatToDo]()
  2315. {
  2316. setThreadName("VCAI::requestActionASAP::whatToDo");
  2317. SET_GLOBAL_STATE(this);
  2318. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  2319. whatToDo();
  2320. });
  2321. }
  2322. void VCAI::lostHero(HeroPtr h)
  2323. {
  2324. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
  2325. vstd::erase_if_present(lockedHeroes, h);
  2326. for(auto obj : reservedHeroesMap[h])
  2327. {
  2328. vstd::erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2329. }
  2330. vstd::erase_if_present(reservedHeroesMap, h);
  2331. vstd::erase_if_present(visitedHeroes, h);
  2332. for (auto heroVec : visitedHeroes)
  2333. {
  2334. vstd::erase_if_present(heroVec.second, h);
  2335. }
  2336. //remove goals with removed hero assigned from main loop
  2337. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  2338. {
  2339. if(x.first->hero == h)
  2340. return true;
  2341. else
  2342. return false;
  2343. });
  2344. auto removedHeroGoalPredicate = [&](const Goals::TSubgoal & x) ->bool
  2345. {
  2346. if(x->hero == h)
  2347. return true;
  2348. else
  2349. return false;
  2350. };
  2351. vstd::erase_if(basicGoals, removedHeroGoalPredicate);
  2352. vstd::erase_if(goalsToAdd, removedHeroGoalPredicate);
  2353. vstd::erase_if(goalsToRemove, removedHeroGoalPredicate);
  2354. for(auto goal : ultimateGoalsFromBasic)
  2355. vstd::erase_if(goal.second, removedHeroGoalPredicate);
  2356. }
  2357. void VCAI::answerQuery(QueryID queryID, int selection)
  2358. {
  2359. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  2360. if(queryID != QueryID(-1))
  2361. {
  2362. cb->selectionMade(selection, queryID);
  2363. }
  2364. else
  2365. {
  2366. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2367. //do nothing
  2368. }
  2369. }
  2370. void VCAI::requestSent(const CPackForServer * pack, int requestID)
  2371. {
  2372. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2373. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  2374. {
  2375. status.attemptedAnsweringQuery(reply->qid, requestID);
  2376. }
  2377. }
  2378. std::string VCAI::getBattleAIName() const
  2379. {
  2380. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  2381. return settings["server"]["enemyAI"].String();
  2382. else
  2383. return "BattleAI";
  2384. }
  2385. void VCAI::validateObject(const CGObjectInstance * obj)
  2386. {
  2387. validateObject(obj->id);
  2388. }
  2389. void VCAI::validateObject(ObjectIdRef obj)
  2390. {
  2391. auto matchesId = [&](const CGObjectInstance * hlpObj) -> bool
  2392. {
  2393. return hlpObj->id == obj.id;
  2394. };
  2395. if(!obj)
  2396. {
  2397. vstd::erase_if(visitableObjs, matchesId);
  2398. for(auto & p : reservedHeroesMap)
  2399. vstd::erase_if(p.second, matchesId);
  2400. vstd::erase_if(reservedObjs, matchesId);
  2401. }
  2402. }
  2403. AIStatus::AIStatus()
  2404. {
  2405. battle = NO_BATTLE;
  2406. havingTurn = false;
  2407. ongoingHeroMovement = false;
  2408. ongoingChannelProbing = false;
  2409. }
  2410. AIStatus::~AIStatus()
  2411. {
  2412. }
  2413. void AIStatus::setBattle(BattleState BS)
  2414. {
  2415. boost::unique_lock<boost::mutex> lock(mx);
  2416. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2417. battle = BS;
  2418. cv.notify_all();
  2419. }
  2420. BattleState AIStatus::getBattle()
  2421. {
  2422. boost::unique_lock<boost::mutex> lock(mx);
  2423. return battle;
  2424. }
  2425. void AIStatus::addQuery(QueryID ID, std::string description)
  2426. {
  2427. if(ID == QueryID(-1))
  2428. {
  2429. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  2430. return;
  2431. }
  2432. assert(ID.getNum() >= 0);
  2433. boost::unique_lock<boost::mutex> lock(mx);
  2434. assert(!vstd::contains(remainingQueries, ID));
  2435. remainingQueries[ID] = description;
  2436. cv.notify_all();
  2437. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2438. }
  2439. void AIStatus::removeQuery(QueryID ID)
  2440. {
  2441. boost::unique_lock<boost::mutex> lock(mx);
  2442. assert(vstd::contains(remainingQueries, ID));
  2443. std::string description = remainingQueries[ID];
  2444. remainingQueries.erase(ID);
  2445. cv.notify_all();
  2446. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2447. }
  2448. int AIStatus::getQueriesCount()
  2449. {
  2450. boost::unique_lock<boost::mutex> lock(mx);
  2451. return remainingQueries.size();
  2452. }
  2453. void AIStatus::startedTurn()
  2454. {
  2455. boost::unique_lock<boost::mutex> lock(mx);
  2456. havingTurn = true;
  2457. cv.notify_all();
  2458. }
  2459. void AIStatus::madeTurn()
  2460. {
  2461. boost::unique_lock<boost::mutex> lock(mx);
  2462. havingTurn = false;
  2463. cv.notify_all();
  2464. }
  2465. void AIStatus::waitTillFree()
  2466. {
  2467. boost::unique_lock<boost::mutex> lock(mx);
  2468. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2469. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  2470. }
  2471. bool AIStatus::haveTurn()
  2472. {
  2473. boost::unique_lock<boost::mutex> lock(mx);
  2474. return havingTurn;
  2475. }
  2476. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2477. {
  2478. boost::unique_lock<boost::mutex> lock(mx);
  2479. assert(vstd::contains(remainingQueries, queryID));
  2480. std::string description = remainingQueries[queryID];
  2481. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  2482. requestToQueryID[answerRequestID] = queryID;
  2483. }
  2484. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2485. {
  2486. assert(vstd::contains(requestToQueryID, answerRequestID));
  2487. QueryID query = requestToQueryID[answerRequestID];
  2488. assert(vstd::contains(remainingQueries, query));
  2489. requestToQueryID.erase(answerRequestID);
  2490. if(result)
  2491. {
  2492. removeQuery(query);
  2493. }
  2494. else
  2495. {
  2496. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  2497. //TODO safely retry
  2498. }
  2499. }
  2500. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  2501. {
  2502. boost::unique_lock<boost::mutex> lock(mx);
  2503. if(started)
  2504. {
  2505. objectsBeingVisited.push_back(obj);
  2506. }
  2507. else
  2508. {
  2509. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2510. // causing visit to hero on the other side.
  2511. // However, we are guaranteed that start/end visit notification maintain stack order.
  2512. assert(!objectsBeingVisited.empty());
  2513. objectsBeingVisited.pop_back();
  2514. }
  2515. cv.notify_all();
  2516. }
  2517. void AIStatus::setMove(bool ongoing)
  2518. {
  2519. boost::unique_lock<boost::mutex> lock(mx);
  2520. ongoingHeroMovement = ongoing;
  2521. cv.notify_all();
  2522. }
  2523. void AIStatus::setChannelProbing(bool ongoing)
  2524. {
  2525. boost::unique_lock<boost::mutex> lock(mx);
  2526. ongoingChannelProbing = ongoing;
  2527. cv.notify_all();
  2528. }
  2529. bool AIStatus::channelProbing()
  2530. {
  2531. return ongoingChannelProbing;
  2532. }
  2533. bool isWeeklyRevisitable(const CGObjectInstance * obj)
  2534. {
  2535. //TODO: allow polling of remaining creatures in dwelling
  2536. if(dynamic_cast<const CGVisitableOPW *>(obj)) // ensures future compatibility, unlike IDs
  2537. return true;
  2538. if(dynamic_cast<const CGDwelling *>(obj))
  2539. return true;
  2540. if(dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2541. return true;
  2542. switch(obj->ID)
  2543. {
  2544. case Obj::STABLES:
  2545. case Obj::MAGIC_WELL:
  2546. case Obj::HILL_FORT:
  2547. return true;
  2548. case Obj::BORDER_GATE:
  2549. case Obj::BORDERGUARD:
  2550. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  2551. }
  2552. return false;
  2553. }
  2554. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2555. {
  2556. switch(obj->ID)
  2557. {
  2558. case Obj::TOWN:
  2559. case Obj::HERO: //never visit our heroes at random
  2560. return obj->tempOwner != h->tempOwner; //do not visit our towns at random
  2561. case Obj::BORDER_GATE:
  2562. {
  2563. for(auto q : ai->myCb->getMyQuests())
  2564. {
  2565. if(q.obj == obj)
  2566. {
  2567. return false; // do not visit guards or gates when wandering
  2568. }
  2569. }
  2570. return true; //we don't have this quest yet
  2571. }
  2572. case Obj::BORDERGUARD: //open borderguard if possible
  2573. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  2574. case Obj::SEER_HUT:
  2575. case Obj::QUEST_GUARD:
  2576. {
  2577. for(auto q : ai->myCb->getMyQuests())
  2578. {
  2579. if(q.obj == obj)
  2580. {
  2581. if(q.quest->checkQuest(h.h))
  2582. return true; //we completed the quest
  2583. else
  2584. return false; //we can't complete this quest
  2585. }
  2586. }
  2587. return true; //we don't have this quest yet
  2588. }
  2589. case Obj::CREATURE_GENERATOR1:
  2590. {
  2591. if(obj->tempOwner != h->tempOwner)
  2592. return true; //flag just in case
  2593. bool canRecruitCreatures = false;
  2594. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2595. for(auto level : d->creatures)
  2596. {
  2597. for(auto c : level.second)
  2598. {
  2599. if(h->getSlotFor(CreatureID(c)) != SlotID())
  2600. canRecruitCreatures = true;
  2601. }
  2602. }
  2603. return canRecruitCreatures;
  2604. }
  2605. case Obj::HILL_FORT:
  2606. {
  2607. for(auto slot : h->Slots())
  2608. {
  2609. if(slot.second->type->upgrades.size())
  2610. return true; //TODO: check price?
  2611. }
  2612. return false;
  2613. }
  2614. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2615. case Obj::MONOLITH_ONE_WAY_EXIT:
  2616. case Obj::MONOLITH_TWO_WAY:
  2617. case Obj::WHIRLPOOL:
  2618. return false;
  2619. case Obj::SCHOOL_OF_MAGIC:
  2620. case Obj::SCHOOL_OF_WAR:
  2621. {
  2622. if (ai->ah->freeGold() < 1000)
  2623. return false;
  2624. break;
  2625. }
  2626. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2627. if(h->level < 12)
  2628. return false;
  2629. break;
  2630. case Obj::TREE_OF_KNOWLEDGE:
  2631. {
  2632. TResources myRes = ai->ah->freeResources();
  2633. if(myRes[Res::GOLD] < 2000 || myRes[Res::GEMS] < 10)
  2634. return false;
  2635. break;
  2636. }
  2637. case Obj::MAGIC_WELL:
  2638. return h->mana < h->manaLimit();
  2639. case Obj::PRISON:
  2640. return ai->myCb->getHeroesInfo().size() < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER;
  2641. case Obj::TAVERN:
  2642. {
  2643. //TODO: make AI actually recruit heroes
  2644. //TODO: only on request
  2645. if(ai->myCb->getHeroesInfo().size() >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)
  2646. return false;
  2647. else if(ai->ah->freeGold() < GameConstants::HERO_GOLD_COST)
  2648. return false;
  2649. break;
  2650. }
  2651. case Obj::BOAT:
  2652. return false;
  2653. //Boats are handled by pathfinder
  2654. case Obj::EYE_OF_MAGI:
  2655. return false; //this object is useless to visit, but could be visited indefinitely
  2656. }
  2657. if(obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2658. return false;
  2659. return true;
  2660. }