VCAI.cpp 100 KB

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