VCAI.cpp 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089
  1. #include "StdInc.h"
  2. #include "VCAI.h"
  3. #include "../../lib/UnlockGuard.h"
  4. #include "../../lib/CObjectHandler.h"
  5. #include "../../lib/CConfigHandler.h"
  6. #include "../../lib/CHeroHandler.h"
  7. #define I_AM_ELEMENTAR return CGoal(*this).setisElementar(true)
  8. extern FuzzyHelper *fh;
  9. class CGVisitableOPW;
  10. const int ACTUAL_RESOURCE_COUNT = 7;
  11. const double SAFE_ATTACK_CONSTANT = 1.5;
  12. using namespace vstd;
  13. //one thread may be turn of AI and another will be handling a side effect for AI2
  14. boost::thread_specific_ptr<CCallback> cb;
  15. boost::thread_specific_ptr<VCAI> ai;
  16. //std::map<int, std::map<int, int> > HeroView::infosCount;
  17. // CCallback *cb;
  18. // VCAI *ai;
  19. //helper RAII to manage global ai/cb ptrs
  20. struct SetGlobalState
  21. {
  22. SetGlobalState(VCAI * AI)
  23. {
  24. assert(!ai.get());
  25. assert(!cb.get());
  26. ai.reset(AI);
  27. cb.reset(AI->myCb.get());
  28. }
  29. ~SetGlobalState()
  30. {
  31. ai.release();
  32. cb.release();
  33. }
  34. };
  35. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  36. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  37. #define MAKING_TURN SET_GLOBAL_STATE(this)
  38. 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)
  39. const int HERO_GOLD_COST = 2500;
  40. const int ALLOWED_ROAMING_HEROES = 8;
  41. const int GOLD_MINE_PRODUCTION = 1000, WOOD_ORE_MINE_PRODUCTION = 2, RESOURCE_MINE_PRODUCTION = 1;
  42. std::string CGoal::name() const
  43. {
  44. switch (goalType)
  45. {
  46. case INVALID:
  47. return "INVALID";
  48. case WIN:
  49. return "WIN";
  50. case DO_NOT_LOSE:
  51. return "DO NOT LOOSE";
  52. case CONQUER:
  53. return "CONQUER";
  54. case BUILD:
  55. return "BUILD";
  56. case EXPLORE:
  57. return "EXPLORE";
  58. case GATHER_ARMY:
  59. return "GATHER ARMY";
  60. case BOOST_HERO:
  61. return "BOOST_HERO (unsupported)";
  62. case RECRUIT_HERO:
  63. return "RECRUIT HERO";
  64. case BUILD_STRUCTURE:
  65. return "BUILD STRUCTURE";
  66. case COLLECT_RES:
  67. return "COLLECT RESOURCE";
  68. case GATHER_TROOPS:
  69. return "GATHER TROOPS";
  70. case GET_OBJ:
  71. return "GET OBJECT " + boost::lexical_cast<std::string>(objid);
  72. case FIND_OBJ:
  73. return "FIND OBJECT " + boost::lexical_cast<std::string>(objid);
  74. case VISIT_HERO:
  75. return "VISIT HERO " + boost::lexical_cast<std::string>(objid);
  76. case GET_ART_TYPE:
  77. return "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  78. case ISSUE_COMMAND:
  79. return "ISSUE COMMAND (unsupported)";
  80. case VISIT_TILE:
  81. return "VISIT TILE " + tile();
  82. case CLEAR_WAY_TO:
  83. return "CLEAR WAY TO " + tile();
  84. case DIG_AT_TILE:
  85. return "DIG AT TILE " + tile();
  86. default:
  87. return boost::lexical_cast<std::string>(goalType);
  88. }
  89. }
  90. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  91. {
  92. return h1->getTotalStrength() < h2->getTotalStrength();
  93. }
  94. bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
  95. {
  96. return a1->getArmyStrength() < a2->getArmyStrength();
  97. }
  98. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  99. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  100. struct TimeCheck
  101. {
  102. CStopWatch time;
  103. std::string txt;
  104. TimeCheck(crstring TXT) : txt(TXT)
  105. {
  106. }
  107. ~TimeCheck()
  108. {
  109. logAi->debugStream() << boost::format("Time of %s was %d ms.") % txt % time.getDiff();
  110. }
  111. };
  112. template<typename T>
  113. void removeDuplicates(std::vector<T> &vec)
  114. {
  115. boost::sort(vec);
  116. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  117. }
  118. struct AtScopeExit
  119. {
  120. std::function<void()> foo;
  121. AtScopeExit(const std::function<void()> &FOO) : foo(FOO)
  122. {}
  123. ~AtScopeExit()
  124. {
  125. foo();
  126. }
  127. };
  128. void foreach_tile_pos(std::function<void(const int3& pos)> foo)
  129. {
  130. for(int i = 0; i < cb->getMapSize().x; i++)
  131. for(int j = 0; j < cb->getMapSize().y; j++)
  132. for(int k = 0; k < cb->getMapSize().z; k++)
  133. foo(int3(i,j,k));
  134. }
  135. void foreach_neighbour(const int3 &pos, std::function<void(const int3& pos)> foo)
  136. {
  137. for(const int3 &dir : dirs)
  138. {
  139. const int3 n = pos + dir;
  140. if(cb->isInTheMap(n))
  141. foo(pos+dir);
  142. }
  143. }
  144. unsigned char &retreiveTileN(std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  145. {
  146. return vectors[pos.x][pos.y][pos.z];
  147. }
  148. const unsigned char &retreiveTileN(const std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  149. {
  150. return vectors[pos.x][pos.y][pos.z];
  151. }
  152. void foreach_tile(std::vector< std::vector< std::vector<unsigned char> > > &vectors, std::function<void(unsigned char &in)> foo)
  153. {
  154. for(auto & vector : vectors)
  155. for(auto j = vector.begin(); j != vector.end(); j++)
  156. for(auto & elem : *j)
  157. foo(elem);
  158. }
  159. struct ObjInfo
  160. {
  161. int3 pos;
  162. std::string name;
  163. ObjInfo(){}
  164. ObjInfo(const CGObjectInstance *obj)
  165. {
  166. pos = obj->pos;
  167. name = obj->getHoverText();
  168. }
  169. };
  170. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  171. template <typename Container, typename Item>
  172. bool erase_if_present(Container &c, const Item &item)
  173. {
  174. auto i = std::find(c.begin(), c.end(), item);
  175. if (i != c.end())
  176. {
  177. c.erase(i);
  178. return true;
  179. }
  180. return false;
  181. }
  182. template <typename V, typename Item, typename Item2>
  183. bool erase_if_present(std::map<Item,V> & c, const Item2 &item)
  184. {
  185. auto i = c.find(item);
  186. if (i != c.end())
  187. {
  188. c.erase(i);
  189. return true;
  190. }
  191. return false;
  192. }
  193. template <typename Container, typename Pred>
  194. void erase(Container &c, Pred pred)
  195. {
  196. c.erase(boost::remove_if(c, pred), c.end());
  197. }
  198. bool isReachable(const CGObjectInstance *obj)
  199. {
  200. return cb->getPathInfo(obj->visitablePos())->turns < 255;
  201. }
  202. ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t)
  203. {
  204. ui64 ret = 0;
  205. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  206. std::vector<const CStackInstance *> toMove;
  207. for(auto const slot : t->Slots())
  208. {
  209. //can be merged woth another stack?
  210. SlotID dst = h->getSlotFor(slot.second->getCreatureID());
  211. if(h->hasStackAtSlot(dst))
  212. ret += t->getPower(slot.first);
  213. else
  214. toMove.push_back(slot.second);
  215. }
  216. boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
  217. {
  218. return lhs->getPower() < rhs->getPower();
  219. });
  220. for (auto & stack : boost::adaptors::reverse(toMove))
  221. {
  222. if(freeHeroSlots)
  223. {
  224. ret += stack->getPower();
  225. freeHeroSlots--;
  226. }
  227. else
  228. break;
  229. }
  230. return ret;
  231. }
  232. std::string strFromInt3(int3 pos)
  233. {
  234. std::ostringstream oss;
  235. oss << pos;
  236. return oss.str();
  237. }
  238. bool isCloser(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  239. {
  240. const CGPathNode *ln = cb->getPathInfo(lhs->visitablePos()), *rn = cb->getPathInfo(rhs->visitablePos());
  241. if(ln->turns != rn->turns)
  242. return ln->turns < rn->turns;
  243. return (ln->moveRemains > rn->moveRemains);
  244. }
  245. bool compareMovement(HeroPtr lhs, HeroPtr rhs)
  246. {
  247. return lhs->movement > rhs->movement;
  248. }
  249. ui64 evaluateDanger(const CGObjectInstance *obj);
  250. ui64 evaluateDanger(crint3 tile)
  251. {
  252. const TerrainTile *t = cb->getTile(tile, false);
  253. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  254. return 190000000; //MUCH
  255. ui64 objectDanger = 0, guardDanger = 0;
  256. auto visObjs = cb->getVisitableObjs(tile);
  257. if(visObjs.size())
  258. objectDanger = evaluateDanger(visObjs.back());
  259. int3 guardPos = cb->guardingCreaturePosition(tile);
  260. if(guardPos.x >= 0 && guardPos != tile)
  261. guardDanger = evaluateDanger(guardPos);
  262. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  263. return std::max(objectDanger, guardDanger);
  264. return 0;
  265. }
  266. ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
  267. {
  268. const TerrainTile *t = cb->getTile(tile, false);
  269. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  270. return 190000000; //MUCH
  271. ui64 objectDanger = 0, guardDanger = 0;
  272. auto visitableObjects = cb->getVisitableObjs(tile);
  273. // in some scenarios hero happens to be "under" the object (eg town). Then we consider ONLY the hero.
  274. if(vstd::contains_if(visitableObjects, objWithID<Obj::HERO>))
  275. erase_if(visitableObjects, [](const CGObjectInstance * obj)
  276. {
  277. return !objWithID<Obj::HERO>(obj);
  278. });
  279. if(const CGObjectInstance * dangerousObject = backOrNull(visitableObjects))
  280. {
  281. objectDanger = evaluateDanger(dangerousObject); //unguarded objects can also be dangerous or unhandled
  282. if (objectDanger)
  283. {
  284. //TODO: don't downcast objects AI shouldnt know about!
  285. auto armedObj = dynamic_cast<const CArmedInstance*>(dangerousObject);
  286. if(armedObj)
  287. objectDanger *= fh->getTacticalAdvantage(visitor, armedObj); //this line tends to go infinite for allied towns (?)
  288. }
  289. }
  290. auto guards = cb->getGuardingCreatures(tile);
  291. for (auto cre : guards)
  292. {
  293. amax (guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre))); //we are interested in strongest monster around
  294. }
  295. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  296. return std::max(objectDanger, guardDanger);
  297. }
  298. ui64 evaluateDanger(const CGObjectInstance *obj)
  299. {
  300. if(obj->tempOwner < PlayerColor::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES) //owned or allied objects don't pose any threat
  301. return 0;
  302. switch(obj->ID)
  303. {
  304. case Obj::HERO:
  305. {
  306. InfoAboutHero iah;
  307. cb->getHeroInfo(obj, iah);
  308. return iah.army.getStrength();
  309. }
  310. case Obj::TOWN:
  311. case Obj::GARRISON: case Obj::GARRISON2: //garrison
  312. {
  313. InfoAboutTown iat;
  314. cb->getTownInfo(obj, iat);
  315. return iat.army.getStrength();
  316. }
  317. case Obj::MONSTER:
  318. {
  319. //TODO!!!!!!!!
  320. const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
  321. return cre->getArmyStrength();
  322. }
  323. case Obj::CREATURE_GENERATOR1:
  324. {
  325. const CGDwelling *d = dynamic_cast<const CGDwelling*>(obj);
  326. return d->getArmyStrength();
  327. }
  328. case Obj::MINE:
  329. case Obj::ABANDONED_MINE:
  330. {
  331. const CArmedInstance * a = dynamic_cast<const CArmedInstance*>(obj);
  332. return a->getArmyStrength();
  333. }
  334. case Obj::CRYPT: //crypt
  335. case Obj::CREATURE_BANK: //crebank
  336. case Obj::DRAGON_UTOPIA:
  337. case Obj::SHIPWRECK: //shipwreck
  338. case Obj::DERELICT_SHIP: //derelict ship
  339. // case Obj::PYRAMID:
  340. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  341. case Obj::PYRAMID:
  342. {
  343. if(obj->subID == 0)
  344. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  345. else
  346. return 0;
  347. }
  348. default:
  349. return 0;
  350. }
  351. }
  352. bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  353. {
  354. return evaluateDanger(lhs) < evaluateDanger(rhs);
  355. }
  356. VCAI::VCAI(void)
  357. {
  358. LOG_TRACE(logAi);
  359. makingTurn = nullptr;
  360. }
  361. VCAI::~VCAI(void)
  362. {
  363. LOG_TRACE(logAi);
  364. }
  365. void VCAI::availableCreaturesChanged(const CGDwelling *town)
  366. {
  367. LOG_TRACE(logAi);
  368. NET_EVENT_HANDLER;
  369. }
  370. void VCAI::heroMoved(const TryMoveHero & details)
  371. {
  372. LOG_TRACE(logAi);
  373. NET_EVENT_HANDLER;
  374. validateObject(details.id); //enemy hero may have left visible area
  375. if(details.result == TryMoveHero::TELEPORTATION)
  376. {
  377. const int3 from = CGHeroInstance::convertPosition(details.start, false),
  378. to = CGHeroInstance::convertPosition(details.end, false);
  379. const CGObjectInstance *o1 = frontOrNull(cb->getVisitableObjs(from)),
  380. *o2 = frontOrNull(cb->getVisitableObjs(to));
  381. if(o1 && o2 && o1->ID == Obj::SUBTERRANEAN_GATE && o2->ID == Obj::SUBTERRANEAN_GATE)
  382. {
  383. knownSubterraneanGates[o1] = o2;
  384. knownSubterraneanGates[o2] = o1;
  385. logAi->debugStream() << boost::format("Found a pair of subterranean gates between %s and %s!") % from % to;
  386. }
  387. }
  388. }
  389. void VCAI::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  390. {
  391. LOG_TRACE_PARAMS(logAi, "isAbsolute '%i'", isAbsolute);
  392. NET_EVENT_HANDLER;
  393. }
  394. void VCAI::heroInGarrisonChange(const CGTownInstance *town)
  395. {
  396. LOG_TRACE(logAi);
  397. NET_EVENT_HANDLER;
  398. }
  399. void VCAI::centerView(int3 pos, int focusTime)
  400. {
  401. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  402. NET_EVENT_HANDLER;
  403. }
  404. void VCAI::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  405. {
  406. LOG_TRACE(logAi);
  407. NET_EVENT_HANDLER;
  408. }
  409. void VCAI::artifactAssembled(const ArtifactLocation &al)
  410. {
  411. LOG_TRACE(logAi);
  412. NET_EVENT_HANDLER;
  413. }
  414. void VCAI::showTavernWindow(const CGObjectInstance *townOrTavern)
  415. {
  416. LOG_TRACE(logAi);
  417. NET_EVENT_HANDLER;
  418. }
  419. void VCAI::showThievesGuildWindow (const CGObjectInstance * obj)
  420. {
  421. LOG_TRACE(logAi);
  422. NET_EVENT_HANDLER;
  423. }
  424. void VCAI::playerBlocked(int reason, bool start)
  425. {
  426. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  427. NET_EVENT_HANDLER;
  428. if (start && reason == PlayerBlocked::UPCOMING_BATTLE)
  429. status.setBattle(UPCOMING_BATTLE);
  430. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  431. status.setMove(start);
  432. }
  433. void VCAI::showPuzzleMap()
  434. {
  435. LOG_TRACE(logAi);
  436. NET_EVENT_HANDLER;
  437. }
  438. void VCAI::showShipyardDialog(const IShipyard *obj)
  439. {
  440. LOG_TRACE(logAi);
  441. NET_EVENT_HANDLER;
  442. }
  443. void VCAI::gameOver(PlayerColor player, bool victory)
  444. {
  445. LOG_TRACE_PARAMS(logAi, "victory '%i'", victory);
  446. NET_EVENT_HANDLER;
  447. logAi->debugStream() << boost::format("Player %d: I heard that player %d %s.") % playerID % player.getNum() % (victory ? "won" : "lost");
  448. if(player == playerID)
  449. {
  450. if(victory)
  451. {
  452. logAi->debugStream() << "VCAI: I won! Incredible!";
  453. logAi->debugStream() << "Turn nr " << myCb->getDate();
  454. }
  455. else
  456. {
  457. logAi->debugStream() << "VCAI: Player " << player << " lost. It's me. What a disappointment! :(";
  458. }
  459. // //let's make Impossible difficulty finally standing to its name :>
  460. // if(myCb->getStartInfo()->difficulty == 4 && !victory)
  461. // {
  462. // //play dirty: crash the whole engine to avoid lose
  463. // //that way AI is unbeatable!
  464. // *(int*)nullptr = 666;
  465. // }
  466. // TODO - at least write some insults on stdout
  467. finish();
  468. }
  469. }
  470. void VCAI::artifactPut(const ArtifactLocation &al)
  471. {
  472. LOG_TRACE(logAi);
  473. NET_EVENT_HANDLER;
  474. }
  475. void VCAI::artifactRemoved(const ArtifactLocation &al)
  476. {
  477. LOG_TRACE(logAi);
  478. NET_EVENT_HANDLER;
  479. }
  480. void VCAI::stacksErased(const StackLocation &location)
  481. {
  482. LOG_TRACE(logAi);
  483. NET_EVENT_HANDLER;
  484. }
  485. void VCAI::artifactDisassembled(const ArtifactLocation &al)
  486. {
  487. LOG_TRACE(logAi);
  488. NET_EVENT_HANDLER;
  489. }
  490. void VCAI::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  491. {
  492. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->hoverName : std::string("n/a")));
  493. NET_EVENT_HANDLER;
  494. if(start)
  495. {
  496. markObjectVisited (visitedObj);
  497. erase_if_present(reservedObjs, visitedObj); //unreserve objects
  498. erase_if_present(reservedHeroesMap[visitor], visitedObj);
  499. completeGoal (CGoal(GET_OBJ).sethero(visitor)); //we don't need to visit in anymore
  500. }
  501. status.heroVisit(visitedObj, start);
  502. }
  503. void VCAI::availableArtifactsChanged(const CGBlackMarket *bm /*= nullptr*/)
  504. {
  505. LOG_TRACE(logAi);
  506. NET_EVENT_HANDLER;
  507. }
  508. void VCAI::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  509. {
  510. LOG_TRACE(logAi);
  511. NET_EVENT_HANDLER;
  512. //buildArmyIn(town);
  513. //moveCreaturesToHero(town);
  514. }
  515. void VCAI::tileHidden(const std::unordered_set<int3, ShashInt3> &pos)
  516. {
  517. LOG_TRACE(logAi);
  518. NET_EVENT_HANDLER;
  519. validateVisitableObjs();
  520. }
  521. void VCAI::tileRevealed(const std::unordered_set<int3, ShashInt3> &pos)
  522. {
  523. LOG_TRACE(logAi);
  524. NET_EVENT_HANDLER;
  525. for(int3 tile : pos)
  526. for(const CGObjectInstance *obj : myCb->getVisitableObjs(tile))
  527. addVisitableObj(obj);
  528. }
  529. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  530. {
  531. LOG_TRACE(logAi);
  532. NET_EVENT_HANDLER;
  533. auto firstHero = cb->getHero(hero1);
  534. auto secondHero = cb->getHero(hero2);
  535. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s and %s") % firstHero->name % secondHero->name));
  536. requestActionASAP([=]()
  537. {
  538. if (firstHero->getHeroStrength() > secondHero->getHeroStrength() && canGetArmy (firstHero, secondHero))
  539. pickBestCreatures (firstHero, secondHero);
  540. else if (canGetArmy (secondHero, firstHero))
  541. pickBestCreatures (secondHero, firstHero);
  542. completeGoal(CGoal(VISIT_HERO).sethero(firstHero)); //TODO: what if we were visited by other hero in the meantime?
  543. completeGoal(CGoal(VISIT_HERO).sethero(secondHero));
  544. //TODO: exchange artifacts
  545. answerQuery(query, 0);
  546. });
  547. }
  548. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  549. {
  550. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  551. NET_EVENT_HANDLER;
  552. }
  553. void VCAI::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  554. {
  555. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  556. NET_EVENT_HANDLER;
  557. }
  558. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  559. {
  560. LOG_TRACE(logAi);
  561. NET_EVENT_HANDLER;
  562. }
  563. void VCAI::stackChangedType(const StackLocation &location, const CCreature &newType)
  564. {
  565. LOG_TRACE(logAi);
  566. NET_EVENT_HANDLER;
  567. }
  568. void VCAI::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  569. {
  570. LOG_TRACE(logAi);
  571. NET_EVENT_HANDLER;
  572. }
  573. void VCAI::newObject(const CGObjectInstance * obj)
  574. {
  575. LOG_TRACE(logAi);
  576. NET_EVENT_HANDLER;
  577. if(obj->isVisitable())
  578. addVisitableObj(obj);
  579. }
  580. void VCAI::objectRemoved(const CGObjectInstance *obj)
  581. {
  582. LOG_TRACE(logAi);
  583. NET_EVENT_HANDLER;
  584. erase_if_present(visitableObjs, obj);
  585. erase_if_present(alreadyVisited, obj);
  586. erase_if_present(reservedObjs, obj);
  587. for(auto &p : reservedHeroesMap)
  588. erase_if_present(p.second, obj);
  589. //TODO
  590. //there are other places where CGObjectinstance ptrs are stored...
  591. //
  592. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  593. {
  594. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  595. }
  596. }
  597. void VCAI::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  598. {
  599. LOG_TRACE(logAi);
  600. NET_EVENT_HANDLER;
  601. requestActionASAP([=]()
  602. {
  603. makePossibleUpgrades(visitor);
  604. });
  605. }
  606. void VCAI::playerBonusChanged(const Bonus &bonus, bool gain)
  607. {
  608. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  609. NET_EVENT_HANDLER;
  610. }
  611. void VCAI::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  612. {
  613. LOG_TRACE(logAi);
  614. NET_EVENT_HANDLER;
  615. }
  616. void VCAI::heroCreated(const CGHeroInstance*)
  617. {
  618. LOG_TRACE(logAi);
  619. NET_EVENT_HANDLER;
  620. }
  621. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  622. {
  623. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  624. NET_EVENT_HANDLER;
  625. }
  626. void VCAI::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  627. {
  628. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  629. NET_EVENT_HANDLER;
  630. }
  631. void VCAI::requestRealized(PackageApplied *pa)
  632. {
  633. LOG_TRACE(logAi);
  634. NET_EVENT_HANDLER;
  635. if(status.haveTurn())
  636. {
  637. if(pa->packType == typeList.getTypeID<EndTurn>())
  638. if(pa->result)
  639. status.madeTurn();
  640. }
  641. if(pa->packType == typeList.getTypeID<QueryReply>())
  642. {
  643. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  644. }
  645. }
  646. void VCAI::receivedResource(int type, int val)
  647. {
  648. LOG_TRACE_PARAMS(logAi, "type '%i', val '%i'", type % val);
  649. NET_EVENT_HANDLER;
  650. }
  651. void VCAI::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  652. {
  653. LOG_TRACE(logAi);
  654. NET_EVENT_HANDLER;
  655. }
  656. void VCAI::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  657. {
  658. LOG_TRACE(logAi);
  659. NET_EVENT_HANDLER;
  660. }
  661. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  662. {
  663. LOG_TRACE(logAi);
  664. NET_EVENT_HANDLER;
  665. }
  666. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  667. {
  668. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  669. NET_EVENT_HANDLER;
  670. }
  671. void VCAI::battleResultsApplied()
  672. {
  673. LOG_TRACE(logAi);
  674. NET_EVENT_HANDLER;
  675. assert(status.getBattle() == ENDING_BATTLE);
  676. status.setBattle(NO_BATTLE);
  677. }
  678. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  679. {
  680. LOG_TRACE(logAi);
  681. NET_EVENT_HANDLER;
  682. if(sop->what == ObjProperty::OWNER)
  683. {
  684. if(sop->val == playerID.getNum())
  685. erase_if_present(visitableObjs, myCb->getObj(sop->id));
  686. //TODO restore lost obj
  687. }
  688. }
  689. void VCAI::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what)
  690. {
  691. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  692. NET_EVENT_HANDLER;
  693. }
  694. void VCAI::heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain)
  695. {
  696. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  697. NET_EVENT_HANDLER;
  698. }
  699. void VCAI::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  700. {
  701. LOG_TRACE(logAi);
  702. NET_EVENT_HANDLER;
  703. }
  704. void VCAI::init(shared_ptr<CCallback> CB)
  705. {
  706. LOG_TRACE(logAi);
  707. myCb = CB;
  708. cbc = CB;
  709. NET_EVENT_HANDLER;
  710. playerID = *myCb->getMyColor();
  711. myCb->waitTillRealize = true;
  712. myCb->unlockGsWhenWaiting = true;
  713. if(!fh)
  714. fh = new FuzzyHelper();
  715. retreiveVisitableObjs(visitableObjs);
  716. }
  717. void VCAI::yourTurn()
  718. {
  719. LOG_TRACE(logAi);
  720. NET_EVENT_HANDLER;
  721. status.startedTurn();
  722. makingTurn = make_unique<boost::thread>(&VCAI::makeTurn, this);
  723. }
  724. void VCAI::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID)
  725. {
  726. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  727. NET_EVENT_HANDLER;
  728. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  729. requestActionASAP([=]{ answerQuery(queryID, 0); });
  730. }
  731. void VCAI::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  732. {
  733. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  734. NET_EVENT_HANDLER;
  735. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  736. requestActionASAP([=]{ answerQuery(queryID, 0); });
  737. }
  738. void VCAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel)
  739. {
  740. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  741. NET_EVENT_HANDLER;
  742. int sel = 0;
  743. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  744. % components.size() % text));
  745. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  746. sel = components.size();
  747. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  748. sel = 1;
  749. requestActionASAP([=]()
  750. {
  751. answerQuery(askID, sel);
  752. });
  753. }
  754. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  755. {
  756. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  757. NET_EVENT_HANDLER;
  758. std::string s1 = up ? up->nodeName() : "NONE";
  759. std::string s2 = down ? down->nodeName() : "NONE";
  760. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  761. //you can't request action from action-response thread
  762. requestActionASAP([=]()
  763. {
  764. pickBestCreatures (down, up);
  765. answerQuery(queryID, 0);
  766. });
  767. }
  768. void VCAI::saveGame(COSer<CSaveFile> &h, const int version)
  769. {
  770. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  771. NET_EVENT_HANDLER;
  772. validateVisitableObjs();
  773. CAdventureAI::saveGame(h, version);
  774. serializeInternal(h, version);
  775. }
  776. void VCAI::loadGame(CISer<CLoadFile> &h, const int version)
  777. {
  778. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  779. NET_EVENT_HANDLER;
  780. CAdventureAI::loadGame(h, version);
  781. serializeInternal(h, version);
  782. }
  783. void makePossibleUpgrades(const CArmedInstance *obj)
  784. {
  785. if(!obj)
  786. return;
  787. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  788. {
  789. if(const CStackInstance *s = obj->getStackPtr(SlotID(i)))
  790. {
  791. UpgradeInfo ui;
  792. cb->getUpgradeInfo(obj, SlotID(i), ui);
  793. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  794. {
  795. cb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  796. }
  797. }
  798. }
  799. }
  800. void VCAI::makeTurn()
  801. {
  802. MAKING_TURN;
  803. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  804. setThreadName("VCAI::makeTurn");
  805. logAi->debugStream() << boost::format("Player %d starting turn") % static_cast<int>(playerID.getNum());
  806. switch(cb->getDate(Date::DAY_OF_WEEK))
  807. {
  808. case 1:
  809. {
  810. townVisitsThisWeek.clear();
  811. std::vector<const CGObjectInstance *> objs;
  812. retreiveVisitableObjs(objs, true);
  813. for(const CGObjectInstance *obj : objs)
  814. {
  815. if (isWeeklyRevisitable(obj))
  816. {
  817. if (!vstd::contains(visitableObjs, obj))
  818. visitableObjs.push_back(obj);
  819. auto o = std::find (alreadyVisited.begin(), alreadyVisited.end(), obj);
  820. if (o != alreadyVisited.end())
  821. alreadyVisited.erase(o);
  822. }
  823. }
  824. }
  825. break;
  826. case 7: //reconsider strategy
  827. {
  828. if(auto h = primaryHero()) //check if our primary hero can handle danger
  829. {
  830. ui64 totalDanger = 0;
  831. int dangerousObjects = 0;
  832. std::vector<const CGObjectInstance *> objs;
  833. retreiveVisitableObjs(objs, false);
  834. for (auto obj : objs)
  835. {
  836. if (evaluateDanger(obj)) //potentilaly dnagerous
  837. {
  838. totalDanger += evaluateDanger(obj->visitablePos(), *h);
  839. ++dangerousObjects;
  840. }
  841. }
  842. ui64 averageDanger = totalDanger / std::max(dangerousObjects, 1);
  843. if (dangerousObjects && averageDanger > h->getHeroStrength())
  844. {
  845. setGoal (h, CGoal(GATHER_ARMY).sethero(h).setvalue(averageDanger * SAFE_ATTACK_CONSTANT).setisAbstract(true));
  846. }
  847. }
  848. }
  849. break;
  850. }
  851. if(cb->getSelectedHero())
  852. cb->recalculatePaths();
  853. makeTurnInternal();
  854. makingTurn.reset();
  855. return;
  856. }
  857. void VCAI::makeTurnInternal()
  858. {
  859. saving = 0;
  860. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  861. for(const CGTownInstance *t : cb->getTownsInfo())
  862. moveCreaturesToHero(t);
  863. try
  864. {
  865. //Pick objects reserved in previous turn - we expect only nerby objects there
  866. auto reservedHeroesCopy = reservedHeroesMap; //work on copy => the map may be changed while iterating (eg because hero died when attempting a goal)
  867. for (auto hero : reservedHeroesCopy)
  868. {
  869. cb->setSelection(hero.first.get());
  870. boost::sort (hero.second, isCloser);
  871. for (auto obj : hero.second)
  872. {
  873. if(!obj || !obj->defInfo || !cb->getObj(obj->id))
  874. {
  875. logAi->errorStream() << "Error: there is wrong object on list for hero " << hero.first->name;
  876. continue;
  877. }
  878. striveToGoal (CGoal(VISIT_TILE).sethero(hero.first).settile(obj->visitablePos()));
  879. }
  880. }
  881. //now try to win
  882. striveToGoal(CGoal(WIN));
  883. //finally, continue our abstract long-term goals
  884. //heroes tend to die in the process and loose their goals, unsafe to iterate it
  885. std::vector<std::pair<HeroPtr, CGoal> > safeCopy;
  886. boost::copy(lockedHeroes, std::back_inserter(safeCopy));
  887. typedef std::pair<HeroPtr, CGoal> TItrType;
  888. auto lockedHeroesSorter = [](TItrType h1, TItrType h2) -> bool
  889. {
  890. return compareMovement (h1.first, h2.first);
  891. };
  892. boost::sort(safeCopy, lockedHeroesSorter);
  893. while (safeCopy.size()) //continue our goals
  894. {
  895. auto it = safeCopy.begin();
  896. if (it->first && it->first->tempOwner == playerID && vstd::contains(lockedHeroes, it->first)) //make sure hero still has his goal
  897. {
  898. cb->setSelection(*it->first);
  899. striveToGoal (it->second);
  900. }
  901. safeCopy.erase(it);
  902. }
  903. auto quests = myCb->getMyQuests();
  904. for (auto quest : quests)
  905. {
  906. striveToQuest (quest);
  907. }
  908. striveToGoal(CGoal(BUILD)); //TODO: smarter building management
  909. }
  910. catch(boost::thread_interrupted &e)
  911. {
  912. logAi->debugStream() << "Making turn thread has been interrupted. We'll end without calling endTurn.";
  913. return;
  914. }
  915. catch(std::exception &e)
  916. {
  917. logAi->debugStream() << "Making turn thread has caught an exception: " << e.what();
  918. }
  919. endTurn();
  920. }
  921. bool VCAI::goVisitObj(const CGObjectInstance * obj, HeroPtr h)
  922. {
  923. int3 dst = obj->visitablePos();
  924. logAi->debugStream() << boost::format("%s will try to visit %s at (%s)") % h->name % obj->getHoverText() % strFromInt3(dst);
  925. return moveHeroToTile(dst, h);
  926. }
  927. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  928. {
  929. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->name % obj->getHoverText() % obj->pos);
  930. switch (obj->ID)
  931. {
  932. case Obj::CREATURE_GENERATOR1:
  933. recruitCreatures (dynamic_cast<const CGDwelling *>(obj));
  934. checkHeroArmy (h);
  935. break;
  936. case Obj::TOWN:
  937. moveCreaturesToHero (dynamic_cast<const CGTownInstance *>(obj));
  938. if (h->visitedTown) //we are inside, not just attacking
  939. {
  940. townVisitsThisWeek[h].push_back(h->visitedTown);
  941. if (!h->hasSpellbook() && cb->getResourceAmount(Res::GOLD) >= GameConstants::SPELLBOOK_GOLD_COST + saving[Res::GOLD] &&
  942. h->visitedTown->hasBuilt (BuildingID::MAGES_GUILD_1))
  943. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  944. }
  945. break;
  946. }
  947. }
  948. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  949. {
  950. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  951. {
  952. pickBestCreatures (t->visitingHero, t);
  953. }
  954. }
  955. bool VCAI::canGetArmy (const CGHeroInstance * army, const CGHeroInstance * source)
  956. { //TODO: merge with pickBestCreatures
  957. if(army->tempOwner != source->tempOwner)
  958. {
  959. logAi->errorStream() << "Why are we even considering exchange between heroes from different players?";
  960. return false;
  961. }
  962. const CArmedInstance *armies[] = {army, source};
  963. int armySize = 0;
  964. //we calculate total strength for each creature type available in armies
  965. std::map<const CCreature*, int> creToPower;
  966. for(auto armyPtr : armies)
  967. for(auto &i : armyPtr->Slots())
  968. {
  969. ++armySize;//TODO: allow splitting stacks?
  970. creToPower[i.second->type] += i.second->getPower();
  971. }
  972. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  973. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  974. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  975. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  976. {
  977. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  978. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  979. {
  980. return lhs.second < rhs.second;
  981. });
  982. bestArmy.push_back(creIt->first);
  983. creToPower.erase(creIt);
  984. if(creToPower.empty())
  985. break;
  986. }
  987. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  988. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  989. {
  990. for(auto armyPtr : armies)
  991. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  992. {
  993. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  994. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army)) //can't take away last creature
  995. return true; //at least one exchange will be performed
  996. }
  997. }
  998. return false;
  999. }
  1000. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  1001. {
  1002. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  1003. const CArmedInstance *armies[] = {army, source};
  1004. int armySize = 0;
  1005. //we calculate total strength for each creature type available in armies
  1006. std::map<const CCreature*, int> creToPower;
  1007. for(auto armyPtr : armies)
  1008. for(auto &i : armyPtr->Slots())
  1009. {
  1010. ++armySize;//TODO: allow splitting stacks?
  1011. creToPower[i.second->type] += i.second->getPower();
  1012. }
  1013. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  1014. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  1015. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  1016. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  1017. {
  1018. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  1019. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  1020. {
  1021. return lhs.second < rhs.second;
  1022. });
  1023. bestArmy.push_back(creIt->first);
  1024. creToPower.erase(creIt);
  1025. if(creToPower.empty())
  1026. break;
  1027. }
  1028. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  1029. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  1030. {
  1031. for(auto armyPtr : armies)
  1032. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  1033. {
  1034. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  1035. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army))
  1036. cb->mergeOrSwapStacks(armyPtr, army, SlotID(j), SlotID(i));
  1037. }
  1038. }
  1039. //TODO - having now strongest possible army, we may want to think about arranging stacks
  1040. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  1041. if (hero)
  1042. {
  1043. checkHeroArmy (hero);
  1044. }
  1045. }
  1046. void VCAI::recruitCreatures(const CGDwelling * d)
  1047. {
  1048. for(int i = 0; i < d->creatures.size(); i++)
  1049. {
  1050. if(!d->creatures[i].second.size())
  1051. continue;
  1052. int count = d->creatures[i].first;
  1053. CreatureID creID = d->creatures[i].second.back();
  1054. // const CCreature *c = VLC->creh->creatures[creID];
  1055. // if(containsSavedRes(c->cost))
  1056. // continue;
  1057. amin(count, freeResources() / VLC->creh->creatures[creID]->cost);
  1058. if(count > 0)
  1059. cb->recruitCreatures(d, creID, count, i);
  1060. }
  1061. }
  1062. bool VCAI::tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays)
  1063. {
  1064. if (!vstd::contains(t->town->buildings, building))
  1065. return false; // no such building in town
  1066. if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  1067. return true;
  1068. std::set<BuildingID> toBuild = cb->getBuildingRequiments(t, building);
  1069. //erase all already built buildings
  1070. for (auto buildIter = toBuild.begin(); buildIter != toBuild.end();)
  1071. {
  1072. if (t->hasBuilt(*buildIter))
  1073. toBuild.erase(buildIter++);
  1074. else
  1075. buildIter++;
  1076. }
  1077. toBuild.insert(building);
  1078. for(BuildingID buildID : toBuild)
  1079. {
  1080. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  1081. if (canBuild == EBuildingState::HAVE_CAPITAL
  1082. || canBuild == EBuildingState::FORBIDDEN
  1083. || canBuild == EBuildingState::NO_WATER)
  1084. return false; //we won't be able to build this
  1085. }
  1086. if (maxDays && toBuild.size() > maxDays)
  1087. return false;
  1088. TResources currentRes = cb->getResourceAmount();
  1089. TResources income = estimateIncome();
  1090. //TODO: calculate if we have enough resources to build it in maxDays
  1091. for(const auto & buildID : toBuild)
  1092. {
  1093. const CBuilding *b = t->town->buildings[buildID];
  1094. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  1095. if(canBuild == EBuildingState::ALLOWED)
  1096. {
  1097. if(!containsSavedRes(b->resources))
  1098. {
  1099. logAi->debugStream() << boost::format("Player %d will build %s in town of %s at %s") % playerID % b->Name() % t->name % t->pos;
  1100. cb->buildBuilding(t, buildID);
  1101. return true;
  1102. }
  1103. continue;
  1104. }
  1105. else if(canBuild == EBuildingState::NO_RESOURCES)
  1106. {
  1107. TResources cost = t->town->buildings[buildID]->resources;
  1108. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1109. {
  1110. int diff = currentRes[i] - cost[i] + income[i];
  1111. if(diff < 0)
  1112. saving[i] = 1;
  1113. }
  1114. continue;
  1115. }
  1116. }
  1117. return false;
  1118. }
  1119. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  1120. {
  1121. for(const auto & building : buildList)
  1122. {
  1123. if(t->hasBuilt(building))
  1124. continue;
  1125. if (tryBuildStructure(t, building, maxDays))
  1126. return true;
  1127. }
  1128. return false; //Can't build anything
  1129. }
  1130. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  1131. {
  1132. for(const auto & building : buildList)
  1133. {
  1134. if(t->hasBuilt(building))
  1135. continue;
  1136. return tryBuildStructure(t, building, maxDays);
  1137. }
  1138. return false;//Nothing to build
  1139. }
  1140. void VCAI::buildStructure(const CGTownInstance * t)
  1141. {
  1142. //TODO make *real* town development system
  1143. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  1144. //TODO: build resource silo, defences when needed
  1145. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  1146. //Set of buildings for different goals. Does not include any prerequisites.
  1147. const BuildingID essential[] = {BuildingID::TAVERN, BuildingID::TOWN_HALL};
  1148. const BuildingID goldSource[] = {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL};
  1149. const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  1150. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  1151. const BuildingID unitsUpgrade[] = { BuildingID::DWELL_LVL_1_UP, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP,
  1152. BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP};
  1153. const BuildingID unitGrowth[] = { BuildingID::FORT, BuildingID::CITADEL, BuildingID::CASTLE, BuildingID::HORDE_1,
  1154. BuildingID::HORDE_1_UPGR, BuildingID::HORDE_2, BuildingID::HORDE_2_UPGR};
  1155. const BuildingID spells[] = {BuildingID::MAGES_GUILD_1, BuildingID::MAGES_GUILD_2, BuildingID::MAGES_GUILD_3,
  1156. BuildingID::MAGES_GUILD_4, BuildingID::MAGES_GUILD_5};
  1157. const BuildingID extra[] = {BuildingID::RESOURCE_SILO, BuildingID::SPECIAL_1, BuildingID::SPECIAL_2, BuildingID::SPECIAL_3,
  1158. BuildingID::SPECIAL_4, BuildingID::SHIPYARD}; // all remaining buildings
  1159. TResources currentRes = cb->getResourceAmount();
  1160. TResources income = estimateIncome();
  1161. if (tryBuildAnyStructure(t, std::vector<BuildingID>(essential, essential + ARRAY_COUNT(essential))))
  1162. return;
  1163. //we're running out of gold - try to build something gold-producing. Multiplier can be tweaked, 6 is minimum due to buildings costs
  1164. if (currentRes[Res::GOLD] < income[Res::GOLD] * 6)
  1165. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1166. return;
  1167. if (cb->getDate(Date::DAY_OF_WEEK) > 6)// last 2 days of week - try to focus on growth
  1168. {
  1169. if (tryBuildNextStructure(t, std::vector<BuildingID>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  1170. return;
  1171. }
  1172. // first in-game week or second half of any week: try build dwellings
  1173. if (cb->getDate(Date::DAY) < 7 || cb->getDate(Date::DAY_OF_WEEK) > 3)
  1174. if (tryBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK)))
  1175. return;
  1176. //try to upgrade dwelling
  1177. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  1178. {
  1179. if (t->hasBuilt(unitsSource[i]) && !t->hasBuilt(unitsUpgrade[i]))
  1180. {
  1181. if (tryBuildStructure(t, unitsUpgrade[i]))
  1182. return;
  1183. }
  1184. }
  1185. //remaining tasks
  1186. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1187. return;
  1188. if (tryBuildNextStructure(t, std::vector<BuildingID>(spells, spells + ARRAY_COUNT(spells))))
  1189. return;
  1190. if (tryBuildAnyStructure(t, std::vector<BuildingID>(extra, extra + ARRAY_COUNT(extra))))
  1191. return;
  1192. }
  1193. bool isSafeToVisit(HeroPtr h, crint3 tile)
  1194. {
  1195. const ui64 heroStrength = h->getTotalStrength(),
  1196. dangerStrength = evaluateDanger(tile, *h);
  1197. if(dangerStrength)
  1198. {
  1199. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  1200. {
  1201. logAi->debugStream() << boost::format("It's, safe for %s to visit tile %s") % h->name % tile;
  1202. return true;
  1203. }
  1204. else
  1205. return false;
  1206. }
  1207. return true; //there's no danger
  1208. }
  1209. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(HeroPtr h)
  1210. {
  1211. validateVisitableObjs();
  1212. std::vector<const CGObjectInstance *> possibleDestinations;
  1213. for(const CGObjectInstance *obj : visitableObjs)
  1214. {
  1215. if(cb->getPathInfo(obj->visitablePos())->reachable() && !obj->wasVisited(playerID) &&
  1216. (obj->tempOwner != playerID || isWeeklyRevisitable(obj))) //flag or get weekly resources / creatures
  1217. possibleDestinations.push_back(obj);
  1218. }
  1219. boost::sort(possibleDestinations, isCloser);
  1220. possibleDestinations.erase(boost::remove_if(possibleDestinations, [&](const CGObjectInstance *obj) -> bool
  1221. {
  1222. const int3 pos = obj->visitablePos();
  1223. if(vstd::contains(alreadyVisited, obj))
  1224. return true;
  1225. if(!isSafeToVisit(h, pos))
  1226. return true;
  1227. if (!shouldVisit(h, obj))
  1228. return true;
  1229. if (vstd::contains(reservedObjs, obj)) //does checking for our own reserved objects make sense? here?
  1230. return true;
  1231. const CGObjectInstance *topObj = cb->getVisitableObjs(pos).back(); //it may be hero visiting this obj
  1232. //we don't try visiting object on which allied or owned hero stands
  1233. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1234. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  1235. return true;
  1236. return false;
  1237. }),possibleDestinations.end());
  1238. return possibleDestinations;
  1239. }
  1240. void VCAI::wander(HeroPtr h)
  1241. {
  1242. while(1)
  1243. {
  1244. validateVisitableObjs();
  1245. std::vector <ObjectIdRef> dests;
  1246. range::copy(reservedHeroesMap[h], std::back_inserter(dests));
  1247. if (!dests.size())
  1248. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  1249. if(!dests.size())
  1250. {
  1251. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  1252. {
  1253. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1254. };
  1255. std::vector<const CGTownInstance *> townsReachable;
  1256. std::vector<const CGTownInstance *> townsNotReachable;
  1257. for(const CGTownInstance *t : cb->getTownsInfo())
  1258. {
  1259. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  1260. {
  1261. if(isReachable(t))
  1262. townsReachable.push_back(t);
  1263. else
  1264. townsNotReachable.push_back(t);
  1265. }
  1266. }
  1267. if(townsReachable.size())
  1268. {
  1269. boost::sort(townsReachable, compareReinforcements);
  1270. dests.emplace_back(townsReachable.back());
  1271. }
  1272. else if(townsNotReachable.size())
  1273. {
  1274. boost::sort(townsNotReachable, compareReinforcements);
  1275. //TODO pick the truly best
  1276. const CGTownInstance *t = townsNotReachable.back();
  1277. 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();
  1278. int3 pos1 = h->pos;
  1279. striveToGoal(CGoal(CLEAR_WAY_TO).settile(t->visitablePos()).sethero(h));
  1280. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  1281. {
  1282. if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size())
  1283. recruitHero(t);
  1284. }
  1285. break;
  1286. }
  1287. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  1288. {
  1289. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1290. erase_if(towns, [](const CGTownInstance *t) -> bool
  1291. {
  1292. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1293. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1294. return true;
  1295. return false;
  1296. });
  1297. boost::sort(towns, compareArmyStrength);
  1298. if(towns.size())
  1299. recruitHero(towns.back());
  1300. break;
  1301. }
  1302. else
  1303. {
  1304. logAi->debugStream() << "Nowhere more to go...";
  1305. break;
  1306. }
  1307. }
  1308. const ObjectIdRef&dest = dests.front();
  1309. logAi->debugStream() << boost::format("Of all %d destinations, object oid=%d seems nice") % dests.size() % dest.id.getNum();
  1310. if(!goVisitObj(dest, h))
  1311. {
  1312. if(!dest)
  1313. {
  1314. logAi->debugStream() << boost::format("Visit attempt made the object (id=%d) gone...") % dest.id.getNum();
  1315. }
  1316. else
  1317. {
  1318. logAi->debugStream() << boost::format("Hero %s apparently used all MPs (%d left)") % h->name % h->movement;
  1319. reserveObject(h, dest); //reserve that object - we predict it will be reached soon
  1320. //removed - do not forget abstract goal so easily
  1321. //setGoal(h, CGoal(VISIT_TILE).sethero(h).settile(dest->visitablePos()));
  1322. }
  1323. break;
  1324. }
  1325. if(h->visitedTown)
  1326. {
  1327. townVisitsThisWeek[h].push_back(h->visitedTown);
  1328. buildArmyIn(h->visitedTown);
  1329. break;
  1330. }
  1331. }
  1332. }
  1333. void VCAI::setGoal(HeroPtr h, const CGoal goal)
  1334. { //TODO: check for presence?
  1335. if (goal.goalType == EGoals::INVALID)
  1336. erase_if_present(lockedHeroes, h);
  1337. else
  1338. lockedHeroes[h] = CGoal(goal).setisElementar(false); //always evaluate goals before realizing
  1339. }
  1340. void VCAI::setGoal(HeroPtr h, EGoals goalType)
  1341. {
  1342. if (goalType == EGoals::INVALID)
  1343. erase_if_present(lockedHeroes, h);
  1344. else
  1345. lockedHeroes[h] = CGoal(goalType).setisElementar(false); //always evaluate goals before realizing;
  1346. }
  1347. void VCAI::completeGoal (const CGoal goal)
  1348. {
  1349. if (const CGHeroInstance * h = goal.hero.get(true))
  1350. {
  1351. auto it = lockedHeroes.find(h);
  1352. if (it != lockedHeroes.end())
  1353. if (it->second.goalType == goal.goalType)
  1354. lockedHeroes.erase(it); //goal fulfilled, free hero
  1355. }
  1356. }
  1357. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1358. {
  1359. NET_EVENT_HANDLER;
  1360. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1361. status.setBattle(ONGOING_BATTLE);
  1362. 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
  1363. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->hoverName : "unknown enemy") % tile);
  1364. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1365. }
  1366. void VCAI::battleEnd(const BattleResult *br)
  1367. {
  1368. NET_EVENT_HANDLER;
  1369. assert(status.getBattle() == ONGOING_BATTLE);
  1370. status.setBattle(ENDING_BATTLE);
  1371. bool won = br->winner == myCb->battleGetMySide();
  1372. logAi->debugStream() << boost::format("Player %d: I %s the %s!") % playerID % (won ? "won" : "lost") % battlename;
  1373. battlename.clear();
  1374. CAdventureAI::battleEnd(br);
  1375. }
  1376. void VCAI::waitTillFree()
  1377. {
  1378. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1379. status.waitTillFree();
  1380. }
  1381. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1382. {
  1383. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1384. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1385. (obj->ID == Obj::MONSTER))
  1386. return;
  1387. alreadyVisited.push_back(obj);
  1388. }
  1389. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj)
  1390. {
  1391. reservedObjs.push_back(obj);
  1392. reservedHeroesMap[h].push_back(obj);
  1393. logAi->debugStream() << "reserved object id=" << obj->id << "; address=" << (intptr_t)obj << "; name=" << obj->getHoverText();
  1394. }
  1395. void VCAI::validateVisitableObjs()
  1396. {
  1397. std::vector<const CGObjectInstance *> hlp;
  1398. retreiveVisitableObjs(hlp, true);
  1399. std::string errorMsg;
  1400. auto shouldBeErased = [&](const CGObjectInstance *obj) -> bool
  1401. {
  1402. if(!vstd::contains(hlp, obj))
  1403. {
  1404. logAi->errorStream() << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << errorMsg;
  1405. return true;
  1406. }
  1407. return false;
  1408. };
  1409. //errorMsg is captured by ref so lambda will take the new text
  1410. errorMsg = " shouldn't be on the visitable objects list!";
  1411. erase_if(visitableObjs, shouldBeErased);
  1412. for(auto &p : reservedHeroesMap)
  1413. {
  1414. errorMsg = " shouldn't be on list for hero " + p.first->name + "!";
  1415. erase_if(p.second, shouldBeErased);
  1416. }
  1417. errorMsg = " shouldn't be on the reserved objs list!";
  1418. erase_if(reservedObjs, shouldBeErased);
  1419. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1420. errorMsg = " shouldn't be on the already visited objs list!";
  1421. erase_if(alreadyVisited, shouldBeErased);
  1422. }
  1423. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1424. {
  1425. foreach_tile_pos([&](const int3 &pos)
  1426. {
  1427. for(const CGObjectInstance *obj : myCb->getVisitableObjs(pos, false))
  1428. {
  1429. if(includeOwned || obj->tempOwner != playerID)
  1430. out.push_back(obj);
  1431. }
  1432. });
  1433. }
  1434. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1435. {
  1436. std::vector<const CGObjectInstance *> ret;
  1437. retreiveVisitableObjs(ret, true);
  1438. erase_if(ret, [](const CGObjectInstance *obj)
  1439. {
  1440. return obj->tempOwner != ai->playerID;
  1441. });
  1442. return ret;
  1443. }
  1444. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1445. {
  1446. visitableObjs.push_back(obj);
  1447. helperObjInfo[obj] = ObjInfo(obj);
  1448. }
  1449. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1450. {
  1451. for(const CGObjectInstance *obj : ai->visitableObjs)
  1452. {
  1453. if(obj->ID == 5 && obj->subID == aid)
  1454. return obj;
  1455. }
  1456. return nullptr;
  1457. //TODO what if more than one artifact is available? return them all or some slection criteria
  1458. }
  1459. bool VCAI::isAccessible(const int3 &pos)
  1460. {
  1461. //TODO precalculate for speed
  1462. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1463. {
  1464. if(isAccessibleForHero(pos, h))
  1465. return true;
  1466. }
  1467. return false;
  1468. }
  1469. HeroPtr VCAI::getHeroWithGrail() const
  1470. {
  1471. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1472. if(h->hasArt(2)) //grail
  1473. return h;
  1474. return nullptr;
  1475. }
  1476. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> &predicate)
  1477. {
  1478. //TODO smarter definition of unvisited
  1479. for(const CGObjectInstance *obj : visitableObjs)
  1480. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1481. return obj;
  1482. return nullptr;
  1483. }
  1484. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies /*= false*/) const
  1485. {
  1486. cb->setSelection(*h);
  1487. if (!includeAllies)
  1488. { //don't visit tile occupied by allied hero
  1489. for (auto obj : cb->getVisitableObjs(pos))
  1490. {
  1491. if (obj->ID == Obj::HERO && obj->tempOwner == h->tempOwner && obj != h)
  1492. return false;
  1493. }
  1494. }
  1495. return cb->getPathInfo(pos)->reachable();
  1496. }
  1497. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1498. {
  1499. logAi->debugStream() << boost::format("Moving hero %s to tile %s") % h->name % dst;
  1500. int3 startHpos = h->visitablePos();
  1501. bool ret = false;
  1502. if(startHpos == dst)
  1503. {
  1504. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1505. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1506. waitTillFree(); //movement may cause battle or blocking dialog
  1507. ret = true;
  1508. }
  1509. else
  1510. {
  1511. CGPath path;
  1512. cb->getPath2(dst, path);
  1513. if(path.nodes.empty())
  1514. {
  1515. logAi->errorStream() << "Hero " << h->name << " cannot reach " << dst;
  1516. //setGoal(h, INVALID);
  1517. completeGoal (CGoal(VISIT_TILE).sethero(h));
  1518. cb->recalculatePaths();
  1519. throw std::runtime_error("Wrong move order!");
  1520. }
  1521. int i=path.nodes.size()-1;
  1522. for(; i>0; i--)
  1523. {
  1524. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1525. if(path.nodes[i-1].turns)
  1526. {
  1527. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1528. break;
  1529. }
  1530. int3 endpos = path.nodes[i-1].coord;
  1531. if(endpos == h->visitablePos())
  1532. //if (endpos == h->pos)
  1533. continue;
  1534. // if(i > 1)
  1535. // {
  1536. // int3 afterEndPos = path.nodes[i-2].coord;
  1537. // if(afterEndPos.z != endpos.z)
  1538. //
  1539. // }
  1540. //logAi->debugStream() << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos;
  1541. cb->moveHero(*h, CGHeroInstance::convertPosition(endpos, true));
  1542. waitTillFree(); //movement may cause battle or blocking dialog
  1543. boost::this_thread::interruption_point();
  1544. if(!h) //we lost hero - remove all tasks assigned to him/her
  1545. {
  1546. lostHero(h);
  1547. //we need to throw, otherwise hero will be assigned to sth again
  1548. throw std::runtime_error("Hero was lost!");
  1549. break;
  1550. }
  1551. }
  1552. ret = !i;
  1553. }
  1554. if (auto visitedObject = frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1555. {
  1556. performObjectInteraction (visitedObject, h);
  1557. //BNLOG("Hero %s moved from %s to %s at %s", h->name % startHpos % visitedObject->hoverName % h->visitablePos());
  1558. //throw goalFulfilledException (CGoal(GET_OBJ).setobjid(visitedObject->id));
  1559. }
  1560. if(h) //we could have lost hero after last move
  1561. {
  1562. cb->recalculatePaths();
  1563. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1564. {
  1565. throw cannotFulfillGoalException("Invalid path found!");
  1566. }
  1567. }
  1568. logAi->debugStream() << boost::format("Hero %s moved from %s to %s. Returning %d.") % h->name % startHpos % h->visitablePos() % ret;
  1569. return ret;
  1570. }
  1571. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  1572. { //TODO: do not explore dead-end boundaries
  1573. int ret = 0;
  1574. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  1575. {
  1576. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  1577. {
  1578. int3 npos = int3(x,y,pos.z);
  1579. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  1580. {
  1581. if (!boundaryBetweenTwoPoints (pos, npos))
  1582. ret++;
  1583. }
  1584. }
  1585. }
  1586. return ret;
  1587. }
  1588. bool boundaryBetweenTwoPoints (int3 pos1, int3 pos2) //determines if two points are separated by known barrier
  1589. {
  1590. int xMin = std::min (pos1.x, pos2.x);
  1591. int xMax = std::max (pos1.x, pos2.x);
  1592. int yMin = std::min (pos1.y, pos2.y);
  1593. int yMax = std::max (pos1.y, pos2.y);
  1594. for (int x = xMin; x <= xMax; ++x)
  1595. {
  1596. for (int y = yMin; y <= yMax; ++y)
  1597. {
  1598. int3 tile = int3(x, y, pos1.z); //use only on same level, ofc
  1599. if (abs(pos1.dist2d(tile) - pos2.dist2d(tile)) < 1.5)
  1600. {
  1601. if (!(cb->isVisible(tile) && cb->getTile(tile)->blocked)) //if there's invisible or unblocked tile inbetween, it's good
  1602. return false;
  1603. }
  1604. }
  1605. }
  1606. return true; //if all are visible and blocked, we're at dead end
  1607. }
  1608. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  1609. {
  1610. return howManyTilesWillBeDiscovered(pos + dir, radious);
  1611. }
  1612. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  1613. {
  1614. for(const int3 &tile : tiles)
  1615. {
  1616. foreach_neighbour(tile, [&](int3 neighbour)
  1617. {
  1618. if(cb->isVisible(neighbour))
  1619. out.push_back(neighbour);
  1620. });
  1621. }
  1622. }
  1623. void VCAI::tryRealize(CGoal g)
  1624. {
  1625. logAi->debugStream() << boost::format("Attempting realizing goal with code %s") % g.name();
  1626. switch(g.goalType)
  1627. {
  1628. case EXPLORE:
  1629. {
  1630. throw cannotFulfillGoalException("EXPLORE is not a elementar goal!");
  1631. }
  1632. break;
  1633. case RECRUIT_HERO:
  1634. {
  1635. if(const CGTownInstance *t = findTownWithTavern())
  1636. {
  1637. recruitHero(t, true);
  1638. //TODO jezeli miasto jest zablokowane, sprobowac oczyscic wejscie
  1639. }
  1640. //TODO karkolomna alternatywa - tawerna na mapie przygod lub wiezienie (nie wiem, czy warto?)
  1641. }
  1642. break;
  1643. case VISIT_TILE:
  1644. {
  1645. //cb->recalculatePaths();
  1646. if(!g.hero->movement)
  1647. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1648. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1649. {
  1650. logAi->warnStream() << boost::format("Why do I want to move hero %s to tile %s? Already standing on that tile! ") % g.hero->name % g.tile;
  1651. throw goalFulfilledException (g);
  1652. }
  1653. //if(!g.isBlockedBorderGate(g.tile))
  1654. //{
  1655. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1656. {
  1657. throw goalFulfilledException (g);
  1658. }
  1659. //}
  1660. //else
  1661. // throw cannotFulfillGoalException("There's a blocked gate!, we should never be here"); //CLEAR_WAY_TO should get keymaster tent
  1662. }
  1663. break;
  1664. case VISIT_HERO:
  1665. {
  1666. if(!g.hero->movement)
  1667. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1668. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1669. {
  1670. throw goalFulfilledException (g);
  1671. }
  1672. }
  1673. break;
  1674. case BUILD_STRUCTURE:
  1675. {
  1676. const CGTownInstance *t = g.town;
  1677. if(!t && g.hero)
  1678. t = g.hero->visitedTown;
  1679. if(!t)
  1680. {
  1681. for(const CGTownInstance *t : cb->getTownsInfo())
  1682. {
  1683. switch(cb->canBuildStructure(t, BuildingID(g.bid)))
  1684. {
  1685. case EBuildingState::ALLOWED:
  1686. cb->buildBuilding(t, BuildingID(g.bid));
  1687. return;
  1688. default:
  1689. break;
  1690. }
  1691. }
  1692. }
  1693. else if(cb->canBuildStructure(t, BuildingID(g.bid)) == EBuildingState::ALLOWED)
  1694. {
  1695. cb->buildBuilding(t, BuildingID(g.bid));
  1696. return;
  1697. }
  1698. throw cannotFulfillGoalException("Cannot build a given structure!");
  1699. }
  1700. break;
  1701. case DIG_AT_TILE:
  1702. {
  1703. assert(g.hero->visitablePos() == g.tile);
  1704. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1705. {
  1706. cb->dig(g.hero.get());
  1707. setGoal(g.hero, INVALID); // finished digging
  1708. }
  1709. else
  1710. {
  1711. ai->lockedHeroes[g.hero] = g; //hero who tries to dig shouldn't do anything else
  1712. throw cannotFulfillGoalException("A hero can't dig!\n");
  1713. }
  1714. }
  1715. break;
  1716. case COLLECT_RES: //TODO: use piles and mines?
  1717. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1718. throw cannotFulfillGoalException("Goal is already fulfilled!");
  1719. if(const CGObjectInstance *obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1720. {
  1721. if(const IMarket *m = IMarket::castFrom(obj, false))
  1722. {
  1723. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1724. {
  1725. if(i == g.resID) continue;
  1726. int toGive, toGet;
  1727. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1728. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1729. //TODO trade only as much as needed
  1730. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1731. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1732. return;
  1733. }
  1734. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1735. }
  1736. else
  1737. {
  1738. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1739. }
  1740. }
  1741. else
  1742. {
  1743. saving[g.resID] = 1;
  1744. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1745. }
  1746. case CONQUER:
  1747. case GATHER_ARMY:
  1748. case BOOST_HERO:
  1749. // TODO: conquer??
  1750. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1751. case BUILD:
  1752. performTypicalActions(); //TODO: separate build and wander
  1753. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1754. case INVALID:
  1755. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1756. default:
  1757. throw cannotFulfillGoalException("Unknown type of goal !");
  1758. }
  1759. }
  1760. const CGTownInstance * VCAI::findTownWithTavern() const
  1761. {
  1762. for(const CGTownInstance *t : cb->getTownsInfo())
  1763. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1764. return t;
  1765. return nullptr;
  1766. }
  1767. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1768. {
  1769. std::vector<HeroPtr> ret;
  1770. boost::copy(cb->getHeroesInfo(), std::back_inserter(ret));
  1771. for(auto h : lockedHeroes)
  1772. {
  1773. //if (!h.second.invalid()) //we can use heroes without valid goal
  1774. if (h.second.goalType == DIG_AT_TILE || !h.first->movement) //experiment: use all heroes that have movement left, TODO: unlock heroes that couldn't realize their goals
  1775. erase_if_present(ret, h.first);
  1776. }
  1777. return ret;
  1778. }
  1779. HeroPtr VCAI::primaryHero() const
  1780. {
  1781. auto hs = cb->getHeroesInfo();
  1782. boost::sort(hs, compareHeroStrength);
  1783. if(hs.empty())
  1784. return nullptr;
  1785. return hs.back();
  1786. }
  1787. void VCAI::endTurn()
  1788. {
  1789. logAi->debugStream() << "Player " << static_cast<int>(playerID.getNum()) << " ends turn";
  1790. if(!status.haveTurn())
  1791. {
  1792. logAi->errorStream() << "Not having turn at the end of turn???";
  1793. }
  1794. do
  1795. {
  1796. cb->endTurn();
  1797. } 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
  1798. logAi->debugStream() << "Player " << static_cast<int>(playerID.getNum()) << " ended turn";
  1799. }
  1800. bool VCAI::fulfillsGoal (CGoal &goal, CGoal &mainGoal)
  1801. {
  1802. if (mainGoal.goalType == GET_OBJ && goal.goalType == VISIT_TILE) //deduce that GET_OBJ was completed by visiting object's tile
  1803. { //TODO: more universal mechanism
  1804. if (cb->getObj(ObjectInstanceID(mainGoal.objid))->visitablePos() == goal.tile)
  1805. return true;
  1806. }
  1807. return false;
  1808. }
  1809. bool VCAI::fulfillsGoal (CGoal &goal, const CGoal &mainGoal)
  1810. {
  1811. if (mainGoal.goalType == GET_OBJ && goal.goalType == VISIT_TILE) //deduce that GET_OBJ was completed by visiting object's tile
  1812. { //TODO: more universal mechanism
  1813. if (cb->getObj(ObjectInstanceID(mainGoal.objid))->visitablePos() == goal.tile)
  1814. return true;
  1815. }
  1816. return false;
  1817. }
  1818. void VCAI::striveToGoal(const CGoal &ultimateGoal)
  1819. {
  1820. if (ultimateGoal.invalid())
  1821. return;
  1822. CGoal abstractGoal;
  1823. while(1)
  1824. {
  1825. CGoal goal = ultimateGoal;
  1826. logAi->debugStream() << boost::format("Striving to goal of type %s") % ultimateGoal.name();
  1827. int maxGoals = 100; //preventing deadlock for mutually dependent goals, FIXME: do not try to realize goal when loop didn't suceed
  1828. while(!goal.isElementar && !goal.isAbstract && maxGoals)
  1829. {
  1830. logAi->debugStream() << boost::format("Considering goal %s") % goal.name();
  1831. try
  1832. {
  1833. boost::this_thread::interruption_point();
  1834. goal = goal.whatToDoToAchieve();
  1835. --maxGoals;
  1836. }
  1837. catch(std::exception &e)
  1838. {
  1839. logAi->debugStream() << boost::format("Goal %s decomposition failed: %s") % goal.name() % e.what();
  1840. //setGoal (goal.hero, INVALID); //test: if we don't know how to realize goal, we should abandon it for now
  1841. return;
  1842. }
  1843. }
  1844. try
  1845. {
  1846. boost::this_thread::interruption_point();
  1847. if (!maxGoals)
  1848. {
  1849. std::runtime_error e("Too many subgoals, don't know what to do");
  1850. throw (e);
  1851. }
  1852. if (goal.hero) //lock this hero to fulfill ultimate goal
  1853. {
  1854. if (maxGoals)
  1855. {
  1856. setGoal(goal.hero, goal);
  1857. }
  1858. else
  1859. {
  1860. setGoal(goal.hero, INVALID); // we seemingly don't know what to do with hero
  1861. }
  1862. }
  1863. if (goal.isAbstract)
  1864. {
  1865. abstractGoal = goal; //allow only one abstract goal per call
  1866. logAi->debugStream() << boost::format("Choosing abstract goal %s") % goal.name();
  1867. break;
  1868. }
  1869. else
  1870. tryRealize(goal);
  1871. boost::this_thread::interruption_point();
  1872. }
  1873. catch(boost::thread_interrupted &e)
  1874. {
  1875. logAi->debugStream() << boost::format("Player %d: Making turn thread received an interruption!") % playerID;
  1876. throw; //rethrow, we want to truly end this thread
  1877. }
  1878. catch(goalFulfilledException &e)
  1879. {
  1880. completeGoal (goal);
  1881. if (fulfillsGoal (goal, ultimateGoal) || maxGoals > 98) //completed goal was main goal //TODO: find better condition
  1882. return;
  1883. }
  1884. catch(std::exception &e)
  1885. {
  1886. logAi->debugStream() << boost::format("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.") % goal.name() % ultimateGoal.name();
  1887. logAi->debugStream() << boost::format("The error message was: %s") % e.what();
  1888. break;
  1889. }
  1890. }
  1891. //TODO: save abstract goals not related to hero
  1892. if (!abstractGoal.invalid()) //try to realize our one goal
  1893. {
  1894. while (1)
  1895. {
  1896. CGoal goal = CGoal(abstractGoal).setisAbstract(false);
  1897. int maxGoals = 50;
  1898. while (!goal.isElementar && maxGoals) //find elementar goal and fulfill it
  1899. {
  1900. try
  1901. {
  1902. boost::this_thread::interruption_point();
  1903. goal = goal.whatToDoToAchieve();
  1904. --maxGoals;
  1905. }
  1906. catch(std::exception &e)
  1907. {
  1908. logAi->debugStream() << boost::format("Goal %s decomposition failed: %s") % goal.name() % e.what();
  1909. //setGoal (goal.hero, INVALID);
  1910. return;
  1911. }
  1912. }
  1913. try
  1914. {
  1915. boost::this_thread::interruption_point();
  1916. if (!maxGoals)
  1917. {
  1918. std::runtime_error e("Too many subgoals, don't know what to do");
  1919. throw (e);
  1920. }
  1921. tryRealize(goal);
  1922. boost::this_thread::interruption_point();
  1923. }
  1924. catch(boost::thread_interrupted &e)
  1925. {
  1926. logAi->debugStream() << boost::format("Player %d: Making turn thread received an interruption!") % playerID;
  1927. throw; //rethrow, we want to truly end this thread
  1928. }
  1929. catch(goalFulfilledException &e)
  1930. {
  1931. completeGoal (goal); //FIXME: deduce that we have realized GET_OBJ goal
  1932. if (fulfillsGoal (goal, abstractGoal) || maxGoals > 98) //completed goal was main goal
  1933. return;
  1934. }
  1935. catch(std::exception &e)
  1936. {
  1937. logAi->debugStream() << boost::format("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.") % goal.name() % ultimateGoal.name();
  1938. logAi->debugStream() << boost::format("The error message was: %s") % e.what();
  1939. break;
  1940. }
  1941. }
  1942. }
  1943. }
  1944. void VCAI::striveToQuest (const QuestInfo &q)
  1945. {
  1946. if (q.quest->missionType && q.quest->progress != CQuest::COMPLETE) //FIXME: quests are never synchronized. Pointer handling needed
  1947. {
  1948. MetaString ms;
  1949. q.quest->getRolloverText(ms, false);
  1950. logAi->debugStream() << boost::format("Trying to realize quest: %s") % ms.toString();
  1951. auto heroes = cb->getHeroesInfo();
  1952. switch (q.quest->missionType)
  1953. {
  1954. case CQuest::MISSION_ART:
  1955. {
  1956. for (auto hero : heroes) //TODO: remove duplicated code?
  1957. {
  1958. if (q.quest->checkQuest(hero))
  1959. {
  1960. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id.getNum()).sethero(hero));
  1961. return;
  1962. }
  1963. }
  1964. for (auto art : q.quest->m5arts)
  1965. {
  1966. striveToGoal (CGoal(GET_ART_TYPE).setaid(art)); //TODO: transport?
  1967. }
  1968. break;
  1969. }
  1970. case CQuest::MISSION_HERO:
  1971. {
  1972. //striveToGoal (CGoal(RECRUIT_HERO));
  1973. for (auto hero : heroes)
  1974. {
  1975. if (q.quest->checkQuest(hero))
  1976. {
  1977. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id.getNum()).sethero(hero));
  1978. return;
  1979. }
  1980. }
  1981. striveToGoal (CGoal(FIND_OBJ).setobjid(Obj::PRISON)); //rule of a thumb - quest heroes usually are locked in prisons
  1982. //BNLOG ("Don't know how to recruit hero with id %d\n", q.quest->m13489val);
  1983. break;
  1984. }
  1985. case CQuest::MISSION_ARMY:
  1986. {
  1987. for (auto hero : heroes)
  1988. {
  1989. if (q.quest->checkQuest(hero)) //veyr bad info - stacks can be split between multiple heroes :(
  1990. {
  1991. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id.getNum()).sethero(hero));
  1992. return;
  1993. }
  1994. }
  1995. for (auto creature : q.quest->m6creatures)
  1996. {
  1997. striveToGoal (CGoal(GATHER_TROOPS).setobjid(creature.type->idNumber).setvalue(creature.count));
  1998. }
  1999. //TODO: exchange armies... oh my
  2000. //BNLOG ("Don't know how to recruit %d of %s\n", (int)(creature.count) % creature.type->namePl);
  2001. break;
  2002. }
  2003. case CQuest::MISSION_RESOURCES:
  2004. {
  2005. if (heroes.size())
  2006. {
  2007. if (q.quest->checkQuest(heroes.front())) //it doesn't matter which hero it is
  2008. {
  2009. striveToGoal (CGoal(VISIT_TILE).settile(q.tile));
  2010. }
  2011. else
  2012. {
  2013. for (int i = 0; i < q.quest->m7resources.size(); ++i)
  2014. {
  2015. if (q.quest->m7resources[i])
  2016. striveToGoal (CGoal(COLLECT_RES).setresID(i).setvalue(q.quest->m7resources[i]));
  2017. }
  2018. }
  2019. }
  2020. else
  2021. striveToGoal (CGoal(RECRUIT_HERO)); //FIXME: checkQuest requires any hero belonging to player :(
  2022. break;
  2023. }
  2024. case CQuest::MISSION_KILL_HERO:
  2025. case CQuest::MISSION_KILL_CREATURE:
  2026. {
  2027. auto obj = cb->getObjByQuestIdentifier(q.quest->m13489val);
  2028. if (obj)
  2029. striveToGoal (CGoal(GET_OBJ).setobjid(obj->id.getNum()));
  2030. else
  2031. striveToGoal (CGoal(VISIT_TILE).settile(q.tile)); //visit seer hut
  2032. break;
  2033. }
  2034. case CQuest::MISSION_PRIMARY_STAT:
  2035. {
  2036. auto heroes = cb->getHeroesInfo();
  2037. for (auto hero : heroes)
  2038. {
  2039. if (q.quest->checkQuest(hero))
  2040. {
  2041. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id.getNum()).sethero(hero));
  2042. return;
  2043. }
  2044. }
  2045. for (int i = 0; i < q.quest->m2stats.size(); ++i)
  2046. {
  2047. logAi->debugStream() << boost::format("Don't know how to increase primary stat %d") % i;
  2048. }
  2049. break;
  2050. }
  2051. case CQuest::MISSION_LEVEL:
  2052. {
  2053. auto heroes = cb->getHeroesInfo();
  2054. for (auto hero : heroes)
  2055. {
  2056. if (q.quest->checkQuest(hero))
  2057. {
  2058. striveToGoal (CGoal(VISIT_TILE).settile(q.tile).sethero(hero)); //TODO: causes infinite loop :/
  2059. return;
  2060. }
  2061. }
  2062. logAi->debugStream() << boost::format("Don't know how to reach hero level %d") % q.quest->m13489val;
  2063. break;
  2064. }
  2065. case CQuest::MISSION_PLAYER:
  2066. {
  2067. if (playerID.getNum() != q.quest->m13489val)
  2068. logAi->debugStream() << boost::format("Can't be player of color %d") % q.quest->m13489val;
  2069. break;
  2070. }
  2071. case CQuest::MISSION_KEYMASTER:
  2072. {
  2073. striveToGoal (CGoal(FIND_OBJ).setobjid(Obj::KEYMASTER).setresID(q.obj->subID));
  2074. break;
  2075. }
  2076. }
  2077. }
  2078. }
  2079. void VCAI::performTypicalActions()
  2080. {
  2081. for(const CGTownInstance *t : cb->getTownsInfo())
  2082. {
  2083. logAi->debugStream() << boost::format("Looking into %s") % t->name;
  2084. buildStructure(t);
  2085. buildArmyIn(t);
  2086. if(!ai->primaryHero() ||
  2087. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  2088. {
  2089. recruitHero(t);
  2090. buildArmyIn(t);
  2091. }
  2092. }
  2093. for(auto h : getUnblockedHeroes())
  2094. {
  2095. logAi->debugStream() << boost::format("Looking into %s, MP=%d") % h->name.c_str() % h->movement;
  2096. makePossibleUpgrades(*h);
  2097. cb->setSelection(*h);
  2098. try
  2099. {
  2100. wander(h);
  2101. }
  2102. catch(std::exception &e)
  2103. {
  2104. logAi->debugStream() << boost::format("Cannot use this hero anymore, received exception: %s") % e.what();
  2105. continue;
  2106. }
  2107. }
  2108. }
  2109. void VCAI::buildArmyIn(const CGTownInstance * t)
  2110. {
  2111. makePossibleUpgrades(t->visitingHero);
  2112. makePossibleUpgrades(t);
  2113. recruitCreatures(t);
  2114. moveCreaturesToHero(t);
  2115. }
  2116. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  2117. {
  2118. TimeCheck tc("looking for best exploration neighbour");
  2119. std::map<int3, int> dstToRevealedTiles;
  2120. for(crint3 dir : dirs)
  2121. if(cb->isInTheMap(hpos+dir))
  2122. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  2123. auto best = dstToRevealedTiles.begin();
  2124. best->second *= cb->getPathInfo(best->first)->reachable();
  2125. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  2126. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  2127. {
  2128. const CGPathNode *pn = cb->getPathInfo(i->first);
  2129. //const TerrainTile *t = cb->getTile(i->first);
  2130. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  2131. best = i;
  2132. }
  2133. if(best->second)
  2134. return best->first;
  2135. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2136. }
  2137. int3 VCAI::explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles)
  2138. {
  2139. TimeCheck tc("looking for new exploration point");
  2140. logAi->debugStream() << "Looking for an another place for exploration...";
  2141. tiles.resize(radius);
  2142. foreach_tile_pos([&](const int3 &pos)
  2143. {
  2144. if(!cb->isVisible(pos))
  2145. tiles[0].push_back(pos);
  2146. });
  2147. for (int i = 1; i < radius; i++)
  2148. {
  2149. getVisibleNeighbours(tiles[i-1], tiles[i]);
  2150. removeDuplicates(tiles[i]);
  2151. for(const int3 &tile : tiles[i])
  2152. {
  2153. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius) && !isBlockedBorderGate(tile))
  2154. {
  2155. return tile;
  2156. }
  2157. }
  2158. }
  2159. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  2160. }
  2161. TResources VCAI::estimateIncome() const
  2162. {
  2163. TResources ret;
  2164. for(const CGTownInstance *t : cb->getTownsInfo())
  2165. {
  2166. ret[Res::GOLD] += t->dailyIncome();
  2167. //TODO duplikuje newturn
  2168. if(t->hasBuilt(BuildingID::RESOURCE_SILO)) //there is resource silo
  2169. {
  2170. if(t->town->primaryRes == Res::WOOD_AND_ORE) //we'll give wood and ore
  2171. {
  2172. ret[Res::WOOD] ++;
  2173. ret[Res::ORE] ++;
  2174. }
  2175. else
  2176. {
  2177. ret[t->town->primaryRes] ++;
  2178. }
  2179. }
  2180. }
  2181. for(const CGObjectInstance *obj : getFlaggedObjects())
  2182. {
  2183. if(obj->ID == Obj::MINE)
  2184. {
  2185. switch(obj->subID)
  2186. {
  2187. case Res::WOOD:
  2188. case Res::ORE:
  2189. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  2190. break;
  2191. case Res::GOLD:
  2192. case 7: //abandoned mine -> also gold
  2193. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  2194. break;
  2195. default:
  2196. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  2197. break;
  2198. }
  2199. }
  2200. }
  2201. return ret;
  2202. }
  2203. bool VCAI::containsSavedRes(const TResources &cost) const
  2204. {
  2205. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  2206. {
  2207. if(saving[i] && cost[i])
  2208. return true;
  2209. }
  2210. return false;
  2211. }
  2212. void VCAI::checkHeroArmy (HeroPtr h)
  2213. {
  2214. auto it = lockedHeroes.find(h);
  2215. if (it != lockedHeroes.end())
  2216. {
  2217. if (it->second.goalType == GATHER_ARMY && it->second.value <= h->getArmyStrength())
  2218. completeGoal(CGoal (GATHER_ARMY).sethero(h));
  2219. }
  2220. }
  2221. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2222. {
  2223. logAi->debugStream() << boost::format("Trying to recruit a hero in %s at %s") % t->name % t->visitablePos();
  2224. if(auto availableHero = frontOrNull(cb->getAvailableHeroes(t)))
  2225. cb->recruitHero(t, availableHero);
  2226. else if(throwing)
  2227. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2228. }
  2229. void VCAI::finish()
  2230. {
  2231. if(makingTurn)
  2232. makingTurn->interrupt();
  2233. }
  2234. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  2235. {
  2236. // static boost::mutex m;
  2237. // boost::unique_lock<boost::mutex> mylock(m);
  2238. boost::barrier b(2);
  2239. boost::thread newThread([&b,this,whatToDo]()
  2240. {
  2241. setThreadName("VCAI::requestActionASAP::helper");
  2242. SET_GLOBAL_STATE(this);
  2243. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  2244. b.wait();
  2245. whatToDo();
  2246. });
  2247. b.wait();
  2248. }
  2249. void VCAI::lostHero(HeroPtr h)
  2250. {
  2251. logAi->debugStream() << boost::format("I lost my hero %s. It's best to forget and move on.") % h.name;
  2252. erase_if_present(lockedHeroes, h);
  2253. for(auto obj : reservedHeroesMap[h])
  2254. {
  2255. erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2256. }
  2257. erase_if_present(reservedHeroesMap, h);
  2258. }
  2259. void VCAI::answerQuery(QueryID queryID, int selection)
  2260. {
  2261. logAi->debugStream() << boost::format("I'll answer the query %d giving the choice %d") % queryID % selection;
  2262. if(queryID != QueryID(-1))
  2263. {
  2264. cb->selectionMade(selection, queryID);
  2265. }
  2266. else
  2267. {
  2268. logAi->debugStream() << boost::format("Since the query ID is %d, the answer won't be sent. This is not a real query!") % queryID;
  2269. //do nothing
  2270. }
  2271. }
  2272. void VCAI::requestSent(const CPackForServer *pack, int requestID)
  2273. {
  2274. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2275. if(auto reply = dynamic_cast<const QueryReply*>(pack))
  2276. {
  2277. status.attemptedAnsweringQuery(reply->qid, requestID);
  2278. }
  2279. }
  2280. std::string VCAI::getBattleAIName() const
  2281. {
  2282. if(settings["server"]["neutralAI"].getType() == JsonNode::DATA_STRING)
  2283. return settings["server"]["neutralAI"].String();
  2284. else
  2285. return "StupidAI";
  2286. }
  2287. void VCAI::validateObject(const CGObjectInstance *obj)
  2288. {
  2289. validateObject(obj->id);
  2290. }
  2291. void VCAI::validateObject(ObjectIdRef obj)
  2292. {
  2293. auto matchesId = [&] (const CGObjectInstance *hlpObj) -> bool { return hlpObj->id == obj.id; };
  2294. if(!obj)
  2295. {
  2296. erase_if(visitableObjs, matchesId);
  2297. for(auto &p : reservedHeroesMap)
  2298. erase_if(p.second, matchesId);
  2299. erase_if(reservedObjs, matchesId);
  2300. }
  2301. }
  2302. TResources VCAI::freeResources() const
  2303. {
  2304. TResources myRes = cb->getResourceAmount();
  2305. myRes[Res::GOLD] -= GOLD_RESERVE;
  2306. vstd::amax(myRes[Res::GOLD], 0);
  2307. return myRes;
  2308. }
  2309. AIStatus::AIStatus()
  2310. {
  2311. battle = NO_BATTLE;
  2312. havingTurn = false;
  2313. ongoingHeroMovement = false;
  2314. }
  2315. AIStatus::~AIStatus()
  2316. {
  2317. }
  2318. void AIStatus::setBattle(BattleState BS)
  2319. {
  2320. boost::unique_lock<boost::mutex> lock(mx);
  2321. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2322. battle = BS;
  2323. cv.notify_all();
  2324. }
  2325. BattleState AIStatus::getBattle()
  2326. {
  2327. boost::unique_lock<boost::mutex> lock(mx);
  2328. return battle;
  2329. }
  2330. void AIStatus::addQuery(QueryID ID, std::string description)
  2331. {
  2332. boost::unique_lock<boost::mutex> lock(mx);
  2333. if(ID == QueryID(-1))
  2334. {
  2335. logAi->debugStream() << boost::format("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s") % ID % description;
  2336. return;
  2337. }
  2338. assert(!vstd::contains(remainingQueries, ID));
  2339. assert(ID.getNum() >= 0);
  2340. remainingQueries[ID] = description;
  2341. cv.notify_all();
  2342. logAi->debugStream() << boost::format("Adding query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  2343. }
  2344. void AIStatus::removeQuery(QueryID ID)
  2345. {
  2346. boost::unique_lock<boost::mutex> lock(mx);
  2347. assert(vstd::contains(remainingQueries, ID));
  2348. std::string description = remainingQueries[ID];
  2349. remainingQueries.erase(ID);
  2350. cv.notify_all();
  2351. logAi->debugStream() << boost::format("Removing query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  2352. }
  2353. int AIStatus::getQueriesCount()
  2354. {
  2355. boost::unique_lock<boost::mutex> lock(mx);
  2356. return remainingQueries.size();
  2357. }
  2358. void AIStatus::startedTurn()
  2359. {
  2360. boost::unique_lock<boost::mutex> lock(mx);
  2361. havingTurn = true;
  2362. cv.notify_all();
  2363. }
  2364. void AIStatus::madeTurn()
  2365. {
  2366. boost::unique_lock<boost::mutex> lock(mx);
  2367. havingTurn = false;
  2368. cv.notify_all();
  2369. }
  2370. void AIStatus::waitTillFree()
  2371. {
  2372. boost::unique_lock<boost::mutex> lock(mx);
  2373. while(battle != NO_BATTLE || remainingQueries.size() || objectsBeingVisited.size() || ongoingHeroMovement)
  2374. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  2375. }
  2376. bool AIStatus::haveTurn()
  2377. {
  2378. boost::unique_lock<boost::mutex> lock(mx);
  2379. return havingTurn;
  2380. }
  2381. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2382. {
  2383. boost::unique_lock<boost::mutex> lock(mx);
  2384. assert(vstd::contains(remainingQueries, queryID));
  2385. std::string description = remainingQueries[queryID];
  2386. logAi->debugStream() << boost::format("Attempted answering query %d - %s. Request id=%d. Waiting for results...") % queryID % description % answerRequestID;
  2387. requestToQueryID[answerRequestID] = queryID;
  2388. }
  2389. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2390. {
  2391. assert(vstd::contains(requestToQueryID, answerRequestID));
  2392. QueryID query = requestToQueryID[answerRequestID];
  2393. assert(vstd::contains(remainingQueries, query));
  2394. requestToQueryID.erase(answerRequestID);
  2395. if(result)
  2396. {
  2397. removeQuery(query);
  2398. }
  2399. else
  2400. {
  2401. logAi->errorStream() << "Something went really wrong, failed to answer query " << query << ": " << remainingQueries[query];
  2402. //TODO safely retry
  2403. }
  2404. }
  2405. void AIStatus::heroVisit(const CGObjectInstance *obj, bool started)
  2406. {
  2407. boost::unique_lock<boost::mutex> lock(mx);
  2408. if(started)
  2409. objectsBeingVisited.push_back(obj);
  2410. else
  2411. {
  2412. assert(objectsBeingVisited.size() == 1);
  2413. objectsBeingVisited.clear();
  2414. }
  2415. cv.notify_all();
  2416. }
  2417. void AIStatus::setMove(bool ongoing)
  2418. {
  2419. boost::unique_lock<boost::mutex> lock(mx);
  2420. ongoingHeroMovement = ongoing;
  2421. cv.notify_all();
  2422. }
  2423. int3 whereToExplore(HeroPtr h)
  2424. {
  2425. //TODO it's stupid and ineffective, write sth better
  2426. cb->setSelection(*h);
  2427. int radius = h->getSightRadious();
  2428. int3 hpos = h->visitablePos();
  2429. //look for nearby objs -> visit them if they're close enouh
  2430. const int DIST_LIMIT = 3;
  2431. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  2432. for(const CGObjectInstance *obj : ai->getPossibleDestinations(h))
  2433. {
  2434. int3 op = obj->visitablePos();
  2435. CGPath p;
  2436. cb->getPath2(op, p);
  2437. if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  2438. nearbyVisitableObjs.push_back(obj);
  2439. }
  2440. boost::sort(nearbyVisitableObjs, isCloser);
  2441. if(nearbyVisitableObjs.size())
  2442. return nearbyVisitableObjs.back()->visitablePos();
  2443. try
  2444. {
  2445. return ai->explorationBestNeighbour(hpos, radius, h);
  2446. }
  2447. catch(cannotFulfillGoalException &e)
  2448. {
  2449. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow]
  2450. try
  2451. {
  2452. return ai->explorationNewPoint(radius, h, tiles);
  2453. }
  2454. catch(cannotFulfillGoalException &e)
  2455. {
  2456. std::map<int, std::vector<int3> > profits;
  2457. {
  2458. TimeCheck tc("Evaluating exploration possibilities");
  2459. tiles[0].clear(); //we can't reach FoW anyway
  2460. for(auto &vt : tiles)
  2461. for(auto &tile : vt)
  2462. profits[howManyTilesWillBeDiscovered(tile, radius)].push_back(tile);
  2463. }
  2464. if(profits.empty())
  2465. return int3 (-1,-1,-1);
  2466. auto bestDest = profits.end();
  2467. bestDest--;
  2468. return bestDest->second.front(); //TODO which is the real best tile?
  2469. }
  2470. }
  2471. }
  2472. TSubgoal CGoal::whatToDoToAchieve()
  2473. {
  2474. logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  2475. switch(goalType)
  2476. {
  2477. case WIN:
  2478. {
  2479. const VictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  2480. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  2481. if(!vc.appliesToAI)
  2482. {
  2483. //TODO deduce victory from human loss condition
  2484. cond = EVictoryConditionType::WINSTANDARD;
  2485. }
  2486. switch(cond)
  2487. {
  2488. case EVictoryConditionType::ARTIFACT:
  2489. return CGoal(GET_ART_TYPE).setaid(vc.objectId);
  2490. case EVictoryConditionType::BEATHERO:
  2491. return CGoal(GET_OBJ).setobjid(vc.obj->id.getNum());
  2492. case EVictoryConditionType::BEATMONSTER:
  2493. return CGoal(GET_OBJ).setobjid(vc.obj->id.getNum());
  2494. case EVictoryConditionType::BUILDCITY:
  2495. //TODO build castle/capitol
  2496. break;
  2497. case EVictoryConditionType::BUILDGRAIL:
  2498. {
  2499. if(auto h = ai->getHeroWithGrail())
  2500. {
  2501. //hero is in a town that can host Grail
  2502. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  2503. {
  2504. const CGTownInstance *t = h->visitedTown;
  2505. return CGoal(BUILD_STRUCTURE).setbid(BuildingID::GRAIL).settown(t);
  2506. }
  2507. else
  2508. {
  2509. auto towns = cb->getTownsInfo();
  2510. towns.erase(boost::remove_if(towns,
  2511. [](const CGTownInstance *t) -> bool
  2512. {
  2513. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  2514. }),
  2515. towns.end());
  2516. boost::sort(towns, isCloser);
  2517. if(towns.size())
  2518. {
  2519. return CGoal(VISIT_TILE).sethero(h).settile(towns.front()->visitablePos());
  2520. }
  2521. }
  2522. }
  2523. double ratio = 0;
  2524. int3 grailPos = cb->getGrailPos(ratio);
  2525. if(ratio > 0.99)
  2526. {
  2527. return CGoal(DIG_AT_TILE).settile(grailPos);
  2528. } //TODO: use FIND_OBJ
  2529. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  2530. {
  2531. return CGoal(GET_OBJ).setobjid(obj->id.getNum());
  2532. }
  2533. else
  2534. return CGoal(EXPLORE);
  2535. }
  2536. break;
  2537. case EVictoryConditionType::CAPTURECITY:
  2538. return CGoal(GET_OBJ).setobjid(vc.obj->id.getNum());
  2539. case EVictoryConditionType::GATHERRESOURCE:
  2540. return CGoal(COLLECT_RES).setresID(static_cast<Res::ERes>(vc.objectId)).setvalue(vc.count);
  2541. //TODO mines? piles? marketplace?
  2542. //save?
  2543. break;
  2544. case EVictoryConditionType::GATHERTROOP:
  2545. return CGoal(GATHER_TROOPS).setobjid(vc.objectId).setvalue(vc.count);
  2546. break;
  2547. case EVictoryConditionType::TAKEDWELLINGS:
  2548. break;
  2549. case EVictoryConditionType::TAKEMINES:
  2550. break;
  2551. case EVictoryConditionType::TRANSPORTITEM:
  2552. break;
  2553. case EVictoryConditionType::WINSTANDARD:
  2554. return CGoal(CONQUER);
  2555. default:
  2556. assert(0);
  2557. }
  2558. }
  2559. break;
  2560. case FIND_OBJ:
  2561. {
  2562. const CGObjectInstance * o = nullptr;
  2563. if (resID > -1) //specified
  2564. {
  2565. for(const CGObjectInstance *obj : ai->visitableObjs)
  2566. {
  2567. if(obj->ID == objid && obj->subID == resID)
  2568. {
  2569. o = obj;
  2570. break; //TODO: consider multiple objects and choose best
  2571. }
  2572. }
  2573. }
  2574. else
  2575. {
  2576. for(const CGObjectInstance *obj : ai->visitableObjs)
  2577. {
  2578. if(obj->ID == objid)
  2579. {
  2580. o = obj;
  2581. break; //TODO: consider multiple objects and choose best
  2582. }
  2583. }
  2584. }
  2585. if (o && isReachable(o))
  2586. return CGoal(GET_OBJ).setobjid(o->id.getNum());
  2587. else
  2588. return CGoal(EXPLORE);
  2589. }
  2590. break;
  2591. case GET_OBJ:
  2592. {
  2593. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  2594. if(!obj)
  2595. return CGoal(EXPLORE);
  2596. int3 pos = obj->visitablePos();
  2597. return CGoal(VISIT_TILE).settile(pos);
  2598. }
  2599. break;
  2600. case VISIT_HERO:
  2601. {
  2602. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  2603. if(!obj)
  2604. return CGoal(EXPLORE);
  2605. int3 pos = obj->visitablePos();
  2606. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  2607. return CGoal(*this).settile(pos).setisElementar(true);
  2608. }
  2609. break;
  2610. case GET_ART_TYPE:
  2611. {
  2612. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  2613. if(alternativeWay.invalid())
  2614. return CGoal(FIND_OBJ).setobjid(Obj::ARTIFACT).setresID(aid);
  2615. }
  2616. break;
  2617. case CLEAR_WAY_TO:
  2618. {
  2619. assert(tile.x >= 0); //set tile
  2620. if(!cb->isVisible(tile))
  2621. {
  2622. logAi->errorStream() << "Clear way should be used with visible tiles!";
  2623. return CGoal(EXPLORE);
  2624. }
  2625. HeroPtr h = hero ? hero : ai->primaryHero();
  2626. if(!h)
  2627. return CGoal(RECRUIT_HERO);
  2628. cb->setSelection(*h);
  2629. SectorMap sm;
  2630. bool dropToFile = false;
  2631. if(dropToFile) //for debug purposes
  2632. sm.write("test.txt");
  2633. int3 tileToHit = sm.firstTileToGet(h, tile);
  2634. //if(isSafeToVisit(h, tileToHit))
  2635. if(isBlockedBorderGate(tileToHit))
  2636. { //FIXME: this way we'll not visit gate and activate quest :?
  2637. return CGoal(FIND_OBJ).setobjid(Obj::KEYMASTER).setresID(cb->getTile(tileToHit)->visitableObjects.back()->subID);
  2638. }
  2639. //FIXME: this code shouldn't be necessary
  2640. if(tileToHit == tile)
  2641. {
  2642. logAi->errorStream() << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  2643. % tileToHit % tile % h->name % h->visitablePos();
  2644. throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  2645. }
  2646. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  2647. if(topObj && topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  2648. {
  2649. std::string problem = boost::str(boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText());
  2650. throw cannotFulfillGoalException(problem);
  2651. }
  2652. return CGoal(VISIT_TILE).settile(tileToHit).sethero(h); //FIXME:: attempts to visit completely unreachable tile with hero results in stall
  2653. //TODO czy istnieje lepsza droga?
  2654. }
  2655. throw cannotFulfillGoalException("Cannot reach given tile!");
  2656. case EXPLORE:
  2657. {
  2658. auto objs = ai->visitableObjs; //try to use buildings that uncover map
  2659. erase_if(objs, [&](const CGObjectInstance *obj) -> bool
  2660. {
  2661. if (vstd::contains(ai->alreadyVisited, obj))
  2662. return true;
  2663. switch (obj->ID.num)
  2664. {
  2665. case Obj::REDWOOD_OBSERVATORY:
  2666. case Obj::PILLAR_OF_FIRE:
  2667. case Obj::CARTOGRAPHER:
  2668. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  2669. //case Obj::MONOLITH1:
  2670. //case obj::MONOLITH2:
  2671. //case obj::MONOLITH3:
  2672. //case Obj::WHIRLPOOL:
  2673. return false; //do not erase
  2674. break;
  2675. default:
  2676. return true;
  2677. }
  2678. });
  2679. if (objs.size())
  2680. {
  2681. if (hero.get(true))
  2682. {
  2683. for (auto obj : objs)
  2684. {
  2685. auto pos = obj->visitablePos();
  2686. //FIXME: this confition fails if everything but guarded subterranen gate was explored. in this case we should gather army for hero
  2687. if (isSafeToVisit(hero, pos) && ai->isAccessibleForHero(pos, hero))
  2688. return CGoal(VISIT_TILE).settile(pos).sethero(hero);
  2689. }
  2690. }
  2691. else
  2692. {
  2693. for (auto obj : objs)
  2694. {
  2695. auto pos = obj->visitablePos();
  2696. if (ai->isAccessible (pos)) //TODO: check safety?
  2697. return CGoal(VISIT_TILE).settile(pos).sethero(hero);
  2698. }
  2699. }
  2700. }
  2701. if (hero)
  2702. {
  2703. int3 t = whereToExplore(hero);
  2704. if (t.z == -1) //no safe tile to explore - we need to break!
  2705. {
  2706. erase_if (objs, [&](const CGObjectInstance *obj) -> bool
  2707. {
  2708. switch (obj->ID.num)
  2709. {
  2710. case Obj::CARTOGRAPHER:
  2711. case Obj::SUBTERRANEAN_GATE:
  2712. //case Obj::MONOLITH1:
  2713. //case obj::MONOLITH2:
  2714. //case obj::MONOLITH3:
  2715. //case Obj::WHIRLPOOL:
  2716. return false; //do not erase
  2717. break;
  2718. default:
  2719. return true;
  2720. }
  2721. });
  2722. if (objs.size())
  2723. {
  2724. return CGoal (VISIT_TILE).settile(objs.front()->visitablePos()).sethero(hero).setisAbstract(true);
  2725. }
  2726. else
  2727. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  2728. }
  2729. return CGoal(VISIT_TILE).settile(t).sethero(hero);
  2730. }
  2731. auto hs = cb->getHeroesInfo();
  2732. int howManyHeroes = hs.size();
  2733. erase(hs, [](const CGHeroInstance *h)
  2734. {
  2735. return contains(ai->lockedHeroes, h);
  2736. });
  2737. if(hs.empty()) //all heroes are busy. buy new one
  2738. {
  2739. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2740. return CGoal(RECRUIT_HERO);
  2741. else //find mobile hero with weakest army
  2742. {
  2743. hs = cb->getHeroesInfo();
  2744. erase_if(hs, [](const CGHeroInstance *h)
  2745. {
  2746. return !h->movement; //only hero with movement are of interest for us
  2747. });
  2748. if (hs.empty())
  2749. {
  2750. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2751. return CGoal(RECRUIT_HERO);
  2752. else
  2753. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2754. }
  2755. boost::sort(hs, compareMovement); //closer to what?
  2756. }
  2757. }
  2758. const CGHeroInstance *h = hs.front();
  2759. return (*this).sethero(h).setisAbstract(true);
  2760. }
  2761. I_AM_ELEMENTAR;
  2762. case RECRUIT_HERO:
  2763. {
  2764. const CGTownInstance *t = ai->findTownWithTavern();
  2765. if(!t)
  2766. return CGoal(BUILD_STRUCTURE).setbid(BuildingID::TAVERN);
  2767. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  2768. return CGoal(COLLECT_RES).setresID(Res::GOLD).setvalue(HERO_GOLD_COST);
  2769. I_AM_ELEMENTAR;
  2770. }
  2771. break;
  2772. case VISIT_TILE:
  2773. {
  2774. if(!cb->isVisible(tile))
  2775. return CGoal(EXPLORE);
  2776. if(hero && !ai->isAccessibleForHero(tile, hero))
  2777. hero = nullptr;
  2778. if(!hero)
  2779. {
  2780. if(cb->getHeroesInfo().empty())
  2781. {
  2782. return CGoal(RECRUIT_HERO);
  2783. }
  2784. for(const CGHeroInstance *h : cb->getHeroesInfo())
  2785. {
  2786. if(ai->isAccessibleForHero(tile, h))
  2787. {
  2788. hero = h;
  2789. break;
  2790. }
  2791. }
  2792. }
  2793. if(hero)
  2794. {
  2795. if(isSafeToVisit(hero, tile))
  2796. return CGoal(*this).setisElementar(true);
  2797. else
  2798. {
  2799. return CGoal(GATHER_ARMY).sethero(hero).setvalue(evaluateDanger(tile, *hero) * SAFE_ATTACK_CONSTANT); //TODO: should it be abstract?
  2800. }
  2801. }
  2802. else //inaccessible for all heroes
  2803. {
  2804. return CGoal(CLEAR_WAY_TO).settile(tile);
  2805. }
  2806. }
  2807. break;
  2808. case DIG_AT_TILE:
  2809. {
  2810. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  2811. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  2812. {
  2813. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  2814. return CGoal(*this).sethero(h).setisElementar(true);
  2815. }
  2816. return CGoal(VISIT_TILE).settile(tile);
  2817. }
  2818. break;
  2819. case BUILD_STRUCTURE:
  2820. //TODO check res
  2821. //look for town
  2822. //prerequisites?
  2823. I_AM_ELEMENTAR;
  2824. case COLLECT_RES:
  2825. {
  2826. std::vector<const IMarket*> markets;
  2827. std::vector<const CGObjectInstance*> visObjs;
  2828. ai->retreiveVisitableObjs(visObjs, true);
  2829. for(const CGObjectInstance *obj : visObjs)
  2830. {
  2831. if(const IMarket *m = IMarket::castFrom(obj, false))
  2832. {
  2833. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  2834. markets.push_back(m);
  2835. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  2836. markets.push_back(m);
  2837. }
  2838. }
  2839. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  2840. {
  2841. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  2842. });
  2843. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  2844. {
  2845. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  2846. && !ai->isAccessible(market->o->visitablePos());
  2847. }),markets.end());
  2848. if(!markets.size())
  2849. {
  2850. for(const CGTownInstance *t : cb->getTownsInfo())
  2851. {
  2852. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  2853. return CGoal(BUILD_STRUCTURE).settown(t).setbid(BuildingID::MARKETPLACE);
  2854. }
  2855. }
  2856. else
  2857. {
  2858. const IMarket *m = markets.back();
  2859. //attempt trade at back (best prices)
  2860. int howManyCanWeBuy = 0;
  2861. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  2862. {
  2863. if(i == resID) continue;
  2864. int toGive = -1, toReceive = -1;
  2865. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  2866. assert(toGive > 0 && toReceive > 0);
  2867. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  2868. }
  2869. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  2870. {
  2871. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  2872. assert(backObj);
  2873. if(backObj->tempOwner != ai->playerID)
  2874. return CGoal(GET_OBJ).setobjid(m->o->id.getNum());
  2875. return setobjid(m->o->id.getNum()).setisElementar(true);
  2876. }
  2877. }
  2878. }
  2879. return CGoal(INVALID);
  2880. case GATHER_TROOPS:
  2881. {
  2882. std::vector<const CGDwelling *> dwellings;
  2883. for(const CGTownInstance *t : cb->getTownsInfo())
  2884. {
  2885. auto creature = VLC->creh->creatures[objid];
  2886. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  2887. {
  2888. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  2889. if(!creatures)
  2890. continue;
  2891. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  2892. if(upgradeNumber < 0)
  2893. continue;
  2894. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  2895. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  2896. {
  2897. dwellings.push_back(t);
  2898. }
  2899. else
  2900. {
  2901. return CGoal (BUILD_STRUCTURE).settown(t).setbid(bid);
  2902. }
  2903. }
  2904. }
  2905. for (auto obj : ai->visitableObjs)
  2906. {
  2907. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  2908. continue;
  2909. auto d = dynamic_cast<const CGDwelling *>(obj);
  2910. for (auto creature : d->creatures)
  2911. {
  2912. if (creature.first) //there are more than 0 creatures avaliabe
  2913. {
  2914. for (auto type : creature.second)
  2915. {
  2916. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  2917. dwellings.push_back(d);
  2918. }
  2919. }
  2920. }
  2921. }
  2922. if (dwellings.size())
  2923. {
  2924. boost::sort(dwellings, isCloser);
  2925. return CGoal(GET_OBJ).setobjid (dwellings.front()->id.getNum());
  2926. }
  2927. else
  2928. return CGoal(EXPLORE);
  2929. //TODO: exchange troops between heroes
  2930. }
  2931. break;
  2932. case CONQUER: //TODO: put it into a function?
  2933. {
  2934. auto hs = cb->getHeroesInfo();
  2935. int howManyHeroes = hs.size();
  2936. erase(hs, [](const CGHeroInstance *h)
  2937. {
  2938. return contains(ai->lockedHeroes, h);
  2939. });
  2940. if(hs.empty()) //all heroes are busy. buy new one
  2941. {
  2942. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2943. return CGoal(RECRUIT_HERO);
  2944. else //find mobile hero with weakest army
  2945. {
  2946. hs = cb->getHeroesInfo();
  2947. erase_if(hs, [](const CGHeroInstance *h)
  2948. {
  2949. return !h->movement; //only hero with movement are of interest for us
  2950. });
  2951. if (hs.empty())
  2952. {
  2953. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2954. return CGoal(RECRUIT_HERO);
  2955. else
  2956. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2957. }
  2958. boost::sort(hs, compareHeroStrength);
  2959. }
  2960. }
  2961. const CGHeroInstance *h = hs.back();
  2962. cb->setSelection(h);
  2963. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  2964. ai->retreiveVisitableObjs(objs);
  2965. erase_if(objs, [&](const CGObjectInstance *obj)
  2966. {
  2967. return (obj->ID != Obj::TOWN && obj->ID != Obj::HERO) //not town/hero
  2968. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  2969. });
  2970. if (objs.empty()) //experiment - try to conquer dwellings and mines, it should pay off
  2971. {
  2972. ai->retreiveVisitableObjs(objs);
  2973. erase_if(objs, [&](const CGObjectInstance *obj)
  2974. {
  2975. return (obj->ID != Obj::CREATURE_GENERATOR1 && obj->ID != Obj::MINE) //not dwelling or mine
  2976. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  2977. });
  2978. }
  2979. if(objs.empty())
  2980. return CGoal(EXPLORE); //we need to find an enemy
  2981. erase_if(objs, [&](const CGObjectInstance *obj)
  2982. {
  2983. return !isSafeToVisit(h, obj->visitablePos()) || vstd::contains (ai->reservedObjs, obj); //no need to capture same object twice
  2984. });
  2985. if(objs.empty())
  2986. I_AM_ELEMENTAR;
  2987. boost::sort(objs, isCloser);
  2988. for(const CGObjectInstance *obj : objs)
  2989. {
  2990. if (ai->isAccessibleForHero(obj->visitablePos(), h))
  2991. {
  2992. ai->reserveObject(h, obj); //no one else will capture same object until we fail
  2993. if (obj->ID == Obj::HERO)
  2994. return CGoal(VISIT_HERO).sethero(h).setobjid(obj->id.getNum()).setisAbstract(true); //track enemy hero
  2995. else
  2996. return CGoal(VISIT_TILE).sethero(h).settile(obj->visitablePos());
  2997. }
  2998. }
  2999. return CGoal(EXPLORE); //enemy is inaccessible
  3000. }
  3001. break;
  3002. case BUILD:
  3003. I_AM_ELEMENTAR;
  3004. case INVALID:
  3005. I_AM_ELEMENTAR;
  3006. case GATHER_ARMY:
  3007. {
  3008. //TODO: find hero if none set
  3009. assert(hero);
  3010. cb->setSelection(*hero);
  3011. auto compareReinforcements = [this](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  3012. {
  3013. return howManyReinforcementsCanGet(hero, lhs) < howManyReinforcementsCanGet(hero, rhs);
  3014. };
  3015. std::vector<const CGTownInstance *> townsReachable;
  3016. for(const CGTownInstance *t : cb->getTownsInfo())
  3017. {
  3018. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  3019. {
  3020. if(isReachable(t) && !vstd::contains (ai->townVisitsThisWeek[hero], t))
  3021. townsReachable.push_back(t);
  3022. }
  3023. }
  3024. if(townsReachable.size()) //try towns first
  3025. {
  3026. boost::sort(townsReachable, compareReinforcements);
  3027. return CGoal(VISIT_TILE).sethero(hero).settile(townsReachable.back()->visitablePos());
  3028. }
  3029. else
  3030. {
  3031. if (hero == ai->primaryHero()) //we can get army from other heroes
  3032. {
  3033. auto otherHeroes = cb->getHeroesInfo();
  3034. auto heroDummy = hero;
  3035. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  3036. {
  3037. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true) || !ai->canGetArmy(heroDummy.h, h));
  3038. });
  3039. if (otherHeroes.size())
  3040. {
  3041. boost::sort(otherHeroes, compareArmyStrength); //TODO: check if hero has at least one stack more powerful than ours? not likely to fail
  3042. int primaryPath, secondaryPath;
  3043. auto h = otherHeroes.back();
  3044. cb->setSelection(hero.h);
  3045. primaryPath = cb->getPathInfo(h->visitablePos())->turns;
  3046. cb->setSelection(h);
  3047. secondaryPath = cb->getPathInfo(hero->visitablePos())->turns;
  3048. if (primaryPath < secondaryPath)
  3049. return CGoal(VISIT_HERO).setisAbstract(true).setobjid(h->id.getNum()).sethero(hero); //go to the other hero if we are faster
  3050. else
  3051. return CGoal(VISIT_HERO).setisAbstract(true).setobjid(hero->id.getNum()).sethero(h); //let the other hero come to us
  3052. }
  3053. }
  3054. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  3055. ai->retreiveVisitableObjs(objs, true);
  3056. erase_if(objs, [&](const CGObjectInstance *obj)
  3057. {
  3058. if(obj->ID != Obj::CREATURE_GENERATOR1)
  3059. return true;
  3060. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  3061. if(relationToOwner == PlayerRelations::ALLIES)
  3062. return true;
  3063. //Use flagged dwellings only when there are available creatures that we can afford
  3064. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  3065. {
  3066. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  3067. for(auto & creLevel : dwelling->creatures)
  3068. {
  3069. if(creLevel.first)
  3070. {
  3071. for(auto & creatureID : creLevel.second)
  3072. {
  3073. auto creature = VLC->creh->creatures[creatureID];
  3074. if(ai->freeResources().canAfford(creature->cost))
  3075. return false;
  3076. }
  3077. }
  3078. }
  3079. }
  3080. return true;
  3081. });
  3082. if(objs.empty()) //no possible objects, we did eveyrthing already
  3083. return CGoal(EXPLORE).sethero(hero);
  3084. //TODO: check if we can recruit any creatures there, evaluate army
  3085. else
  3086. {
  3087. boost::sort(objs, isCloser);
  3088. HeroPtr h = nullptr;
  3089. for(const CGObjectInstance *obj : objs)
  3090. { //find safe dwelling
  3091. auto pos = obj->visitablePos();
  3092. if (shouldVisit (hero, obj)) //creatures fit in army
  3093. h = hero;
  3094. else
  3095. {
  3096. for(auto ourHero : cb->getHeroesInfo()) //make use of multiple heroes
  3097. {
  3098. if (shouldVisit(ourHero, obj))
  3099. h = ourHero;
  3100. }
  3101. }
  3102. if (h && isSafeToVisit(h, pos) && ai->isAccessibleForHero(pos, h))
  3103. return CGoal(VISIT_TILE).sethero(h).settile(pos);
  3104. }
  3105. }
  3106. }
  3107. return CGoal(EXPLORE).sethero(hero); //find dwelling. use current hero to prevent him from doing nothing.
  3108. }
  3109. break;
  3110. default:
  3111. assert(0);
  3112. }
  3113. return CGoal(EXPLORE);
  3114. }
  3115. TSubgoal CGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  3116. {
  3117. if(obj)
  3118. return CGoal(GET_OBJ).setobjid(obj->id.getNum());
  3119. else
  3120. return CGoal(EXPLORE);
  3121. }
  3122. TSubgoal CGoal::lookForArtSmart(int aid)
  3123. {
  3124. return CGoal(INVALID);
  3125. }
  3126. bool CGoal::invalid() const
  3127. {
  3128. return goalType == INVALID;
  3129. }
  3130. bool isBlockedBorderGate(int3 tileToHit)
  3131. {
  3132. return cb->getTile(tileToHit)->topVisitableId() == Obj::BORDER_GATE
  3133. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  3134. }
  3135. SectorMap::SectorMap()
  3136. {
  3137. // int3 sizes = cb->getMapSize();
  3138. // sector.resize(sizes.x);
  3139. // for(auto &i : sector)
  3140. // i.resize(sizes.y);
  3141. //
  3142. // for(auto &i : sector)
  3143. // for(auto &j : i)
  3144. // j.resize(sizes.z, 0);
  3145. update();
  3146. }
  3147. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  3148. {
  3149. if(t->blocked && !t->visitable)
  3150. {
  3151. sec = NOT_AVAILABLE;
  3152. return true;
  3153. }
  3154. return false;
  3155. }
  3156. bool markIfBlocked(ui8 &sec, crint3 pos)
  3157. {
  3158. return markIfBlocked(sec, pos, cb->getTile(pos));
  3159. }
  3160. void SectorMap::update()
  3161. {
  3162. clear();
  3163. int curSector = 3; //0 is invisible, 1 is not explored
  3164. foreach_tile_pos([&](crint3 pos)
  3165. {
  3166. if(retreiveTile(pos) == NOT_CHECKED)
  3167. {
  3168. if(!markIfBlocked(retreiveTile(pos), pos))
  3169. exploreNewSector(pos, curSector++);
  3170. }
  3171. });
  3172. valid = true;
  3173. }
  3174. void SectorMap::clear()
  3175. {
  3176. sector = cb->getVisibilityMap();
  3177. valid = false;
  3178. }
  3179. bool canBeEmbarkmentPoint(const TerrainTile *t)
  3180. {
  3181. //tile must be free of with unoccupied boat
  3182. return !t->blocked
  3183. || (t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT);
  3184. }
  3185. void SectorMap::exploreNewSector(crint3 pos, int num)
  3186. {
  3187. Sector &s = infoOnSectors[num];
  3188. s.id = num;
  3189. s.water = cb->getTile(pos)->isWater();
  3190. std::queue<int3> toVisit;
  3191. toVisit.push(pos);
  3192. while(toVisit.size())
  3193. {
  3194. int3 curPos = toVisit.front();
  3195. toVisit.pop();
  3196. ui8 &sec = retreiveTile(curPos);
  3197. if(sec == NOT_CHECKED)
  3198. {
  3199. const TerrainTile *t = cb->getTile(curPos);
  3200. if(!markIfBlocked(sec, curPos, t))
  3201. {
  3202. if(t->isWater() == s.water) //sector is only-water or only-land
  3203. {
  3204. sec = num;
  3205. s.tiles.push_back(curPos);
  3206. foreach_neighbour(curPos, [&](crint3 neighPos)
  3207. {
  3208. if(retreiveTile(neighPos) == NOT_CHECKED)
  3209. {
  3210. toVisit.push(neighPos);
  3211. //parent[neighPos] = curPos;
  3212. }
  3213. const TerrainTile *nt = cb->getTile(neighPos, false);
  3214. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  3215. {
  3216. s.embarkmentPoints.push_back(neighPos);
  3217. }
  3218. });
  3219. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  3220. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->visitablePos());
  3221. }
  3222. }
  3223. }
  3224. }
  3225. removeDuplicates(s.embarkmentPoints);
  3226. }
  3227. void SectorMap::write(crstring fname)
  3228. {
  3229. std::ofstream out(fname);
  3230. for(int k = 0; k < cb->getMapSize().z; k++)
  3231. {
  3232. for(int j = 0; j < cb->getMapSize().y; j++)
  3233. {
  3234. for(int i = 0; i < cb->getMapSize().x; i++)
  3235. {
  3236. out << (int)sector[i][j][k] << '\t';
  3237. }
  3238. out << std::endl;
  3239. }
  3240. out << std::endl;
  3241. }
  3242. }
  3243. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  3244. { //TODO: allow polling of remaining creatures in dwelling
  3245. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  3246. dynamic_cast<const CGDwelling *>(obj) ||
  3247. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  3248. return true;
  3249. switch (obj->ID)
  3250. {
  3251. case Obj::STABLES:
  3252. case Obj::MAGIC_WELL:
  3253. case Obj::HILL_FORT:
  3254. return true;
  3255. break;
  3256. case Obj::BORDER_GATE:
  3257. case Obj::BORDERGUARD:
  3258. return (dynamic_cast <const CGKeys *>(obj))->wasMyColorVisited (ai->playerID); //FIXME: they could be revisited sooner than in a week
  3259. break;
  3260. }
  3261. return false;
  3262. }
  3263. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  3264. {
  3265. switch (obj->ID)
  3266. {
  3267. case Obj::BORDERGUARD:
  3268. case Obj::BORDER_GATE:
  3269. {
  3270. for (auto q : ai->myCb->getMyQuests())
  3271. {
  3272. if (q.obj == obj)
  3273. {
  3274. return false; // do not visit guards or gates when wandering
  3275. }
  3276. }
  3277. return true; //we don't have this quest yet
  3278. break;
  3279. }
  3280. case Obj::SEER_HUT:
  3281. case Obj::QUEST_GUARD:
  3282. {
  3283. for (auto q : ai->myCb->getMyQuests())
  3284. {
  3285. if (q.obj == obj)
  3286. {
  3287. if (q.quest->checkQuest(*h))
  3288. return true; //we completed the quest
  3289. else
  3290. return false; //we can't complete this quest
  3291. }
  3292. }
  3293. return true; //we don't have this quest yet
  3294. break;
  3295. }
  3296. case Obj::CREATURE_GENERATOR1:
  3297. {
  3298. if (obj->tempOwner != h->tempOwner)
  3299. return true; //flag just in case
  3300. bool canRecruitCreatures = false;
  3301. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  3302. for(auto level : d->creatures)
  3303. {
  3304. for(auto c : level.second)
  3305. {
  3306. if (h->getSlotFor(CreatureID(c)) != SlotID())
  3307. canRecruitCreatures = true;
  3308. }
  3309. }
  3310. return canRecruitCreatures;
  3311. break;
  3312. }
  3313. case Obj::HILL_FORT:
  3314. {
  3315. for (auto slot : h->Slots())
  3316. {
  3317. if (slot.second->type->upgrades.size())
  3318. return true; //TODO: check price?
  3319. }
  3320. return false;
  3321. break;
  3322. }
  3323. case Obj::MONOLITH1:
  3324. case Obj::MONOLITH2:
  3325. case Obj::MONOLITH3:
  3326. case Obj::WHIRLPOOL:
  3327. //TODO: mechanism for handling monoliths
  3328. return false;
  3329. break;
  3330. case Obj::SCHOOL_OF_MAGIC:
  3331. case Obj::SCHOOL_OF_WAR:
  3332. {
  3333. TResources myRes = ai->myCb->getResourceAmount();
  3334. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  3335. return false;
  3336. }
  3337. break;
  3338. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  3339. if (h->level < 12)
  3340. return false;
  3341. break;
  3342. case Obj::TREE_OF_KNOWLEDGE:
  3343. {
  3344. TResources myRes = ai->myCb->getResourceAmount();
  3345. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  3346. return false;
  3347. }
  3348. break;
  3349. case Obj::MAGIC_WELL:
  3350. return h->mana < h->manaLimit();
  3351. break;
  3352. case Obj::PRISON:
  3353. return ai->myCb->getHeroesInfo().size() < GameConstants::MAX_HEROES_PER_PLAYER;
  3354. break;
  3355. case Obj::BOAT:
  3356. return false;
  3357. //Boats are handled by pathfinder
  3358. }
  3359. if (obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  3360. return false;
  3361. return true;
  3362. }
  3363. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  3364. {
  3365. int sourceSector = retreiveTile(h->visitablePos()),
  3366. destinationSector = retreiveTile(dst);
  3367. if(sourceSector != destinationSector)
  3368. {
  3369. const Sector *src = &infoOnSectors[sourceSector],
  3370. *dst = &infoOnSectors[destinationSector];
  3371. std::map<const Sector*, const Sector*> preds;
  3372. std::queue<const Sector *> sq;
  3373. sq.push(src);
  3374. while(!sq.empty())
  3375. {
  3376. const Sector *s = sq.front();
  3377. sq.pop();
  3378. for(int3 ep : s->embarkmentPoints)
  3379. {
  3380. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  3381. //preds[s].push_back(neigh);
  3382. if(!preds[neigh])
  3383. {
  3384. preds[neigh] = s;
  3385. sq.push(neigh);
  3386. }
  3387. }
  3388. //TODO consider other types of connections between sectors?
  3389. }
  3390. if(!preds[dst])
  3391. {
  3392. write("test.txt");
  3393. ai->completeGoal (CGoal(EXPLORE).sethero(h)); //if we can't find the way, seemingly all tiles were explored
  3394. //TODO: more organized way?
  3395. throw cannotFulfillGoalException(boost::str(boost::format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  3396. }
  3397. std::vector<const Sector*> toTraverse;
  3398. toTraverse.push_back(dst);
  3399. while(toTraverse.back() != src)
  3400. {
  3401. toTraverse.push_back(preds[toTraverse.back()]);
  3402. }
  3403. if(preds[dst])
  3404. {
  3405. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  3406. if(!src->water && sectorToReach->water) //embark
  3407. {
  3408. //embark on ship -> look for an EP with a boat
  3409. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  3410. {
  3411. const TerrainTile *t = cb->getTile(pos);
  3412. return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT
  3413. && retreiveTile(pos) == sectorToReach->id;
  3414. });
  3415. if(firstEP != src->embarkmentPoints.end())
  3416. {
  3417. return *firstEP;
  3418. }
  3419. else
  3420. {
  3421. //we need to find a shipyard with an access to the desired sector's EP
  3422. //TODO what about Summon Boat spell?
  3423. std::vector<const IShipyard *> shipyards;
  3424. for(const CGTownInstance *t : cb->getTownsInfo())
  3425. {
  3426. if(t->hasBuilt(BuildingID::SHIPYARD))
  3427. shipyards.push_back(t);
  3428. }
  3429. std::vector<const CGObjectInstance*> visObjs;
  3430. ai->retreiveVisitableObjs(visObjs, true);
  3431. for(const CGObjectInstance *obj : visObjs)
  3432. {
  3433. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  3434. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  3435. shipyards.push_back(shipyard);
  3436. }
  3437. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  3438. {
  3439. return shipyard->shipyardStatus() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  3440. }),shipyards.end());
  3441. if(!shipyards.size())
  3442. {
  3443. //TODO consider possibility of building shipyard in a town
  3444. throw cannotFulfillGoalException("There is no known shipyard!");
  3445. }
  3446. //we have only shipyards that possibly can build ships onto the appropriate EP
  3447. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  3448. {
  3449. return s->o->tempOwner == ai->playerID;
  3450. });
  3451. if(ownedGoodShipyard != shipyards.end())
  3452. {
  3453. const IShipyard *s = *ownedGoodShipyard;
  3454. TResources shipCost;
  3455. s->getBoatCost(shipCost);
  3456. if(cb->getResourceAmount().canAfford(shipCost))
  3457. {
  3458. int3 ret = s->bestLocation();
  3459. cb->buildBoat(s);
  3460. return ret;
  3461. }
  3462. else
  3463. {
  3464. //TODO gather res
  3465. throw cannotFulfillGoalException("Not enough resources to build a boat");
  3466. }
  3467. }
  3468. else
  3469. {
  3470. //TODO pick best shipyard to take over
  3471. return shipyards.front()->o->visitablePos();
  3472. }
  3473. }
  3474. }
  3475. else if(src->water && !sectorToReach->water)
  3476. {
  3477. //TODO
  3478. //disembark
  3479. }
  3480. else
  3481. {
  3482. //TODO
  3483. //transition between two land/water sectors. Monolith? Whirlpool? ...
  3484. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  3485. }
  3486. }
  3487. else
  3488. {
  3489. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  3490. }
  3491. }
  3492. else
  3493. {
  3494. makeParentBFS(h->visitablePos());
  3495. int3 curtile = dst;
  3496. while(curtile != h->visitablePos())
  3497. {
  3498. if(cb->getPathInfo(curtile)->reachable())
  3499. {
  3500. return curtile;
  3501. }
  3502. else
  3503. {
  3504. auto i = parent.find(curtile);
  3505. if(i != parent.end())
  3506. {
  3507. assert(curtile != i->second);
  3508. curtile = i->second;
  3509. }
  3510. else
  3511. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  3512. }
  3513. }
  3514. }
  3515. throw cannotFulfillGoalException("Impossible happened.");
  3516. }
  3517. void SectorMap::makeParentBFS(crint3 source)
  3518. {
  3519. parent.clear();
  3520. int mySector = retreiveTile(source);
  3521. std::queue<int3> toVisit;
  3522. toVisit.push(source);
  3523. while(toVisit.size())
  3524. {
  3525. int3 curPos = toVisit.front();
  3526. toVisit.pop();
  3527. ui8 &sec = retreiveTile(curPos);
  3528. assert(sec == mySector); //consider only tiles from the same sector
  3529. //const TerrainTile *t = cb->getTile(curPos);
  3530. foreach_neighbour(curPos, [&](crint3 neighPos)
  3531. {
  3532. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  3533. {
  3534. toVisit.push(neighPos);
  3535. parent[neighPos] = curPos;
  3536. }
  3537. });
  3538. }
  3539. }
  3540. unsigned char & SectorMap::retreiveTile(crint3 pos)
  3541. {
  3542. return retreiveTileN(sector, pos);
  3543. }
  3544. const CGObjectInstance * ObjectIdRef::operator->() const
  3545. {
  3546. return cb->getObj(id, false);
  3547. }
  3548. ObjectIdRef::operator const CGObjectInstance*() const
  3549. {
  3550. return cb->getObj(id, false);
  3551. }
  3552. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id) : id(_id)
  3553. {
  3554. }
  3555. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  3556. {
  3557. }
  3558. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  3559. {
  3560. return id < rhs.id;
  3561. }
  3562. HeroPtr::HeroPtr(const CGHeroInstance *H)
  3563. {
  3564. if(!H)
  3565. {
  3566. //init from nullptr should equal to default init
  3567. *this = HeroPtr();
  3568. return;
  3569. }
  3570. h = H;
  3571. name = h->name;
  3572. hid = H->id;
  3573. // infosCount[ai->playerID][hid]++;
  3574. }
  3575. HeroPtr::HeroPtr()
  3576. {
  3577. h = nullptr;
  3578. hid = ObjectInstanceID();
  3579. }
  3580. HeroPtr::~HeroPtr()
  3581. {
  3582. // if(hid >= 0)
  3583. // infosCount[ai->playerID][hid]--;
  3584. }
  3585. bool HeroPtr::operator<(const HeroPtr &rhs) const
  3586. {
  3587. return hid < rhs.hid;
  3588. }
  3589. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
  3590. {
  3591. //TODO? check if these all assertions every time we get info about hero affect efficiency
  3592. //
  3593. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  3594. assert(doWeExpectNull || h);
  3595. if(h)
  3596. {
  3597. auto obj = cb->getObj(hid);
  3598. const bool owned = obj && obj->tempOwner == ai->playerID;
  3599. if(doWeExpectNull && !owned)
  3600. {
  3601. return nullptr;
  3602. }
  3603. else
  3604. {
  3605. assert(obj);
  3606. assert(owned);
  3607. }
  3608. }
  3609. return h;
  3610. }
  3611. const CGHeroInstance * HeroPtr::operator->() const
  3612. {
  3613. return get();
  3614. }
  3615. bool HeroPtr::validAndSet() const
  3616. {
  3617. return get(true);
  3618. }
  3619. const CGHeroInstance * HeroPtr::operator*() const
  3620. {
  3621. return get();
  3622. }