VCAI.cpp 98 KB

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