VCAI.cpp 95 KB

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