VCAI.cpp 87 KB

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