VCAI.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913
  1. /*
  2. * VCAI.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "VCAI.h"
  12. #include "FuzzyHelper.h"
  13. #include "ResourceManager.h"
  14. #include "BuildingManager.h"
  15. #include "Goals/Goals.h"
  16. #include "Goals/CompleteQuest.h"
  17. #include "../../lib/AsyncRunner.h"
  18. #include "../../lib/CThreadHelper.h"
  19. #include "../../lib/UnlockGuard.h"
  20. #include "../../lib/StartInfo.h"
  21. #include "../../lib/mapObjects/MapObjects.h"
  22. #include "../../lib/mapObjects/ObjectTemplate.h"
  23. #include "../../lib/CConfigHandler.h"
  24. #include "../../lib/IGameSettings.h"
  25. #include "../../lib/gameState/CGameState.h"
  26. #include "../../lib/gameState/UpgradeInfo.h"
  27. #include "../../lib/bonuses/Limiters.h"
  28. #include "../../lib/bonuses/Updaters.h"
  29. #include "../../lib/bonuses/Propagators.h"
  30. #include "../../lib/entities/artifact/ArtifactUtils.h"
  31. #include "../../lib/entities/artifact/CArtifact.h"
  32. #include "../../lib/entities/building/CBuilding.h"
  33. #include "../../lib/mapObjects/CQuest.h"
  34. #include "../../lib/networkPacks/PacksForClient.h"
  35. #include "../../lib/networkPacks/PacksForClientBattle.h"
  36. #include "../../lib/networkPacks/PacksForServer.h"
  37. #include "../../lib/serializer/CTypeList.h"
  38. #include "../../lib/pathfinder/PathfinderCache.h"
  39. #include "../../lib/pathfinder/PathfinderOptions.h"
  40. #include "AIhelper.h"
  41. extern FuzzyHelper * fh;
  42. const double SAFE_ATTACK_CONSTANT = 1.5;
  43. //one thread may be turn of AI and another will be handling a side effect for AI2
  44. thread_local CCallback * cb = nullptr;
  45. thread_local VCAI * ai = nullptr;
  46. //std::map<int, std::map<int, int> > HeroView::infosCount;
  47. //helper RAII to manage global ai/cb ptrs
  48. struct SetGlobalState
  49. {
  50. SetGlobalState(VCAI * AI)
  51. {
  52. assert(!ai);
  53. assert(!cb);
  54. ai = AI;
  55. cb = AI->myCb.get();
  56. }
  57. ~SetGlobalState()
  58. {
  59. //TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
  60. //TODO: to ensure that, make rm unique_ptr
  61. ai = nullptr;
  62. cb = nullptr;
  63. }
  64. };
  65. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai)
  66. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  67. #define MAKING_TURN SET_GLOBAL_STATE(this)
  68. VCAI::VCAI()
  69. {
  70. LOG_TRACE(logAi);
  71. asyncTasks = std::make_unique<AsyncRunner>();
  72. destinationTeleport = ObjectInstanceID();
  73. destinationTeleportPos = int3(-1);
  74. ah = new AIhelper();
  75. ah->setAI(this);
  76. }
  77. VCAI::~VCAI()
  78. {
  79. delete ah;
  80. LOG_TRACE(logAi);
  81. finish();
  82. }
  83. void VCAI::availableCreaturesChanged(const CGDwelling * town)
  84. {
  85. LOG_TRACE(logAi);
  86. NET_EVENT_HANDLER;
  87. }
  88. void VCAI::heroMoved(const TryMoveHero & details, bool verbose)
  89. {
  90. LOG_TRACE(logAi);
  91. NET_EVENT_HANDLER;
  92. //enemy hero may have left visible area
  93. validateObject(details.id);
  94. auto hero = cb->getHero(details.id);
  95. const int3 from = hero ? hero->convertToVisitablePos(details.start) : (details.start - int3(0,1,0));
  96. const int3 to = hero ? hero->convertToVisitablePos(details.end) : (details.end - int3(0,1,0));
  97. const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from, verbose));
  98. const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to, verbose));
  99. if(details.result == TryMoveHero::TELEPORTATION)
  100. {
  101. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  102. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  103. if(t1 && t2)
  104. {
  105. if(cb->isTeleportChannelBidirectional(t1->channel))
  106. {
  107. 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
  108. {
  109. knownSubterraneanGates[o1] = o2;
  110. knownSubterraneanGates[o2] = o1;
  111. logAi->debug("Found a pair of subterranean gates between %s and %s!", from.toString(), to.toString());
  112. }
  113. }
  114. }
  115. //FIXME: teleports are not correctly visited
  116. unreserveObject(hero, t1);
  117. unreserveObject(hero, t2);
  118. }
  119. else if(details.result == TryMoveHero::EMBARK && hero)
  120. {
  121. //make sure AI not attempt to visit used boat
  122. validateObject(hero->getBoat());
  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::heroInGarrisonChange(const CGTownInstance * town)
  132. {
  133. LOG_TRACE(logAi);
  134. NET_EVENT_HANDLER;
  135. }
  136. void VCAI::centerView(int3 pos, int focusTime)
  137. {
  138. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  139. NET_EVENT_HANDLER;
  140. }
  141. void VCAI::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
  142. {
  143. LOG_TRACE(logAi);
  144. NET_EVENT_HANDLER;
  145. }
  146. void VCAI::artifactAssembled(const ArtifactLocation & al)
  147. {
  148. LOG_TRACE(logAi);
  149. NET_EVENT_HANDLER;
  150. }
  151. void VCAI::showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID)
  152. {
  153. LOG_TRACE(logAi);
  154. NET_EVENT_HANDLER;
  155. status.addQuery(queryID, "TavernWindow");
  156. executeActionAsync("showTavernWindow", [this, queryID](){ answerQuery(queryID, 0); });
  157. }
  158. void VCAI::showThievesGuildWindow(const CGObjectInstance * obj)
  159. {
  160. LOG_TRACE(logAi);
  161. NET_EVENT_HANDLER;
  162. }
  163. void VCAI::playerBlocked(int reason, bool start)
  164. {
  165. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  166. NET_EVENT_HANDLER;
  167. if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
  168. status.setBattle(UPCOMING_BATTLE);
  169. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  170. status.setMove(start);
  171. }
  172. void VCAI::showPuzzleMap()
  173. {
  174. LOG_TRACE(logAi);
  175. NET_EVENT_HANDLER;
  176. }
  177. void VCAI::showShipyardDialog(const IShipyard * obj)
  178. {
  179. LOG_TRACE(logAi);
  180. NET_EVENT_HANDLER;
  181. }
  182. void VCAI::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  183. {
  184. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf.toString());
  185. NET_EVENT_HANDLER;
  186. logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.toString(), player, player.toString(), (victoryLossCheckResult.victory() ? "won" : "lost"));
  187. if(player == playerID)
  188. {
  189. if(victoryLossCheckResult.victory())
  190. {
  191. logAi->debug("VCAI: I won! Incredible!");
  192. logAi->debug("Turn nr %d", myCb->getDate());
  193. }
  194. else
  195. {
  196. logAi->debug("VCAI: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.toString());
  197. }
  198. makingTurnInterrupption.interruptThread();
  199. }
  200. }
  201. void VCAI::artifactPut(const ArtifactLocation & al)
  202. {
  203. LOG_TRACE(logAi);
  204. NET_EVENT_HANDLER;
  205. }
  206. void VCAI::artifactRemoved(const ArtifactLocation & al)
  207. {
  208. LOG_TRACE(logAi);
  209. NET_EVENT_HANDLER;
  210. }
  211. void VCAI::artifactDisassembled(const ArtifactLocation & al)
  212. {
  213. LOG_TRACE(logAi);
  214. NET_EVENT_HANDLER;
  215. }
  216. void VCAI::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  217. {
  218. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
  219. NET_EVENT_HANDLER;
  220. if(start && visitedObj) //we can end visit with null object, anyway
  221. {
  222. markObjectVisited(visitedObj);
  223. unreserveObject(visitor, visitedObj);
  224. completeGoal(sptr(Goals::VisitObj(visitedObj->id.getNum()).sethero(visitor))); //we don't need to visit it anymore
  225. //TODO: what if we visited one-time visitable object that was reserved by another hero (shouldn't, but..)
  226. if (visitedObj->ID == Obj::HERO)
  227. {
  228. visitedHeroes[visitor].insert(HeroPtr(dynamic_cast<const CGHeroInstance *>(visitedObj)));
  229. }
  230. }
  231. status.heroVisit(visitedObj, start);
  232. }
  233. void VCAI::availableArtifactsChanged(const CGBlackMarket * bm)
  234. {
  235. LOG_TRACE(logAi);
  236. NET_EVENT_HANDLER;
  237. }
  238. void VCAI::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
  239. {
  240. LOG_TRACE(logAi);
  241. NET_EVENT_HANDLER;
  242. //buildArmyIn(town);
  243. //moveCreaturesToHero(town);
  244. }
  245. void VCAI::tileHidden(const std::unordered_set<int3> & pos)
  246. {
  247. LOG_TRACE(logAi);
  248. NET_EVENT_HANDLER;
  249. validateVisitableObjs();
  250. clearPathsInfo();
  251. }
  252. void VCAI::tileRevealed(const std::unordered_set<int3> & pos)
  253. {
  254. LOG_TRACE(logAi);
  255. NET_EVENT_HANDLER;
  256. for(int3 tile : pos)
  257. {
  258. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  259. addVisitableObj(obj);
  260. }
  261. clearPathsInfo();
  262. }
  263. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  264. {
  265. LOG_TRACE(logAi);
  266. NET_EVENT_HANDLER;
  267. auto firstHero = cb->getHero(hero1);
  268. auto secondHero = cb->getHero(hero2);
  269. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->getNameTranslated() % firstHero->tempOwner % secondHero->getNameTranslated() % secondHero->tempOwner));
  270. executeActionAsync("heroExchangeStarted", [this, firstHero, secondHero, query]()
  271. {
  272. float goalpriority1 = 0;
  273. float goalpriority2 = 0;
  274. auto firstGoal = getGoal(firstHero);
  275. if(firstGoal->goalType == Goals::GATHER_ARMY)
  276. goalpriority1 = firstGoal->priority;
  277. auto secondGoal = getGoal(secondHero);
  278. if(secondGoal->goalType == Goals::GATHER_ARMY)
  279. goalpriority2 = secondGoal->priority;
  280. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  281. {
  282. this->pickBestCreatures(h1, h2);
  283. this->pickBestArtifacts(h1, h2);
  284. };
  285. //Do not attempt army or artifacts exchange if we visited ally player
  286. //Visits can still be useful if hero have skills like Scholar
  287. if(firstHero->tempOwner != secondHero->tempOwner)
  288. {
  289. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  290. }
  291. else if(goalpriority1 > goalpriority2)
  292. {
  293. transferFrom2to1(firstHero, secondHero);
  294. }
  295. else if(goalpriority1 < goalpriority2)
  296. {
  297. transferFrom2to1(secondHero, firstHero);
  298. }
  299. else //regular criteria
  300. {
  301. if(firstHero->getFightingStrength() > secondHero->getFightingStrength() && ah->canGetArmy(firstHero, secondHero))
  302. transferFrom2to1(firstHero, secondHero);
  303. else if(ah->canGetArmy(secondHero, firstHero))
  304. transferFrom2to1(secondHero, firstHero);
  305. }
  306. completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
  307. completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
  308. answerQuery(query, 0);
  309. });
  310. }
  311. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val)
  312. {
  313. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which.getNum() % val);
  314. NET_EVENT_HANDLER;
  315. }
  316. void VCAI::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level, QueryID queryID)
  317. {
  318. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  319. NET_EVENT_HANDLER;
  320. status.addQuery(queryID, "RecruitmentDialog");
  321. executeActionAsync("showRecruitmentDialog", [this, dwelling, dst, queryID](){
  322. recruitCreatures(dwelling, dst);
  323. checkHeroArmy(dynamic_cast<const CGHeroInstance*>(dst));
  324. answerQuery(queryID, 0);
  325. });
  326. }
  327. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  328. {
  329. LOG_TRACE(logAi);
  330. NET_EVENT_HANDLER;
  331. }
  332. void VCAI::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  333. {
  334. LOG_TRACE(logAi);
  335. NET_EVENT_HANDLER;
  336. }
  337. void VCAI::newObject(const CGObjectInstance * obj)
  338. {
  339. LOG_TRACE(logAi);
  340. NET_EVENT_HANDLER;
  341. if(obj->isVisitable())
  342. addVisitableObj(obj);
  343. }
  344. //to prevent AI from accessing objects that got deleted while they became invisible (Cover of Darkness, enemy hero moved etc.) below code allows AI to know deletion of objects out of sight
  345. //see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
  346. void VCAI::objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator)
  347. {
  348. LOG_TRACE(logAi);
  349. NET_EVENT_HANDLER;
  350. vstd::erase_if_present(visitableObjs, obj);
  351. vstd::erase_if_present(alreadyVisited, obj);
  352. for(auto h : cb->getHeroesInfo())
  353. unreserveObject(h, obj);
  354. std::function<bool(const Goals::TSubgoal &)> checkRemovalValidity = [&](const Goals::TSubgoal & x) -> bool
  355. {
  356. if((x->goalType == Goals::VISIT_OBJ) && (x->objid == obj->id.getNum()))
  357. return true;
  358. else if(x->parent && checkRemovalValidity(x->parent)) //repeat this lambda check recursively on parent goal
  359. return true;
  360. else
  361. return false;
  362. };
  363. //clear VCAI / main loop caches
  364. vstd::erase_if(lockedHeroes, [&](const std::pair<HeroPtr, Goals::TSubgoal> & x) -> bool
  365. {
  366. return checkRemovalValidity(x.second);
  367. });
  368. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  369. {
  370. return checkRemovalValidity(x.first);
  371. });
  372. vstd::erase_if(basicGoals, checkRemovalValidity);
  373. vstd::erase_if(goalsToAdd, checkRemovalValidity);
  374. vstd::erase_if(goalsToRemove, checkRemovalValidity);
  375. for(auto goal : ultimateGoalsFromBasic)
  376. vstd::erase_if(goal.second, checkRemovalValidity);
  377. //clear resource manager goal cache
  378. ah->removeOutdatedObjectives(checkRemovalValidity);
  379. //TODO: Find better way to handle hero boat removal
  380. if(auto hero = dynamic_cast<const CGHeroInstance *>(obj))
  381. {
  382. if(hero->inBoat())
  383. {
  384. vstd::erase_if_present(visitableObjs, hero->getBoat());
  385. vstd::erase_if_present(alreadyVisited, hero->getBoat());
  386. for(auto h : cb->getHeroesInfo())
  387. unreserveObject(h, hero->getBoat());
  388. }
  389. }
  390. //TODO
  391. //there are other places where CGObjectinstance ptrs are stored...
  392. //
  393. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  394. {
  395. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  396. }
  397. }
  398. void VCAI::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  399. {
  400. LOG_TRACE(logAi);
  401. NET_EVENT_HANDLER;
  402. executeActionAsync("showHillFortWindow", [visitor]()
  403. {
  404. makePossibleUpgrades(visitor);
  405. });
  406. }
  407. void VCAI::playerBonusChanged(const Bonus & bonus, bool gain)
  408. {
  409. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  410. NET_EVENT_HANDLER;
  411. }
  412. void VCAI::heroCreated(const CGHeroInstance * h)
  413. {
  414. LOG_TRACE(logAi);
  415. if(h->getVisitedTown())
  416. townVisitsThisWeek[HeroPtr(h)].insert(h->getVisitedTown());
  417. NET_EVENT_HANDLER;
  418. }
  419. void VCAI::advmapSpellCast(const CGHeroInstance * caster, SpellID spellID)
  420. {
  421. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  422. NET_EVENT_HANDLER;
  423. }
  424. void VCAI::showInfoDialog(EInfoWindowMode type, const std::string & text, const std::vector<Component> & components, int soundID)
  425. {
  426. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  427. NET_EVENT_HANDLER;
  428. }
  429. void VCAI::requestRealized(PackageApplied * pa)
  430. {
  431. LOG_TRACE(logAi);
  432. NET_EVENT_HANDLER;
  433. if(status.haveTurn())
  434. {
  435. if(pa->packType == CTypeList::getInstance().getTypeID<EndTurn>(nullptr))
  436. {
  437. if(pa->result)
  438. status.madeTurn();
  439. }
  440. }
  441. if(pa->packType == CTypeList::getInstance().getTypeID<QueryReply>(nullptr))
  442. {
  443. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  444. }
  445. }
  446. void VCAI::receivedResource()
  447. {
  448. LOG_TRACE(logAi);
  449. NET_EVENT_HANDLER;
  450. }
  451. void VCAI::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  452. {
  453. LOG_TRACE(logAi);
  454. NET_EVENT_HANDLER;
  455. status.addQuery(queryID, "UniversityWindow");
  456. executeActionAsync("showUniversityWindow", [this, queryID](){ answerQuery(queryID, 0); });
  457. }
  458. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  459. {
  460. LOG_TRACE(logAi);
  461. NET_EVENT_HANDLER;
  462. }
  463. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  464. {
  465. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  466. NET_EVENT_HANDLER;
  467. }
  468. void VCAI::battleResultsApplied()
  469. {
  470. LOG_TRACE(logAi);
  471. NET_EVENT_HANDLER;
  472. assert(status.getBattle() == ENDING_BATTLE);
  473. status.setBattle(NO_BATTLE);
  474. }
  475. void VCAI::beforeObjectPropertyChanged(const SetObjectProperty * sop)
  476. {
  477. }
  478. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  479. {
  480. LOG_TRACE(logAi);
  481. NET_EVENT_HANDLER;
  482. if(sop->what == ObjProperty::OWNER)
  483. {
  484. if(myCb->getPlayerRelations(playerID, sop->identifier.as<PlayerColor>()) == PlayerRelations::ENEMIES)
  485. {
  486. //we want to visit objects owned by oppponents
  487. auto obj = myCb->getObj(sop->id, false);
  488. if(obj)
  489. {
  490. addVisitableObj(obj); // TODO: Remove once save compatibility broken. In past owned objects were removed from this set
  491. vstd::erase_if_present(alreadyVisited, obj);
  492. }
  493. }
  494. }
  495. }
  496. void VCAI::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  497. {
  498. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  499. NET_EVENT_HANDLER;
  500. if(town->getOwner() == playerID && what == 1) //built
  501. completeGoal(sptr(Goals::BuildThis(buildingID, town)));
  502. }
  503. void VCAI::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  504. {
  505. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  506. NET_EVENT_HANDLER;
  507. }
  508. void VCAI::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  509. {
  510. LOG_TRACE(logAi);
  511. NET_EVENT_HANDLER;
  512. status.addQuery(queryID, "MarketWindow");
  513. executeActionAsync("showMarketWindow", [this, queryID](){ answerQuery(queryID, 0); });
  514. }
  515. void VCAI::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain)
  516. {
  517. //TODO: AI support for ViewXXX spell
  518. LOG_TRACE(logAi);
  519. NET_EVENT_HANDLER;
  520. }
  521. void VCAI::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  522. {
  523. LOG_TRACE(logAi);
  524. env = ENV;
  525. myCb = CB;
  526. cbc = CB;
  527. ah->init(CB.get());
  528. NET_EVENT_HANDLER; //sets ah->rm->cb
  529. playerID = *myCb->getPlayerID();
  530. myCb->waitTillRealize = true;
  531. myCb->unlockGsWhenWaiting = true;
  532. pathfinderCache = std::make_unique<PathfinderCache>(myCb.get(), PathfinderOptions(*myCb));
  533. if(!fh)
  534. fh = new FuzzyHelper();
  535. retrieveVisitableObjs();
  536. }
  537. std::shared_ptr<const CPathsInfo> VCAI::getPathsInfo(const CGHeroInstance * h) const
  538. {
  539. return pathfinderCache->getPathsInfo(h);
  540. }
  541. void VCAI::invalidatePaths()
  542. {
  543. pathfinderCache->invalidatePaths();
  544. }
  545. void VCAI::yourTurn(QueryID queryID)
  546. {
  547. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  548. NET_EVENT_HANDLER;
  549. status.addQuery(queryID, "YourTurn");
  550. executeActionAsync("yourTurn", [this, queryID](){ answerQuery(queryID, 0); });
  551. status.startedTurn();
  552. makingTurnInterrupption.reset();
  553. asyncTasks->run([this]()
  554. {
  555. ScopedThreadName guard("VCAI::makingTurn");
  556. makeTurn();
  557. });
  558. }
  559. void VCAI::heroGotLevel(const CGHeroInstance * hero, PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  560. {
  561. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  562. NET_EVENT_HANDLER;
  563. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->getNameTranslated() % hero->level));
  564. executeActionAsync("heroGotLevel", [this, queryID](){ answerQuery(queryID, 0); });
  565. }
  566. void VCAI::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  567. {
  568. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  569. NET_EVENT_HANDLER;
  570. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->getArmy()->nodeName() % static_cast<int>(commander->level)));
  571. executeActionAsync("commanderGotLevel", [this, queryID](){ answerQuery(queryID, 0); });
  572. }
  573. void VCAI::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel, bool safeToAutoaccept)
  574. {
  575. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i', autoaccept '%i'", text % askID % soundID % selection % cancel % safeToAutoaccept);
  576. NET_EVENT_HANDLER;
  577. int sel = 0;
  578. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  579. % components.size() % text));
  580. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  581. sel = static_cast<int>(components.size());
  582. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  583. sel = 1;
  584. executeActionAsync("showBlockingDialog", [this, askID, sel]()
  585. {
  586. answerQuery(askID, sel);
  587. });
  588. }
  589. void VCAI::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  590. {
  591. // LOG_TRACE_PARAMS(logAi, "askID '%i', exits '%s'", askID % exits);
  592. NET_EVENT_HANDLER;
  593. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits")
  594. % exits.size()));
  595. int chosenExit = -1;
  596. if(impassable)
  597. {
  598. knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  599. }
  600. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.isValid())
  601. {
  602. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  603. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  604. chosenExit = vstd::find_pos(exits, neededExit);
  605. }
  606. for(auto exit : exits)
  607. {
  608. if(status.channelProbing() && exit.first == destinationTeleport)
  609. {
  610. chosenExit = vstd::find_pos(exits, exit);
  611. break;
  612. }
  613. else
  614. {
  615. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  616. // So far this is the best option to handle decision about probing
  617. auto obj = cb->getObj(exit.first, false);
  618. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  619. {
  620. if(exit.first != destinationTeleport)
  621. teleportChannelProbingList.push_back(exit.first);
  622. }
  623. }
  624. }
  625. executeActionAsync("showTeleportDialog", [this, askID, chosenExit]()
  626. {
  627. answerQuery(askID, chosenExit);
  628. });
  629. }
  630. void VCAI::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  631. {
  632. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  633. NET_EVENT_HANDLER;
  634. std::string s1 = up ? up->nodeName() : "NONE";
  635. std::string s2 = down ? down->nodeName() : "NONE";
  636. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  637. //you can't request action from action-response thread
  638. executeActionAsync("showGarrisonDialog", [this, down, up, removableUnits, queryID]()
  639. {
  640. if(removableUnits && !cb->getStartInfo()->isRestorationOfErathiaCampaign())
  641. pickBestCreatures(down, up);
  642. answerQuery(queryID, 0);
  643. });
  644. }
  645. void VCAI::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  646. {
  647. NET_EVENT_HANDLER;
  648. status.addQuery(askID, "Map object select query");
  649. executeActionAsync("showMapObjectSelectDialog", [this, askID](){ answerQuery(askID, selectedObject.getNum()); });
  650. }
  651. void makePossibleUpgrades(const CArmedInstance * obj)
  652. {
  653. if(!obj)
  654. return;
  655. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  656. {
  657. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  658. {
  659. UpgradeInfo upgradeInfo(s->getId());
  660. do
  661. {
  662. cb->fillUpgradeInfo(obj, SlotID(i), upgradeInfo);
  663. if(upgradeInfo.hasUpgrades())
  664. {
  665. // creature at given slot might have alternative upgrades, pick best one
  666. CreatureID upgID = *vstd::maxElementByFun(upgradeInfo.getAvailableUpgrades(), [](const CreatureID & id)
  667. {
  668. return id.toCreature()->getAIValue();
  669. });
  670. if(cb->getResourceAmount().canAfford(upgradeInfo.getUpgradeCostsFor(upgID) * s->getCount()))
  671. {
  672. cb->upgradeCreature(obj, SlotID(i), upgID);
  673. logAi->debug("Upgraded %d %s to %s", s->getCount(), upgradeInfo.oldID.toCreature()->getNamePluralTranslated(),
  674. upgradeInfo.getUpgrade().toCreature()->getNamePluralTranslated());
  675. }
  676. else
  677. break;
  678. }
  679. }
  680. while(upgradeInfo.hasUpgrades());
  681. }
  682. }
  683. }
  684. void VCAI::makeTurn()
  685. {
  686. MAKING_TURN;
  687. auto day = cb->getDate(Date::DAY);
  688. logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.toString(), day);
  689. std::shared_lock gsLock(CGameState::mutex);
  690. setThreadName("VCAI::makeTurn");
  691. switch(cb->getDate(Date::DAY_OF_WEEK))
  692. {
  693. case 1:
  694. {
  695. townVisitsThisWeek.clear();
  696. std::vector<const CGObjectInstance *> objs;
  697. retrieveVisitableObjs(objs, true);
  698. for(const CGObjectInstance * obj : objs)
  699. {
  700. if(isWeeklyRevisitable(obj))
  701. {
  702. addVisitableObj(obj);
  703. vstd::erase_if_present(alreadyVisited, obj);
  704. }
  705. }
  706. break;
  707. }
  708. }
  709. markHeroAbleToExplore(primaryHero());
  710. visitedHeroes.clear();
  711. try
  712. {
  713. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  714. for (const CGTownInstance * t : cb->getTownsInfo())
  715. moveCreaturesToHero(t);
  716. mainLoop();
  717. /*Below function is also responsible for hero movement via internal wander function. By design it is separate logic for heroes that have nothing to do.
  718. Heroes that were not picked by striveToGoal(sptr(Goals::Win())); recently (so they do not have new goals and cannot continue/reevaluate previously locked goals) will do logic in wander().*/
  719. performTypicalActions();
  720. //for debug purpose
  721. for (auto h : cb->getHeroesInfo())
  722. {
  723. if (h->movementPointsRemaining())
  724. logAi->info("Hero %s has %d MP left", h->getNameTranslated(), h->movementPointsRemaining());
  725. }
  726. }
  727. catch (const TerminationRequestedException &)
  728. {
  729. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  730. return;
  731. }
  732. catch (std::exception & e)
  733. {
  734. logAi->debug("Making turn thread has caught an exception: %s", e.what());
  735. }
  736. endTurn();
  737. }
  738. std::vector<HeroPtr> VCAI::getMyHeroes() const
  739. {
  740. std::vector<HeroPtr> ret;
  741. for(auto h : cb->getHeroesInfo())
  742. {
  743. ret.push_back(h);
  744. }
  745. return ret;
  746. }
  747. void VCAI::mainLoop()
  748. {
  749. std::vector<Goals::TSubgoal> elementarGoals; //no duplicates allowed (operator ==)
  750. basicGoals.clear();
  751. validateVisitableObjs();
  752. //get all potential and saved goals
  753. //TODO: not lose
  754. basicGoals.push_back(sptr(Goals::Win()));
  755. for (auto goalPair : lockedHeroes)
  756. {
  757. fh->setPriority(goalPair.second); //re-evaluate, as heroes moved in the meantime
  758. basicGoals.push_back(goalPair.second);
  759. }
  760. if (ah->hasTasksLeft())
  761. basicGoals.push_back(ah->whatToDo());
  762. for (auto quest : myCb->getMyQuests())
  763. {
  764. basicGoals.push_back(sptr(Goals::CompleteQuest(quest)));
  765. }
  766. basicGoals.push_back(sptr(Goals::Build()));
  767. invalidPathHeroes.clear();
  768. for (int pass = 0; pass< 30 && basicGoals.size(); pass++)
  769. {
  770. vstd::removeDuplicates(basicGoals); //TODO: container which does this automagically without has would be nice
  771. goalsToAdd.clear();
  772. goalsToRemove.clear();
  773. elementarGoals.clear();
  774. ultimateGoalsFromBasic.clear();
  775. ah->updatePaths(getMyHeroes());
  776. logAi->debug("Main loop: decomposing %i basic goals", basicGoals.size());
  777. for (auto basicGoal : basicGoals)
  778. {
  779. logAi->debug("Main loop: decomposing basic goal %s", basicGoal->name());
  780. auto goalToDecompose = basicGoal;
  781. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  782. int maxAbstractGoals = 10;
  783. while (!elementarGoal->isElementar && maxAbstractGoals)
  784. {
  785. try
  786. {
  787. elementarGoal = decomposeGoal(goalToDecompose);
  788. }
  789. catch (goalFulfilledException & e)
  790. {
  791. //it is impossible to continue some goals (like exploration, for example)
  792. //complete abstract goal for now, but maybe main goal finds another path
  793. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  794. completeGoal(e.goal); //put in goalsToRemove
  795. break;
  796. }
  797. catch(cannotFulfillGoalException & e)
  798. {
  799. //it is impossible to continue some goals (like exploration, for example)
  800. //complete abstract goal for now, but maybe main goal finds another path
  801. goalsToRemove.push_back(basicGoal);
  802. logAi->debug("Goal %s decomposition failed: %s", goalToDecompose->name(), e.what());
  803. break;
  804. }
  805. catch (std::exception & e) //decomposition failed, which means we can't decompose entire tree
  806. {
  807. goalsToRemove.push_back(basicGoal);
  808. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  809. break;
  810. }
  811. if (elementarGoal->isAbstract) //we can decompose it further
  812. {
  813. goalsToAdd.push_back(elementarGoal);
  814. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  815. goalToDecompose = elementarGoal;
  816. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  817. maxAbstractGoals--;
  818. }
  819. else if (elementarGoal->isElementar) //should be
  820. {
  821. logAi->debug("Found elementar goal %s", elementarGoal->name());
  822. elementarGoals.push_back(elementarGoal);
  823. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  824. break;
  825. }
  826. else //should never be here
  827. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  828. }
  829. }
  830. logAi->trace("Main loop: selecting best elementar goal");
  831. //now choose one elementar goal to realize
  832. Goals::TGoalVec possibleGoals(elementarGoals.begin(), elementarGoals.end()); //copy to vector
  833. Goals::TSubgoal goalToRealize = sptr(Goals::Invalid());
  834. while (possibleGoals.size())
  835. {
  836. //allow assign goals to heroes with 0 movement, but don't realize them
  837. //maybe there are better ones left
  838. auto bestGoal = fh->chooseSolution(possibleGoals);
  839. if (bestGoal->hero) //lock this hero to fulfill goal
  840. {
  841. setGoal(bestGoal->hero, bestGoal);
  842. if (!bestGoal->hero->movementPointsRemaining() || vstd::contains(invalidPathHeroes, bestGoal->hero))
  843. {
  844. if (!vstd::erase_if_present(possibleGoals, bestGoal))
  845. {
  846. logAi->error("erase_if_preset failed? Something very wrong!");
  847. break;
  848. }
  849. continue; //chose next from the list
  850. }
  851. }
  852. goalToRealize = bestGoal; //we found our goal to execute
  853. break;
  854. }
  855. //realize best goal
  856. if (!goalToRealize->invalid())
  857. {
  858. logAi->debug("Trying to realize %s (value %2.3f)", goalToRealize->name(), goalToRealize->priority);
  859. try
  860. {
  861. makingTurnInterrupption.interruptionPoint();
  862. goalToRealize->accept(this); //visitor pattern
  863. makingTurnInterrupption.interruptionPoint();
  864. }
  865. catch (const TerminationRequestedException &)
  866. {
  867. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  868. throw; //rethrow, we want to truly end this thread
  869. }
  870. catch (const goalFulfilledException & e)
  871. {
  872. //the sub-goal was completed successfully
  873. completeGoal(e.goal);
  874. //local goal was also completed?
  875. completeGoal(goalToRealize);
  876. // remove abstract visit tile if we completed the elementar one
  877. vstd::erase_if_present(goalsToAdd, goalToRealize);
  878. }
  879. catch (const std::exception & e)
  880. {
  881. logAi->debug("Failed to realize subgoal of type %s, I will stop.", goalToRealize->name());
  882. logAi->debug("The error message was: %s", e.what());
  883. //erase base goal if we failed to execute decomposed goal
  884. for (auto basicGoal : ultimateGoalsFromBasic[goalToRealize])
  885. goalsToRemove.push_back(basicGoal);
  886. // sometimes resource manager contains an elementar goal which is not able to execute anymore and just fails each turn.
  887. ai->ah->notifyGoalCompleted(goalToRealize);
  888. //we failed to realize best goal, but maybe others are still possible?
  889. }
  890. //remove goals we couldn't decompose
  891. for (auto goal : goalsToRemove)
  892. vstd::erase_if_present(basicGoals, goal);
  893. //add abstract goals
  894. boost::sort(goalsToAdd, [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  895. {
  896. return lhs->priority > rhs->priority; //highest priority at the beginning
  897. });
  898. //max number of goals = 10
  899. int i = 0;
  900. while (basicGoals.size() < 10 && goalsToAdd.size() > i)
  901. {
  902. if (!vstd::contains(basicGoals, goalsToAdd[i])) //don't add duplicates
  903. basicGoals.push_back(goalsToAdd[i]);
  904. i++;
  905. }
  906. }
  907. else //no elementar goals possible
  908. {
  909. logAi->debug("Goal decomposition exhausted");
  910. break;
  911. }
  912. }
  913. }
  914. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  915. {
  916. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->getNameTranslated() % obj->getObjectName() % obj->anchorPos().toString());
  917. switch(obj->ID)
  918. {
  919. case Obj::TOWN:
  920. moveCreaturesToHero(dynamic_cast<const CGTownInstance *>(obj));
  921. if(h->getVisitedTown()) //we are inside, not just attacking
  922. {
  923. townVisitsThisWeek[h].insert(h->getVisitedTown());
  924. if(!h->hasSpellbook() && ah->freeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  925. {
  926. if(h->getVisitedTown()->hasBuilt(BuildingID::MAGES_GUILD_1))
  927. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  928. }
  929. }
  930. break;
  931. }
  932. completeGoal(sptr(Goals::VisitObj(obj->id.getNum()).sethero(h)));
  933. }
  934. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  935. {
  936. if(t->getVisitingHero() && t->armedGarrison() && t->getVisitingHero()->tempOwner == t->tempOwner)
  937. {
  938. pickBestCreatures(t->getVisitingHero(), t);
  939. }
  940. }
  941. void VCAI::pickBestCreatures(const CArmedInstance * destinationArmy, const CArmedInstance * source)
  942. {
  943. const CArmedInstance * armies[] = {destinationArmy, source};
  944. auto bestArmy = ah->getSortedSlots(destinationArmy, source);
  945. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  946. for(SlotID i = SlotID(0); i.getNum() < bestArmy.size() && i.validSlot(); i.advance(1)) //i-th strongest creature type will go to i-th slot
  947. {
  948. const CCreature * targetCreature = bestArmy[i.getNum()].creature;
  949. for(auto armyPtr : armies)
  950. {
  951. for(SlotID j = SlotID(0); j.validSlot(); j.advance(1))
  952. {
  953. if(armyPtr->getCreature(j) == targetCreature && (i != j || armyPtr != destinationArmy)) //it's a searched creature not in dst SLOT
  954. {
  955. //can't take away last creature without split. generate a new stack with 1 creature which is weak but fast
  956. if(armyPtr == source
  957. && source->needsLastStack()
  958. && source->stacksCount() == 1
  959. && (!destinationArmy->hasStackAtSlot(i) || destinationArmy->getCreature(i) == targetCreature))
  960. {
  961. auto weakest = ah->getWeakestCreature(bestArmy);
  962. if(weakest->creature == targetCreature)
  963. {
  964. if(1 == source->getStackCount(j))
  965. break;
  966. // move all except 1 of weakest creature from source to destination
  967. cb->splitStack(
  968. source,
  969. destinationArmy,
  970. j,
  971. destinationArmy->getSlotFor(targetCreature),
  972. destinationArmy->getStackCount(i) + source->getStackCount(j) - 1);
  973. break;
  974. }
  975. else
  976. {
  977. // Source last stack is not weakest. Move 1 of weakest creature from destination to source
  978. cb->splitStack(
  979. destinationArmy,
  980. source,
  981. destinationArmy->getSlotFor(weakest->creature),
  982. source->getFreeSlot(),
  983. 1);
  984. }
  985. }
  986. cb->mergeOrSwapStacks(armyPtr, destinationArmy, j, i);
  987. }
  988. }
  989. }
  990. }
  991. //TODO - having now strongest possible army, we may want to think about arranging stacks
  992. auto hero = dynamic_cast<const CGHeroInstance *>(destinationArmy);
  993. if(hero)
  994. checkHeroArmy(hero);
  995. }
  996. void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  997. {
  998. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  999. {
  1000. bool changeMade = false;
  1001. do
  1002. {
  1003. changeMade = false;
  1004. //we collect gear always in same order
  1005. std::vector<ArtifactLocation> allArtifacts;
  1006. if(giveStuffToFirstHero)
  1007. {
  1008. for(auto p : h->artifactsWorn)
  1009. {
  1010. if(p.second.getArt())
  1011. allArtifacts.push_back(ArtifactLocation(h->id, p.first));
  1012. }
  1013. }
  1014. for(auto slot : h->artifactsInBackpack)
  1015. allArtifacts.push_back(ArtifactLocation(h->id, h->getArtPos(slot.getArt())));
  1016. if(otherh)
  1017. {
  1018. for(auto p : otherh->artifactsWorn)
  1019. {
  1020. if(p.second.getArt())
  1021. allArtifacts.push_back(ArtifactLocation(otherh->id, p.first));
  1022. }
  1023. for(auto slot : otherh->artifactsInBackpack)
  1024. allArtifacts.push_back(ArtifactLocation(otherh->id, otherh->getArtPos(slot.getArt())));
  1025. }
  1026. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  1027. const CGHeroInstance * target = nullptr;
  1028. if(giveStuffToFirstHero || !otherh)
  1029. target = h;
  1030. else
  1031. target = otherh;
  1032. for(auto location : allArtifacts)
  1033. {
  1034. if(location.slot == ArtifactPosition::MACH4 || location.slot == ArtifactPosition::SPELLBOOK)
  1035. continue; // don't attempt to move catapult and spellbook
  1036. if(location.artHolder == target->id && ArtifactUtils::isSlotEquipment(location.slot))
  1037. continue; //don't reequip artifact we already wear
  1038. auto s = cb->getHero(location.artHolder)->getSlot(location.slot);
  1039. if(!s || s->locked) //we can't move locks
  1040. continue;
  1041. auto artifact = s->getArt();
  1042. if(!artifact)
  1043. continue;
  1044. //FIXME: why are the above possible to be null?
  1045. bool emptySlotFound = false;
  1046. for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
  1047. {
  1048. if(target->isPositionFree(slot) && artifact->canBePutAt(target, slot, true)) //combined artifacts are not always allowed to move
  1049. {
  1050. ArtifactLocation destLocation(target->id, slot);
  1051. cb->swapArtifacts(location, destLocation); //just put into empty slot
  1052. emptySlotFound = true;
  1053. changeMade = true;
  1054. break;
  1055. }
  1056. }
  1057. if(!emptySlotFound) //try to put that atifact in already occupied slot
  1058. {
  1059. for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
  1060. {
  1061. auto otherSlot = target->getSlot(slot);
  1062. if(otherSlot && otherSlot->getArt()) //we need to exchange artifact for better one
  1063. {
  1064. //if that artifact is better than what we have, pick it
  1065. if(compareArtifacts(artifact, otherSlot->getArt()) && artifact->canBePutAt(target, slot, true)) //combined artifacts are not always allowed to move
  1066. {
  1067. ArtifactLocation destLocation(target->id, slot);
  1068. cb->swapArtifacts(location, ArtifactLocation(target->id, target->getArtPos(otherSlot->getArt())));
  1069. changeMade = true;
  1070. break;
  1071. }
  1072. }
  1073. }
  1074. }
  1075. if(changeMade)
  1076. break; //start evaluating artifacts from scratch
  1077. }
  1078. }
  1079. while(changeMade);
  1080. };
  1081. equipBest(h, other, true);
  1082. if(other)
  1083. equipBest(h, other, false);
  1084. }
  1085. void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  1086. {
  1087. //now used only for visited dwellings / towns, not BuyArmy goal
  1088. for(int i = 0; i < d->creatures.size(); i++)
  1089. {
  1090. if(!d->creatures[i].second.size())
  1091. continue;
  1092. int count = d->creatures[i].first;
  1093. CreatureID creID = d->creatures[i].second.back();
  1094. vstd::amin(count, ah->freeResources() / LIBRARY->creatures()->getById(creID)->getFullRecruitCost());
  1095. if(count > 0)
  1096. cb->recruitCreatures(d, recruiter, creID, count, i);
  1097. }
  1098. }
  1099. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional<float> movementCostLimit)
  1100. {
  1101. int3 op = obj->visitablePos();
  1102. auto paths = ah->getPathsToTile(h, op);
  1103. for(const auto & path : paths)
  1104. {
  1105. if(movementCostLimit && movementCostLimit.value() < path.movementCost())
  1106. return false;
  1107. if(isGoodForVisit(obj, h, path))
  1108. return true;
  1109. }
  1110. return false;
  1111. }
  1112. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const
  1113. {
  1114. const int3 pos = obj->visitablePos();
  1115. const int3 targetPos = path.firstTileToGet();
  1116. if (!targetPos.isValid())
  1117. return false;
  1118. if (!isTileNotReserved(h.get(), targetPos))
  1119. return false;
  1120. if (obj->wasVisited(playerID))
  1121. return false;
  1122. if (cb->getPlayerRelations(playerID, obj->tempOwner) != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
  1123. return false; // Otherwise we flag or get weekly resources / creatures
  1124. if (!isSafeToVisit(h, pos))
  1125. return false;
  1126. if (!shouldVisit(h, obj))
  1127. return false;
  1128. if (vstd::contains(alreadyVisited, obj))
  1129. return false;
  1130. if (vstd::contains(reservedObjs, obj))
  1131. return false;
  1132. // TODO: looks extra if we already have AIPath
  1133. //if (!isAccessibleForHero(targetPos, h))
  1134. // return false;
  1135. const CGObjectInstance * topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
  1136. //we don't try visiting object on which allied or owned hero stands
  1137. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1138. return !(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES); //all of the following is met
  1139. }
  1140. bool VCAI::isTileNotReserved(const CGHeroInstance * h, int3 t) const
  1141. {
  1142. if(t.isValid())
  1143. {
  1144. auto obj = cb->getTopObj(t);
  1145. if(obj && vstd::contains(ai->reservedObjs, obj)
  1146. && vstd::contains(reservedHeroesMap, h)
  1147. && !vstd::contains(reservedHeroesMap.at(h), obj))
  1148. return false; //do not capture object reserved by another hero
  1149. else
  1150. return true;
  1151. }
  1152. else
  1153. {
  1154. return false;
  1155. }
  1156. }
  1157. bool VCAI::canRecruitAnyHero(const CGTownInstance * t) const
  1158. {
  1159. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  1160. if(!t)
  1161. t = findTownWithTavern();
  1162. if(!t)
  1163. return false;
  1164. if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST) //TODO: use ResourceManager
  1165. return false;
  1166. if(cb->getHeroesInfo().size() >= cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  1167. return false;
  1168. if(!cb->getAvailableHeroes(t).size())
  1169. return false;
  1170. return true;
  1171. }
  1172. void VCAI::wander(HeroPtr h)
  1173. {
  1174. auto visitTownIfAny = [this](HeroPtr h) -> bool
  1175. {
  1176. if (h->getVisitedTown())
  1177. {
  1178. townVisitsThisWeek[h].insert(h->getVisitedTown());
  1179. buildArmyIn(h->getVisitedTown());
  1180. return true;
  1181. }
  1182. return false;
  1183. };
  1184. //unclaim objects that are now dangerous for us
  1185. auto reservedObjsSetCopy = reservedHeroesMap[h];
  1186. for(auto obj : reservedObjsSetCopy)
  1187. {
  1188. if(!isSafeToVisit(h, obj->visitablePos()))
  1189. unreserveObject(h, obj);
  1190. }
  1191. TimeCheck tc("looking for wander destination");
  1192. for(int k = 0; k < 10 && h->movementPointsRemaining(); k++)
  1193. {
  1194. validateVisitableObjs();
  1195. ah->updatePaths(getMyHeroes());
  1196. std::vector<ObjectIdRef> dests;
  1197. //also visit our reserved objects - but they are not prioritized to avoid running back and forth
  1198. vstd::copy_if(reservedHeroesMap[h], std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1199. {
  1200. return ah->isTileAccessible(h, obj->visitablePos());
  1201. });
  1202. int pass = 0;
  1203. std::vector<std::optional<float>> distanceLimits = {1.0, 2.0, std::nullopt};
  1204. while(!dests.size() && pass < distanceLimits.size())
  1205. {
  1206. auto & distanceLimit = distanceLimits[pass];
  1207. logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.value_or(-1.0));
  1208. vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1209. {
  1210. return isGoodForVisit(obj, h, distanceLimit);
  1211. });
  1212. pass++;
  1213. }
  1214. if(!dests.size())
  1215. {
  1216. logAi->debug("Looking for town destination");
  1217. if(cb->getVisitableObjs(h->visitablePos()).size() > 1)
  1218. moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
  1219. auto compareReinforcements = [&](const CGTownInstance * lhs, const CGTownInstance * rhs) -> bool
  1220. {
  1221. const CGHeroInstance * hptr = h.get();
  1222. auto r1 = ah->howManyReinforcementsCanGet(hptr, lhs);
  1223. auto r2 = ah->howManyReinforcementsCanGet(hptr, rhs);
  1224. if (r1 != r2)
  1225. return r1 < r2;
  1226. else
  1227. return ah->howManyReinforcementsCanBuy(hptr, lhs) < ah->howManyReinforcementsCanBuy(hptr, rhs);
  1228. };
  1229. std::vector<const CGTownInstance *> townsReachable;
  1230. std::vector<const CGTownInstance *> townsNotReachable;
  1231. for(const CGTownInstance * t : cb->getTownsInfo())
  1232. {
  1233. if(!t->getVisitingHero() && !vstd::contains(townVisitsThisWeek[h], t))
  1234. {
  1235. if(isAccessibleForHero(t->visitablePos(), h))
  1236. townsReachable.push_back(t);
  1237. else
  1238. townsNotReachable.push_back(t);
  1239. }
  1240. }
  1241. if(townsReachable.size()) //travel to town with largest garrison, or empty - better than nothing
  1242. {
  1243. dests.push_back(*boost::max_element(townsReachable, compareReinforcements));
  1244. }
  1245. else if(townsNotReachable.size())
  1246. {
  1247. //TODO pick the truly best
  1248. const CGTownInstance * t = *boost::max_element(townsNotReachable, compareReinforcements);
  1249. logAi->debug("%s can't reach any town, we'll try to make our way to %s at %s", h->getNameTranslated(), t->getNameTranslated(), t->visitablePos().toString());
  1250. int3 posBefore = h->visitablePos();
  1251. striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h))); //TODO: drop "strive", add to mainLoop
  1252. //if out hero is stuck, we may need to request another hero to clear the way we see
  1253. if(posBefore == h->visitablePos() && h == primaryHero()) //hero can't move
  1254. {
  1255. if(canRecruitAnyHero(t))
  1256. recruitHero(t);
  1257. }
  1258. break;
  1259. }
  1260. else if(cb->getResourceAmount(EGameResID::GOLD) >= GameConstants::HERO_GOLD_COST)
  1261. {
  1262. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1263. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  1264. {
  1265. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1266. {
  1267. if(!t->getArmyStrength() || ah->howManyReinforcementsCanGet(h, t))
  1268. return true;
  1269. }
  1270. return false;
  1271. });
  1272. if (towns.size())
  1273. {
  1274. recruitHero(*boost::max_element(towns, compareArmyStrength));
  1275. }
  1276. break;
  1277. }
  1278. else
  1279. {
  1280. logAi->debug("Nowhere more to go...");
  1281. break;
  1282. }
  1283. }
  1284. //end of objs empty
  1285. if(dests.size()) //performance improvement
  1286. {
  1287. Goals::TGoalVec targetObjectGoals;
  1288. for(auto destination : dests)
  1289. {
  1290. vstd::concatenate(targetObjectGoals, ah->howToVisitObj(h, destination, false));
  1291. }
  1292. if(targetObjectGoals.size())
  1293. {
  1294. auto bestObjectGoal = fh->chooseSolution(targetObjectGoals);
  1295. //wander should not cause heroes to be reserved - they are always considered free
  1296. if(bestObjectGoal->goalType == Goals::VISIT_OBJ)
  1297. {
  1298. auto chosenObject = cb->getObjInstance(ObjectInstanceID(bestObjectGoal->objid));
  1299. if(chosenObject != nullptr)
  1300. logAi->debug("Of all %d destinations, object %s at pos=%s seems nice", dests.size(), chosenObject->getObjectName(), chosenObject->anchorPos().toString());
  1301. }
  1302. else
  1303. logAi->debug("Trying to realize goal of type %s as part of wandering.", bestObjectGoal->name());
  1304. try
  1305. {
  1306. decomposeGoal(bestObjectGoal)->accept(this);
  1307. }
  1308. catch(const goalFulfilledException & e)
  1309. {
  1310. if(e.goal->goalType == Goals::EGoals::VISIT_TILE || e.goal->goalType == Goals::EGoals::VISIT_OBJ)
  1311. continue;
  1312. throw;
  1313. }
  1314. }
  1315. else
  1316. {
  1317. logAi->debug("Nowhere more to go...");
  1318. break;
  1319. }
  1320. visitTownIfAny(h);
  1321. }
  1322. }
  1323. visitTownIfAny(h); //in case hero is just sitting in town
  1324. }
  1325. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1326. {
  1327. if(goal->invalid())
  1328. {
  1329. vstd::erase_if_present(lockedHeroes, h);
  1330. }
  1331. else
  1332. {
  1333. lockedHeroes[h] = goal;
  1334. goal->setisElementar(false); //Force always evaluate goals before realizing
  1335. }
  1336. }
  1337. void VCAI::evaluateGoal(HeroPtr h)
  1338. {
  1339. if(vstd::contains(lockedHeroes, h))
  1340. fh->setPriority(lockedHeroes[h]);
  1341. }
  1342. void VCAI::completeGoal(Goals::TSubgoal goal)
  1343. {
  1344. if (goal->goalType == Goals::WIN) //we can never complete this goal - unless we already won
  1345. return;
  1346. logAi->debug("Completing goal: %s", goal->name());
  1347. //notify Managers
  1348. ah->notifyGoalCompleted(goal);
  1349. //notify mainLoop()
  1350. goalsToRemove.push_back(goal); //will be removed from mainLoop() goals
  1351. for (auto basicGoal : basicGoals) //we could luckily fulfill any of our goals
  1352. {
  1353. if (basicGoal->fulfillsMe(goal))
  1354. goalsToRemove.push_back(basicGoal);
  1355. }
  1356. //unreserve heroes
  1357. if(const CGHeroInstance * h = goal->hero.get(true))
  1358. {
  1359. auto it = lockedHeroes.find(h);
  1360. if(it != lockedHeroes.end())
  1361. {
  1362. if(it->second == goal || it->second->fulfillsMe(goal)) //FIXME this is overspecified, fulfillsMe should be complete
  1363. {
  1364. logAi->debug(goal->completeMessage());
  1365. lockedHeroes.erase(it); //goal fulfilled, free hero
  1366. }
  1367. }
  1368. }
  1369. else //complete goal for all heroes maybe?
  1370. {
  1371. vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
  1372. {
  1373. if(p.second == goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1374. {
  1375. logAi->debug(p.second->completeMessage());
  1376. return true;
  1377. }
  1378. return false;
  1379. });
  1380. }
  1381. }
  1382. void VCAI::battleStart(const BattleID & battleID, const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, BattleSide side, bool replayAllowed)
  1383. {
  1384. NET_EVENT_HANDLER;
  1385. assert(!playerID.isValidPlayer() || status.getBattle() == UPCOMING_BATTLE);
  1386. status.setBattle(ONGOING_BATTLE);
  1387. 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
  1388. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->getNameTranslated() : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile.toString());
  1389. CAdventureAI::battleStart(battleID, army1, army2, tile, hero1, hero2, side, replayAllowed);
  1390. }
  1391. void VCAI::battleEnd(const BattleID & battleID, const BattleResult * br, QueryID queryID)
  1392. {
  1393. NET_EVENT_HANDLER;
  1394. assert(status.getBattle() == ONGOING_BATTLE);
  1395. status.setBattle(ENDING_BATTLE);
  1396. bool won = br->winner == myCb->getBattle(battleID)->battleGetMySide();
  1397. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.toString(), (won ? "won" : "lost"), battlename);
  1398. battlename.clear();
  1399. CAdventureAI::battleEnd(battleID, br, queryID);
  1400. }
  1401. void VCAI::waitTillFree()
  1402. {
  1403. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  1404. status.waitTillFree();
  1405. }
  1406. void VCAI::markObjectVisited(const CGObjectInstance * obj)
  1407. {
  1408. if(!obj)
  1409. return;
  1410. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj)) //we may want to visit it with another hero
  1411. {
  1412. if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_HERO) //we may want to visit it with another hero
  1413. return;
  1414. if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_BONUS) //or another time
  1415. return;
  1416. }
  1417. if(obj->ID == Obj::MONSTER)
  1418. return;
  1419. alreadyVisited.insert(obj);
  1420. }
  1421. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance * obj)
  1422. {
  1423. reservedObjs.insert(obj);
  1424. reservedHeroesMap[h].insert(obj);
  1425. logAi->debug("reserved object id=%d; address=%p; name=%s", obj->id, obj, obj->getObjectName());
  1426. }
  1427. void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance * obj)
  1428. {
  1429. vstd::erase_if_present(reservedObjs, obj); //unreserve objects
  1430. vstd::erase_if_present(reservedHeroesMap[h], obj);
  1431. }
  1432. void VCAI::markHeroUnableToExplore(HeroPtr h)
  1433. {
  1434. heroesUnableToExplore.insert(h);
  1435. }
  1436. void VCAI::markHeroAbleToExplore(HeroPtr h)
  1437. {
  1438. vstd::erase_if_present(heroesUnableToExplore, h);
  1439. }
  1440. bool VCAI::isAbleToExplore(HeroPtr h)
  1441. {
  1442. return !vstd::contains(heroesUnableToExplore, h);
  1443. }
  1444. void VCAI::clearPathsInfo()
  1445. {
  1446. heroesUnableToExplore.clear();
  1447. }
  1448. void VCAI::validateVisitableObjs()
  1449. {
  1450. std::string errorMsg;
  1451. auto shouldBeErased = [&](const CGObjectInstance * obj) -> bool
  1452. {
  1453. if(obj)
  1454. return !cb->getObj(obj->id, false); // no verbose output needed as we check object visibility
  1455. else
  1456. return true;
  1457. };
  1458. //errorMsg is captured by ref so lambda will take the new text
  1459. errorMsg = " shouldn't be on the visitable objects list!";
  1460. vstd::erase_if(visitableObjs, shouldBeErased);
  1461. //FIXME: how comes our own heroes become inaccessible?
  1462. vstd::erase_if(reservedHeroesMap, [](std::pair<HeroPtr, std::set<const CGObjectInstance *>> hp) -> bool
  1463. {
  1464. return !hp.first.get(true);
  1465. });
  1466. for(auto & p : reservedHeroesMap)
  1467. {
  1468. errorMsg = " shouldn't be on list for hero " + p.first->getNameTranslated() + "!";
  1469. vstd::erase_if(p.second, shouldBeErased);
  1470. }
  1471. errorMsg = " shouldn't be on the reserved objs list!";
  1472. vstd::erase_if(reservedObjs, shouldBeErased);
  1473. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1474. errorMsg = " shouldn't be on the already visited objs list!";
  1475. vstd::erase_if(alreadyVisited, shouldBeErased);
  1476. }
  1477. void VCAI::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
  1478. {
  1479. foreach_tile_pos([&](const int3 & pos)
  1480. {
  1481. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1482. {
  1483. if(includeOwned || obj->tempOwner != playerID)
  1484. out.push_back(obj);
  1485. }
  1486. });
  1487. }
  1488. void VCAI::retrieveVisitableObjs()
  1489. {
  1490. foreach_tile_pos([&](const int3 & pos)
  1491. {
  1492. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1493. {
  1494. if(obj->tempOwner != playerID)
  1495. addVisitableObj(obj);
  1496. }
  1497. });
  1498. }
  1499. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1500. {
  1501. std::vector<const CGObjectInstance *> ret;
  1502. for(const CGObjectInstance * obj : visitableObjs)
  1503. {
  1504. if(obj->tempOwner == playerID)
  1505. ret.push_back(obj);
  1506. }
  1507. return ret;
  1508. }
  1509. void VCAI::addVisitableObj(const CGObjectInstance * obj)
  1510. {
  1511. if(obj->ID == Obj::EVENT)
  1512. return;
  1513. visitableObjs.insert(obj);
  1514. // All teleport objects seen automatically assigned to appropriate channels
  1515. auto teleportObj = dynamic_cast<const CGTeleport *>(obj);
  1516. if(teleportObj)
  1517. CGTeleport::addToChannel(knownTeleportChannels, teleportObj);
  1518. }
  1519. const CGObjectInstance * VCAI::lookForArt(ArtifactID aid) const
  1520. {
  1521. for(const CGObjectInstance * obj : ai->visitableObjs)
  1522. {
  1523. if(obj->ID == Obj::ARTIFACT && dynamic_cast<const CGArtifact *>(obj)->getArtifactType() == aid)
  1524. return obj;
  1525. }
  1526. return nullptr;
  1527. //TODO what if more than one artifact is available? return them all or some selection criteria
  1528. }
  1529. bool VCAI::isAccessible(const int3 & pos) const
  1530. {
  1531. //TODO precalculate for speed
  1532. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1533. {
  1534. if(isAccessibleForHero(pos, h))
  1535. return true;
  1536. }
  1537. return false;
  1538. }
  1539. HeroPtr VCAI::getHeroWithGrail() const
  1540. {
  1541. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1542. {
  1543. if(h->hasArt(ArtifactID::GRAIL))
  1544. return h;
  1545. }
  1546. return nullptr;
  1547. }
  1548. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate)
  1549. {
  1550. //TODO smarter definition of unvisited
  1551. for(const CGObjectInstance * obj : visitableObjs)
  1552. {
  1553. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1554. return obj;
  1555. }
  1556. return nullptr;
  1557. }
  1558. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies) const
  1559. {
  1560. // Don't visit tile occupied by allied hero
  1561. if(!includeAllies)
  1562. {
  1563. for(auto obj : cb->getVisitableObjs(pos))
  1564. {
  1565. if(obj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES)
  1566. {
  1567. if(obj != h.get())
  1568. return false;
  1569. }
  1570. }
  1571. }
  1572. return getPathsInfo(h.get())->getPathInfo(pos)->reachable();
  1573. }
  1574. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1575. {
  1576. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  1577. auto afterMovementCheck = [&]() -> void
  1578. {
  1579. waitTillFree(); //movement may cause battle or blocking dialog
  1580. if(!h)
  1581. {
  1582. lostHero(h);
  1583. teleportChannelProbingList.clear();
  1584. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  1585. status.setChannelProbing(false);
  1586. throw cannotFulfillGoalException("Hero was lost!");
  1587. }
  1588. };
  1589. logAi->debug("Moving hero %s to tile %s", h->getNameTranslated(), dst.toString());
  1590. int3 startHpos = h->visitablePos();
  1591. bool ret = false;
  1592. if(startHpos == dst)
  1593. {
  1594. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1595. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1596. cb->moveHero(*h, h->convertFromVisitablePos(dst), false);
  1597. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  1598. // If revisiting, teleport probing is never done, and so the entries into the list would remain unused and uncleared
  1599. teleportChannelProbingList.clear();
  1600. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1601. ret = true;
  1602. }
  1603. else
  1604. {
  1605. CGPath path;
  1606. getPathsInfo(h.get())->getPath(path, dst);
  1607. if(path.nodes.empty())
  1608. {
  1609. logAi->error("Hero %s cannot reach %s.", h->getNameTranslated(), dst.toString());
  1610. throw goalFulfilledException(sptr(Goals::VisitTile(dst).sethero(h)));
  1611. }
  1612. int i = (int)path.nodes.size() - 1;
  1613. auto getObj = [&](int3 coord, bool ignoreHero)
  1614. {
  1615. return cb->getObj(cb->getTile(coord)->topVisitableObj(ignoreHero));
  1616. };
  1617. auto isTeleportAction = [&](EPathNodeAction action) -> bool
  1618. {
  1619. if(action != EPathNodeAction::TELEPORT_NORMAL && action != EPathNodeAction::TELEPORT_BLOCKING_VISIT)
  1620. {
  1621. if(action != EPathNodeAction::TELEPORT_BATTLE)
  1622. {
  1623. return false;
  1624. }
  1625. }
  1626. return true;
  1627. };
  1628. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1629. {
  1630. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1631. return nextObjectTop;
  1632. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1633. {
  1634. if(CGTeleport::isConnected(currentObject, nextObject))
  1635. return nextObject;
  1636. }
  1637. return nullptr;
  1638. };
  1639. auto doMovement = [&](int3 dst, bool transit)
  1640. {
  1641. cb->moveHero(*h, h->convertFromVisitablePos(dst), transit);
  1642. };
  1643. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1644. {
  1645. destinationTeleport = exitId;
  1646. if(exitPos.isValid())
  1647. destinationTeleportPos = exitPos;
  1648. cb->moveHero(*h, h->pos, false);
  1649. destinationTeleport = ObjectInstanceID();
  1650. destinationTeleportPos = int3(-1);
  1651. afterMovementCheck();
  1652. };
  1653. auto doChannelProbing = [&]() -> void
  1654. {
  1655. auto currentPos = h->visitablePos();
  1656. auto currentExit = getObj(currentPos, true)->id;
  1657. status.setChannelProbing(true);
  1658. for(auto exit : teleportChannelProbingList)
  1659. doTeleportMovement(exit, int3(-1));
  1660. teleportChannelProbingList.clear();
  1661. status.setChannelProbing(false);
  1662. doTeleportMovement(currentExit, currentPos);
  1663. };
  1664. for(; i > 0; i--)
  1665. {
  1666. int3 currentCoord = path.nodes[i].coord;
  1667. int3 nextCoord = path.nodes[i - 1].coord;
  1668. auto currentObject = getObj(currentCoord, currentCoord == h->visitablePos());
  1669. auto nextObjectTop = getObj(nextCoord, false);
  1670. auto nextObject = getObj(nextCoord, true);
  1671. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1672. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1673. {
  1674. //we use special login if hero standing on teleporter it's mean we need
  1675. doTeleportMovement(destTeleportObj->id, nextCoord);
  1676. if(teleportChannelProbingList.size())
  1677. doChannelProbing();
  1678. markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1679. continue;
  1680. }
  1681. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1682. if(path.nodes[i - 1].turns)
  1683. {
  1684. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1685. break;
  1686. }
  1687. int3 endpos = path.nodes[i - 1].coord;
  1688. if(endpos == h->visitablePos())
  1689. continue;
  1690. bool isConnected = false;
  1691. bool isNextObjectTeleport = false;
  1692. // Check there is node after next one; otherwise transit is pointless
  1693. if(i - 2 >= 0)
  1694. {
  1695. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1696. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1697. }
  1698. if(isConnected || isNextObjectTeleport)
  1699. {
  1700. // Hero should be able to go through object if it's allow transit
  1701. doMovement(endpos, true);
  1702. }
  1703. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1704. {
  1705. doMovement(endpos, true);
  1706. }
  1707. else
  1708. {
  1709. doMovement(endpos, false);
  1710. }
  1711. afterMovementCheck();
  1712. if(teleportChannelProbingList.size())
  1713. doChannelProbing();
  1714. }
  1715. if(path.nodes[0].action == EPathNodeAction::BLOCKING_VISIT)
  1716. {
  1717. ret = h && i == 0; // when we take resource we do not reach its position. We even might not move
  1718. }
  1719. }
  1720. if(h)
  1721. {
  1722. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1723. {
  1724. if(visitedObject != *h)
  1725. performObjectInteraction(visitedObject, h);
  1726. }
  1727. }
  1728. if(h) //we could have lost hero after last move
  1729. {
  1730. completeGoal(sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
  1731. completeGoal(sptr(Goals::ClearWayTo(dst).sethero(h)));
  1732. ret = ret || (dst == h->visitablePos());
  1733. if(!ret) //reserve object we are heading towards
  1734. {
  1735. auto obj = vstd::frontOrNull(cb->getVisitableObjs(dst));
  1736. if(obj && obj != *h)
  1737. reserveObject(h, obj);
  1738. }
  1739. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1740. {
  1741. vstd::erase_if_present(lockedHeroes, h); //hero seemingly is confused or has only 95mp which is not enough to move
  1742. invalidPathHeroes.insert(h);
  1743. throw cannotFulfillGoalException("Invalid path found!");
  1744. }
  1745. evaluateGoal(h); //new hero position means new game situation
  1746. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->getNameTranslated(), startHpos.toString(), h->visitablePos().toString(), ret);
  1747. }
  1748. return ret;
  1749. }
  1750. void VCAI::buildStructure(const CGTownInstance * t, BuildingID building)
  1751. {
  1752. auto name = t->getTown()->buildings.at(building)->getNameTranslated();
  1753. logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->getNameTranslated(), t->anchorPos().toString());
  1754. cb->buildBuilding(t, building); //just do this;
  1755. }
  1756. void VCAI::tryRealize(Goals::Explore & g)
  1757. {
  1758. throw cannotFulfillGoalException("EXPLORE is not an elementar goal!");
  1759. }
  1760. void VCAI::tryRealize(Goals::RecruitHero & g)
  1761. {
  1762. if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST)
  1763. throw cannotFulfillGoalException("Not enough gold to recruit hero!");
  1764. if(const CGTownInstance * t = findTownWithTavern())
  1765. {
  1766. recruitHero(t, true);
  1767. //TODO try to free way to blocked town
  1768. //TODO: adventure map tavern or prison?
  1769. }
  1770. else
  1771. {
  1772. throw cannotFulfillGoalException("No town to recruit hero!");
  1773. }
  1774. }
  1775. void VCAI::tryRealize(Goals::VisitTile & g)
  1776. {
  1777. if(!g.hero->movementPointsRemaining())
  1778. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1779. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1780. {
  1781. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
  1782. throw goalFulfilledException(sptr(g));
  1783. }
  1784. if(ai->moveHeroToTile(g.tile, g.hero.get()))
  1785. {
  1786. throw goalFulfilledException(sptr(g));
  1787. }
  1788. }
  1789. void VCAI::tryRealize(Goals::VisitObj & g)
  1790. {
  1791. auto position = g.tile;
  1792. if(!g.hero->movementPointsRemaining())
  1793. throw cannotFulfillGoalException("Cannot visit object: hero is out of MPs!");
  1794. if(position == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1795. {
  1796. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
  1797. throw goalFulfilledException(sptr(g));
  1798. }
  1799. if(ai->moveHeroToTile(position, g.hero.get()))
  1800. {
  1801. throw goalFulfilledException(sptr(g));
  1802. }
  1803. }
  1804. void VCAI::tryRealize(Goals::VisitHero & g)
  1805. {
  1806. if(!g.hero->movementPointsRemaining())
  1807. throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
  1808. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
  1809. if(obj)
  1810. {
  1811. if(ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
  1812. {
  1813. throw goalFulfilledException(sptr(g));
  1814. }
  1815. }
  1816. else
  1817. {
  1818. throw cannotFulfillGoalException("Cannot visit hero: object not found!");
  1819. }
  1820. }
  1821. void VCAI::tryRealize(Goals::BuildThis & g)
  1822. {
  1823. auto b = BuildingID(g.bid);
  1824. auto t = g.town;
  1825. if (t)
  1826. {
  1827. if (cb->canBuildStructure(t, b) == EBuildingState::ALLOWED)
  1828. {
  1829. logAi->debug("Player %d will build %s in town of %s at %s",
  1830. playerID, t->getTown()->buildings.at(b)->getNameTranslated(), t->getNameTranslated(), t->anchorPos().toString());
  1831. cb->buildBuilding(t, b);
  1832. throw goalFulfilledException(sptr(g));
  1833. }
  1834. }
  1835. throw cannotFulfillGoalException("Cannot build a given structure!");
  1836. }
  1837. void VCAI::tryRealize(Goals::DigAtTile & g)
  1838. {
  1839. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1840. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1841. {
  1842. cb->dig(g.hero.get());
  1843. completeGoal(sptr(g)); // finished digging
  1844. }
  1845. else
  1846. {
  1847. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1848. throw cannotFulfillGoalException("A hero can't dig!\n");
  1849. }
  1850. }
  1851. void VCAI::tryRealize(Goals::Trade & g) //trade
  1852. {
  1853. if(ah->freeResources()[g.resID] >= g.value) //goal is already fulfilled. Why we need this check, anyway?
  1854. throw goalFulfilledException(sptr(g));
  1855. int acquiredResources = 0;
  1856. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1857. {
  1858. if(const auto * m = dynamic_cast<const IMarket*>(obj))
  1859. {
  1860. auto freeRes = ah->freeResources(); //trade only resources which are not reserved
  1861. for(auto it = ResourceSet::nziterator(freeRes); it.valid(); it++)
  1862. {
  1863. auto res = it->resType;
  1864. if(res.getNum() == g.resID) //sell any other resource
  1865. continue;
  1866. int toGive;
  1867. int toGet;
  1868. m->getOffer(res.getNum(), g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1869. toGive = static_cast<int>(toGive * (it->resVal / toGive)); //round down
  1870. //TODO trade only as much as needed
  1871. if (toGive) //don't try to sell 0 resources
  1872. {
  1873. cb->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, res, GameResID(g.resID), toGive);
  1874. acquiredResources = static_cast<int>(toGet * (it->resVal / toGive));
  1875. logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, acquiredResources, g.resID, obj->getObjectName());
  1876. }
  1877. if (ah->freeResources()[g.resID] >= g.value)
  1878. throw goalFulfilledException(sptr(g)); //we traded all we needed
  1879. }
  1880. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1881. }
  1882. else
  1883. {
  1884. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1885. }
  1886. }
  1887. else
  1888. {
  1889. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1890. }
  1891. }
  1892. void VCAI::tryRealize(Goals::BuyArmy & g)
  1893. {
  1894. auto t = g.town;
  1895. ui64 valueBought = 0;
  1896. //buy the stacks with largest AI value
  1897. makePossibleUpgrades(t);
  1898. while (valueBought < g.value)
  1899. {
  1900. auto res = ah->allResources();
  1901. std::vector<creInfo> creaturesInDwellings;
  1902. for (int i = 0; i < t->creatures.size(); i++)
  1903. {
  1904. auto ci = infoFromDC(t->creatures[i]);
  1905. if(!ci.count
  1906. || ci.creID == CreatureID::NONE
  1907. || (g.objid != -1 && ci.creID.getNum() != g.objid)
  1908. || t->getUpperArmy()->getSlotFor(ci.creID) == SlotID())
  1909. continue;
  1910. vstd::amin(ci.count, res / ci.cre->getFullRecruitCost()); //max count we can afford
  1911. if(!ci.count)
  1912. continue;
  1913. ci.level = i; //this is important for Dungeon Summoning Portal
  1914. creaturesInDwellings.push_back(ci);
  1915. }
  1916. if (creaturesInDwellings.empty())
  1917. throw cannotFulfillGoalException("Can't buy any more creatures!");
  1918. creInfo ci =
  1919. *boost::max_element(creaturesInDwellings, [](const creInfo & lhs, const creInfo & rhs)
  1920. {
  1921. //max value of creatures we can buy with our res
  1922. int value1 = lhs.cre->getAIValue() * lhs.count;
  1923. int value2 = rhs.cre->getAIValue() * rhs.count;
  1924. return value1 < value2;
  1925. });
  1926. cb->recruitCreatures(t, t->getUpperArmy(), ci.creID, ci.count, ci.level);
  1927. valueBought += ci.count * ci.cre->getAIValue();
  1928. }
  1929. throw goalFulfilledException(sptr(g)); //we bought as many creatures as we wanted
  1930. }
  1931. void VCAI::tryRealize(Goals::Invalid & g)
  1932. {
  1933. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1934. }
  1935. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1936. {
  1937. logAi->debug("Attempting realizing goal with code %s", g.name());
  1938. throw cannotFulfillGoalException("Unknown type of goal !");
  1939. }
  1940. const CGTownInstance * VCAI::findTownWithTavern() const
  1941. {
  1942. for(const CGTownInstance * t : cb->getTownsInfo())
  1943. if(t->hasBuilt(BuildingID::TAVERN) && !t->getVisitingHero())
  1944. return t;
  1945. return nullptr;
  1946. }
  1947. Goals::TSubgoal VCAI::getGoal(HeroPtr h) const
  1948. {
  1949. auto it = lockedHeroes.find(h);
  1950. if(it != lockedHeroes.end())
  1951. return it->second;
  1952. else
  1953. return sptr(Goals::Invalid());
  1954. }
  1955. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1956. {
  1957. std::vector<HeroPtr> ret;
  1958. for(auto h : cb->getHeroesInfo())
  1959. {
  1960. //&& !vstd::contains(lockedHeroes, h)
  1961. //at this point we assume heroes exhausted their locked goals
  1962. if(canAct(h))
  1963. ret.push_back(h);
  1964. }
  1965. return ret;
  1966. }
  1967. bool VCAI::canAct(HeroPtr h) const
  1968. {
  1969. auto mission = lockedHeroes.find(h);
  1970. if(mission != lockedHeroes.end())
  1971. {
  1972. //FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
  1973. if(mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
  1974. return false;
  1975. }
  1976. return h->movementPointsRemaining();
  1977. }
  1978. HeroPtr VCAI::primaryHero() const
  1979. {
  1980. auto hs = cb->getHeroesInfo();
  1981. if (hs.empty())
  1982. return nullptr;
  1983. else
  1984. return *boost::max_element(hs, compareHeroStrength);
  1985. }
  1986. void VCAI::endTurn()
  1987. {
  1988. logAi->info("Player %d (%s) ends turn", playerID, playerID.toString());
  1989. if(!status.haveTurn())
  1990. {
  1991. logAi->error("Not having turn at the end of turn???");
  1992. }
  1993. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  1994. do
  1995. {
  1996. cb->endTurn();
  1997. }
  1998. 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
  1999. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.toString());
  2000. }
  2001. void VCAI::striveToGoal(Goals::TSubgoal basicGoal)
  2002. {
  2003. //TODO: this function is deprecated and should be dropped altogether
  2004. auto goalToDecompose = basicGoal;
  2005. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  2006. int maxAbstractGoals = 10;
  2007. while (!elementarGoal->isElementar && maxAbstractGoals)
  2008. {
  2009. try
  2010. {
  2011. elementarGoal = decomposeGoal(goalToDecompose);
  2012. }
  2013. catch (goalFulfilledException & e)
  2014. {
  2015. //it is impossible to continue some goals (like exploration, for example)
  2016. completeGoal(e.goal); //put in goalsToRemove
  2017. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  2018. return;
  2019. }
  2020. catch (std::exception & e)
  2021. {
  2022. goalsToRemove.push_back(basicGoal);
  2023. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  2024. return;
  2025. }
  2026. if (elementarGoal->isAbstract) //we can decompose it further
  2027. {
  2028. goalsToAdd.push_back(elementarGoal);
  2029. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  2030. goalToDecompose = elementarGoal;
  2031. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  2032. maxAbstractGoals--;
  2033. }
  2034. else if (elementarGoal->isElementar) //should be
  2035. {
  2036. logAi->debug("Found elementar goal %s", elementarGoal->name());
  2037. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  2038. break;
  2039. }
  2040. else //should never be here
  2041. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  2042. }
  2043. //realize best goal
  2044. if (!elementarGoal->invalid())
  2045. {
  2046. logAi->debug("Trying to realize %s (value %2.3f)", elementarGoal->name(), elementarGoal->priority);
  2047. try
  2048. {
  2049. makingTurnInterrupption.interruptionPoint();
  2050. elementarGoal->accept(this); //visitor pattern
  2051. makingTurnInterrupption.interruptionPoint();
  2052. }
  2053. catch (const TerminationRequestedException &)
  2054. {
  2055. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  2056. throw; //rethrow, we want to truly end this thread
  2057. }
  2058. catch (const goalFulfilledException & e)
  2059. {
  2060. //the sub-goal was completed successfully
  2061. completeGoal(e.goal);
  2062. //local goal was also completed
  2063. completeGoal(elementarGoal);
  2064. }
  2065. catch (const std::exception & e)
  2066. {
  2067. logAi->debug("Failed to realize subgoal of type %s, I will stop.", elementarGoal->name());
  2068. logAi->debug("The error message was: %s", e.what());
  2069. //erase base goal if we failed to execute decomposed goal
  2070. for (auto basicGoalToRemove : ultimateGoalsFromBasic[elementarGoal])
  2071. goalsToRemove.push_back(basicGoalToRemove);
  2072. }
  2073. }
  2074. }
  2075. Goals::TSubgoal VCAI::decomposeGoal(Goals::TSubgoal ultimateGoal)
  2076. {
  2077. if(ultimateGoal->isElementar)
  2078. {
  2079. logAi->warn("Trying to decompose elementar goal %s", ultimateGoal->name());
  2080. return ultimateGoal;
  2081. }
  2082. const int searchDepth = 30;
  2083. Goals::TSubgoal goal = ultimateGoal;
  2084. logAi->debug("Decomposing goal %s", ultimateGoal->name());
  2085. int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
  2086. while (maxGoals)
  2087. {
  2088. makingTurnInterrupption.interruptionPoint();
  2089. goal = goal->whatToDoToAchieve(); //may throw if decomposition fails
  2090. --maxGoals;
  2091. if (goal == ultimateGoal) //compare objects by value
  2092. if (goal->isElementar == ultimateGoal->isElementar)
  2093. throw cannotFulfillGoalException((boost::format("Goal dependency loop detected for %s!")
  2094. % ultimateGoal->name()).str());
  2095. if (goal->isAbstract || goal->isElementar)
  2096. return goal;
  2097. else
  2098. logAi->debug("Considering: %s", goal->name());
  2099. }
  2100. throw cannotFulfillGoalException("Too many subgoals, don't know what to do");
  2101. }
  2102. void VCAI::performTypicalActions()
  2103. {
  2104. for(auto h : getUnblockedHeroes())
  2105. {
  2106. if(!h) //hero might be lost. getUnblockedHeroes() called once on start of turn
  2107. continue;
  2108. logAi->debug("Hero %s started wandering, MP=%d", h->getNameTranslated(), h->movementPointsRemaining());
  2109. makePossibleUpgrades(*h);
  2110. pickBestArtifacts(*h);
  2111. try
  2112. {
  2113. wander(h);
  2114. }
  2115. catch(std::exception & e)
  2116. {
  2117. logAi->debug("Cannot use this hero anymore, received exception: %s", e.what());
  2118. continue;
  2119. }
  2120. }
  2121. }
  2122. void VCAI::buildArmyIn(const CGTownInstance * t)
  2123. {
  2124. makePossibleUpgrades(t->getVisitingHero());
  2125. makePossibleUpgrades(t);
  2126. recruitCreatures(t, t->getUpperArmy());
  2127. moveCreaturesToHero(t);
  2128. }
  2129. void VCAI::checkHeroArmy(HeroPtr h)
  2130. {
  2131. auto it = lockedHeroes.find(h);
  2132. if(it != lockedHeroes.end())
  2133. {
  2134. if(it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  2135. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  2136. }
  2137. }
  2138. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2139. {
  2140. logAi->debug("Trying to recruit a hero in %s at %s", t->getNameTranslated(), t->visitablePos().toString());
  2141. auto heroes = cb->getAvailableHeroes(t);
  2142. if(heroes.size())
  2143. {
  2144. auto hero = heroes[0];
  2145. if(heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
  2146. {
  2147. if(heroes[1]->getTotalStrength() > hero->getTotalStrength())
  2148. hero = heroes[1];
  2149. }
  2150. cb->recruitHero(t, hero);
  2151. throw goalFulfilledException(sptr(Goals::RecruitHero().settown(t)));
  2152. }
  2153. else if(throwing)
  2154. {
  2155. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2156. }
  2157. }
  2158. void VCAI::finish()
  2159. {
  2160. makingTurnInterrupption.interruptThread();
  2161. if (asyncTasks)
  2162. {
  2163. asyncTasks->wait();
  2164. asyncTasks.reset();
  2165. }
  2166. }
  2167. void VCAI::executeActionAsync(const std::string & description, const std::function<void()> & whatToDo)
  2168. {
  2169. if (!asyncTasks)
  2170. throw std::runtime_error("Attempt to execute task on shut down AI state!");
  2171. asyncTasks->run([this, description, whatToDo]()
  2172. {
  2173. ScopedThreadName guard("VCAI::" + description);
  2174. SET_GLOBAL_STATE(this);
  2175. std::shared_lock gsLock(CGameState::mutex);
  2176. whatToDo();
  2177. });
  2178. }
  2179. void VCAI::lostHero(HeroPtr h)
  2180. {
  2181. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
  2182. vstd::erase_if_present(lockedHeroes, h);
  2183. for(auto obj : reservedHeroesMap[h])
  2184. {
  2185. vstd::erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2186. }
  2187. vstd::erase_if_present(reservedHeroesMap, h);
  2188. vstd::erase_if_present(visitedHeroes, h);
  2189. for (auto heroVec : visitedHeroes)
  2190. {
  2191. vstd::erase_if_present(heroVec.second, h);
  2192. }
  2193. //remove goals with removed hero assigned from main loop
  2194. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  2195. {
  2196. if(x.first->hero == h)
  2197. return true;
  2198. else
  2199. return false;
  2200. });
  2201. auto removedHeroGoalPredicate = [&](const Goals::TSubgoal & x) ->bool
  2202. {
  2203. if(x->hero == h)
  2204. return true;
  2205. else
  2206. return false;
  2207. };
  2208. vstd::erase_if(basicGoals, removedHeroGoalPredicate);
  2209. vstd::erase_if(goalsToAdd, removedHeroGoalPredicate);
  2210. vstd::erase_if(goalsToRemove, removedHeroGoalPredicate);
  2211. for(auto goal : ultimateGoalsFromBasic)
  2212. vstd::erase_if(goal.second, removedHeroGoalPredicate);
  2213. }
  2214. void VCAI::answerQuery(QueryID queryID, int selection)
  2215. {
  2216. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  2217. if(queryID != QueryID(-1))
  2218. {
  2219. cb->selectionMade(selection, queryID);
  2220. }
  2221. else
  2222. {
  2223. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2224. //do nothing
  2225. }
  2226. }
  2227. void VCAI::requestSent(const CPackForServer * pack, int requestID)
  2228. {
  2229. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2230. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  2231. {
  2232. status.attemptedAnsweringQuery(reply->qid, requestID);
  2233. }
  2234. }
  2235. std::string VCAI::getBattleAIName() const
  2236. {
  2237. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  2238. return settings["server"]["enemyAI"].String();
  2239. else
  2240. return "BattleAI";
  2241. }
  2242. void VCAI::validateObject(const CGObjectInstance * obj)
  2243. {
  2244. validateObject(obj->id);
  2245. }
  2246. void VCAI::validateObject(ObjectIdRef obj)
  2247. {
  2248. auto matchesId = [&](const CGObjectInstance * hlpObj) -> bool
  2249. {
  2250. return hlpObj->id == obj.id;
  2251. };
  2252. if(!obj)
  2253. {
  2254. vstd::erase_if(visitableObjs, matchesId);
  2255. for(auto & p : reservedHeroesMap)
  2256. vstd::erase_if(p.second, matchesId);
  2257. vstd::erase_if(reservedObjs, matchesId);
  2258. }
  2259. }
  2260. AIStatus::AIStatus()
  2261. {
  2262. battle = NO_BATTLE;
  2263. havingTurn = false;
  2264. ongoingHeroMovement = false;
  2265. ongoingChannelProbing = false;
  2266. }
  2267. AIStatus::~AIStatus()
  2268. {
  2269. }
  2270. void AIStatus::setBattle(BattleState BS)
  2271. {
  2272. std::unique_lock<std::mutex> lock(mx);
  2273. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2274. battle = BS;
  2275. cv.notify_all();
  2276. }
  2277. BattleState AIStatus::getBattle()
  2278. {
  2279. std::unique_lock<std::mutex> lock(mx);
  2280. return battle;
  2281. }
  2282. void AIStatus::addQuery(QueryID ID, std::string description)
  2283. {
  2284. if(ID == QueryID(-1))
  2285. {
  2286. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  2287. return;
  2288. }
  2289. assert(ID.getNum() >= 0);
  2290. std::unique_lock<std::mutex> lock(mx);
  2291. assert(!vstd::contains(remainingQueries, ID));
  2292. remainingQueries[ID] = description;
  2293. cv.notify_all();
  2294. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2295. }
  2296. void AIStatus::removeQuery(QueryID ID)
  2297. {
  2298. std::unique_lock<std::mutex> lock(mx);
  2299. assert(vstd::contains(remainingQueries, ID));
  2300. std::string description = remainingQueries[ID];
  2301. remainingQueries.erase(ID);
  2302. cv.notify_all();
  2303. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2304. }
  2305. int AIStatus::getQueriesCount()
  2306. {
  2307. std::unique_lock<std::mutex> lock(mx);
  2308. return static_cast<int>(remainingQueries.size());
  2309. }
  2310. void AIStatus::startedTurn()
  2311. {
  2312. std::unique_lock<std::mutex> lock(mx);
  2313. havingTurn = true;
  2314. cv.notify_all();
  2315. }
  2316. void AIStatus::madeTurn()
  2317. {
  2318. std::unique_lock<std::mutex> lock(mx);
  2319. havingTurn = false;
  2320. cv.notify_all();
  2321. }
  2322. void AIStatus::waitTillFree()
  2323. {
  2324. std::unique_lock<std::mutex> lock(mx);
  2325. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2326. cv.wait_for(lock, std::chrono::milliseconds(100));
  2327. }
  2328. bool AIStatus::haveTurn()
  2329. {
  2330. std::unique_lock<std::mutex> lock(mx);
  2331. return havingTurn;
  2332. }
  2333. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2334. {
  2335. std::unique_lock<std::mutex> lock(mx);
  2336. assert(vstd::contains(remainingQueries, queryID));
  2337. std::string description = remainingQueries[queryID];
  2338. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  2339. requestToQueryID[answerRequestID] = queryID;
  2340. }
  2341. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2342. {
  2343. QueryID query;
  2344. {
  2345. std::unique_lock<std::mutex> lock(mx);
  2346. assert(vstd::contains(requestToQueryID, answerRequestID));
  2347. query = requestToQueryID[answerRequestID];
  2348. assert(vstd::contains(remainingQueries, query));
  2349. requestToQueryID.erase(answerRequestID);
  2350. }
  2351. if(result)
  2352. {
  2353. removeQuery(query);
  2354. }
  2355. else
  2356. {
  2357. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  2358. //TODO safely retry
  2359. }
  2360. }
  2361. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  2362. {
  2363. std::unique_lock<std::mutex> lock(mx);
  2364. if(started)
  2365. {
  2366. objectsBeingVisited.push_back(obj);
  2367. }
  2368. else
  2369. {
  2370. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2371. // causing visit to hero on the other side.
  2372. // However, we are guaranteed that start/end visit notification maintain stack order.
  2373. assert(!objectsBeingVisited.empty());
  2374. objectsBeingVisited.pop_back();
  2375. }
  2376. cv.notify_all();
  2377. }
  2378. void AIStatus::setMove(bool ongoing)
  2379. {
  2380. std::unique_lock<std::mutex> lock(mx);
  2381. ongoingHeroMovement = ongoing;
  2382. cv.notify_all();
  2383. }
  2384. void AIStatus::setChannelProbing(bool ongoing)
  2385. {
  2386. std::unique_lock<std::mutex> lock(mx);
  2387. ongoingChannelProbing = ongoing;
  2388. cv.notify_all();
  2389. }
  2390. bool AIStatus::channelProbing()
  2391. {
  2392. return ongoingChannelProbing;
  2393. }
  2394. bool isWeeklyRevisitable(const CGObjectInstance * obj)
  2395. {
  2396. //TODO: allow polling of remaining creatures in dwelling
  2397. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
  2398. return rewardable->configuration.getResetDuration() == 7;
  2399. if(dynamic_cast<const CGDwelling *>(obj))
  2400. return true;
  2401. switch(obj->ID)
  2402. {
  2403. case Obj::STABLES:
  2404. case Obj::MAGIC_WELL:
  2405. case Obj::HILL_FORT:
  2406. return true;
  2407. case Obj::BORDER_GATE:
  2408. case Obj::BORDERGUARD:
  2409. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  2410. }
  2411. return false;
  2412. }
  2413. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2414. {
  2415. switch(obj->ID)
  2416. {
  2417. case Obj::TOWN:
  2418. case Obj::HERO: //never visit our heroes at random
  2419. return obj->tempOwner != h->tempOwner; //do not visit our towns at random
  2420. case Obj::BORDER_GATE:
  2421. {
  2422. for(auto q : ai->myCb->getMyQuests())
  2423. {
  2424. if(q.getObject(cb) == obj)
  2425. {
  2426. return false; // do not visit guards or gates when wandering
  2427. }
  2428. }
  2429. return true; //we don't have this quest yet
  2430. }
  2431. case Obj::BORDERGUARD: //open borderguard if possible
  2432. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  2433. case Obj::SEER_HUT:
  2434. case Obj::QUEST_GUARD:
  2435. {
  2436. for(auto q : ai->myCb->getMyQuests())
  2437. {
  2438. if(q.getObject(cb) == obj)
  2439. {
  2440. if(q.getQuest(cb)->checkQuest(h.h))
  2441. return true; //we completed the quest
  2442. else
  2443. return false; //we can't complete this quest
  2444. }
  2445. }
  2446. return true; //we don't have this quest yet
  2447. }
  2448. case Obj::CREATURE_GENERATOR1:
  2449. {
  2450. if(obj->tempOwner != h->tempOwner)
  2451. return true; //flag just in case
  2452. bool canRecruitCreatures = false;
  2453. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2454. for(auto level : d->creatures)
  2455. {
  2456. for(auto c : level.second)
  2457. {
  2458. if(h->getSlotFor(CreatureID(c)) != SlotID())
  2459. canRecruitCreatures = true;
  2460. }
  2461. }
  2462. return canRecruitCreatures;
  2463. }
  2464. case Obj::HILL_FORT:
  2465. {
  2466. for(const auto & slot : h->Slots())
  2467. {
  2468. if(slot.second->getType()->hasUpgrades())
  2469. return true; //TODO: check price?
  2470. }
  2471. return false;
  2472. }
  2473. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2474. case Obj::MONOLITH_ONE_WAY_EXIT:
  2475. case Obj::MONOLITH_TWO_WAY:
  2476. case Obj::WHIRLPOOL:
  2477. return false;
  2478. case Obj::SCHOOL_OF_MAGIC:
  2479. case Obj::SCHOOL_OF_WAR:
  2480. {
  2481. if (ai->ah->freeGold() < 1000)
  2482. return false;
  2483. break;
  2484. }
  2485. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2486. if(h->level < 12)
  2487. return false;
  2488. break;
  2489. case Obj::TREE_OF_KNOWLEDGE:
  2490. {
  2491. TResources myRes = ai->ah->freeResources();
  2492. if(myRes[EGameResID::GOLD] < 2000 || myRes[EGameResID::GEMS] < 10)
  2493. return false;
  2494. break;
  2495. }
  2496. case Obj::MAGIC_WELL:
  2497. return h->mana < h->manaLimit();
  2498. case Obj::PRISON:
  2499. return ai->myCb->getHeroesInfo().size() < cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP);
  2500. case Obj::TAVERN:
  2501. {
  2502. //TODO: make AI actually recruit heroes
  2503. //TODO: only on request
  2504. if(ai->myCb->getHeroesInfo().size() >= cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  2505. return false;
  2506. else if(ai->ah->freeGold() < GameConstants::HERO_GOLD_COST)
  2507. return false;
  2508. break;
  2509. }
  2510. case Obj::BOAT:
  2511. return false;
  2512. //Boats are handled by pathfinder
  2513. case Obj::EYE_OF_MAGI:
  2514. return false; //this object is useless to visit, but could be visited indefinitely
  2515. }
  2516. if(obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2517. return false;
  2518. return true;
  2519. }
  2520. std::optional<BattleAction> VCAI::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  2521. {
  2522. return std::nullopt;
  2523. }