VCAI.cpp 99 KB

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