VCAI.cpp 99 KB

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