VCAI.cpp 101 KB

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