VCAI.cpp 99 KB

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