VCAI.cpp 99 KB

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