VCAI.cpp 99 KB

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