VCAI.cpp 88 KB

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