VCAI.cpp 95 KB

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