VCAI.cpp 107 KB

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