VCAI.cpp 98 KB

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