VCAI.cpp 103 KB

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