VCAI.cpp 96 KB

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