VCAI.cpp 97 KB

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