VCAI.cpp 100 KB

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