VCAI.cpp 83 KB

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