VCAI.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685
  1. #include "StdInc.h"
  2. #include "VCAI.h"
  3. #include "../../lib/UnlockGuard.h"
  4. #include "Fuzzy.h"
  5. #include "../../lib/CObjectHandler.h"
  6. #define I_AM_ELEMENTAR return CGoal(*this).setisElementar(true)
  7. CLogger &aiLogger = tlog6;
  8. extern FuzzyHelper *fh;
  9. class CGVisitableOPW;
  10. const int ACTUAL_RESOURCE_COUNT = 7;
  11. const double SAFE_ATTACK_CONSTANT = 1.5;
  12. using namespace vstd;
  13. //one thread may be turn of AI and another will be handling a side effect for AI2
  14. boost::thread_specific_ptr<CCallback> cb;
  15. boost::thread_specific_ptr<VCAI> ai;
  16. // 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. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  35. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  36. #define MAKING_TURN SET_GLOBAL_STATE(this)
  37. 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)
  38. const int HERO_GOLD_COST = 2500;
  39. const int ALLOWED_ROAMING_HEROES = 8;
  40. const int GOLD_MINE_PRODUCTION = 1000, WOOD_ORE_MINE_PRODUCTION = 2, RESOURCE_MINE_PRODUCTION = 1;
  41. std::string goalName(EGoals goalType)
  42. {
  43. switch (goalType)
  44. {
  45. case INVALID:
  46. return "INVALID";
  47. case WIN:
  48. return "WIN";
  49. case CONQUER:
  50. return "CONQUER";
  51. case EXPLORE:
  52. return "EXPLORE";
  53. case GATHER_ARMY:
  54. return "GATHER ARMY";
  55. case VISIT_TILE:
  56. return "VISIT TILE";
  57. case CLEAR_WAY_TO:
  58. return "CLEAR WAY TO";
  59. default:
  60. return boost::lexical_cast<std::string>(goalType);
  61. }
  62. }
  63. bool compareHeroStrength(const CGHeroInstance *h1, const CGHeroInstance *h2)
  64. {
  65. return h1->getTotalStrength() < h2->getTotalStrength();
  66. }
  67. bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
  68. {
  69. return a1->getArmyStrength() < a2->getArmyStrength();
  70. }
  71. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  72. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  73. struct AILogger
  74. {
  75. AILogger()
  76. {
  77. lvl = 0;
  78. }
  79. int lvl;
  80. struct Tab
  81. {
  82. Tab();
  83. ~Tab();
  84. };
  85. } logger;
  86. AILogger::Tab::Tab()
  87. {
  88. logger.lvl++;
  89. }
  90. AILogger::Tab::~Tab()
  91. {
  92. logger.lvl--;
  93. }
  94. struct TimeCheck
  95. {
  96. CStopWatch time;
  97. std::string txt;
  98. TimeCheck(crstring TXT) : txt(TXT)
  99. {
  100. }
  101. ~TimeCheck()
  102. {
  103. BNLOG("Time of %s was %d ms.", txt % time.getDiff());
  104. }
  105. };
  106. template<typename T>
  107. void removeDuplicates(std::vector<T> &vec)
  108. {
  109. boost::sort(vec);
  110. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  111. }
  112. template<typename Range, typename Predicate>
  113. void erase_if(Range &vec, Predicate pred)
  114. {
  115. vec.erase(boost::remove_if(vec, pred),vec.end());
  116. }
  117. struct AtScopeExit
  118. {
  119. boost::function<void()> foo;
  120. AtScopeExit(const boost::function<void()> &FOO) : foo(FOO)
  121. {}
  122. ~AtScopeExit()
  123. {
  124. foo();
  125. }
  126. };
  127. void foreach_tile_pos(boost::function<void(const int3& pos)> foo)
  128. {
  129. for(int i = 0; i < cb->getMapSize().x; i++)
  130. for(int j = 0; j < cb->getMapSize().y; j++)
  131. for(int k = 0; k < cb->getMapSize().z; k++)
  132. foo(int3(i,j,k));
  133. }
  134. void foreach_neighbour(const int3 &pos, boost::function<void(const int3& pos)> foo)
  135. {
  136. BOOST_FOREACH(const int3 &dir, dirs)
  137. {
  138. const int3 n = pos + dir;
  139. if(cb->isInTheMap(n))
  140. foo(pos+dir);
  141. }
  142. }
  143. unsigned char &retreiveTileN(std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  144. {
  145. return vectors[pos.x][pos.y][pos.z];
  146. }
  147. const unsigned char &retreiveTileN(const std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  148. {
  149. return vectors[pos.x][pos.y][pos.z];
  150. }
  151. void foreach_tile(std::vector< std::vector< std::vector<unsigned char> > > &vectors, boost::function<void(unsigned char &in)> foo)
  152. {
  153. for(auto i = vectors.begin(); i != vectors.end(); i++)
  154. for(auto j = i->begin(); j != i->end(); j++)
  155. for(auto z = j->begin(); z != j->end(); z++)
  156. foo(*z);
  157. }
  158. struct ObjInfo
  159. {
  160. int3 pos;
  161. std::string name;
  162. ObjInfo(){}
  163. ObjInfo(const CGObjectInstance *obj)
  164. {
  165. pos = obj->pos;
  166. name = obj->getHoverText();
  167. }
  168. };
  169. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  170. template <typename Container, typename Item>
  171. bool remove_if_present(Container &c, const Item &item)
  172. {
  173. auto i = std::find(c.begin(), c.end(), item);
  174. if (i != c.end())
  175. {
  176. c.erase(i);
  177. return true;
  178. }
  179. return false;
  180. }
  181. template <typename V, typename Item, typename Item2>
  182. bool remove_if_present(std::map<Item,V> & c, const Item2 &item)
  183. {
  184. auto i = c.find(item);
  185. if (i != c.end())
  186. {
  187. c.erase(i);
  188. return true;
  189. }
  190. return false;
  191. }
  192. template <typename Container, typename Pred>
  193. void erase(Container &c, Pred pred)
  194. {
  195. c.erase(boost::remove_if(c, pred), c.end());
  196. }
  197. bool isReachable(const CGObjectInstance *obj)
  198. {
  199. return cb->getPathInfo(obj->visitablePos())->turns < 255;
  200. }
  201. ui64 howManyReinforcementsCanGet(const CGHeroInstance *h, const CGTownInstance *t)
  202. {
  203. ui64 ret = 0;
  204. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  205. std::vector<const CStackInstance *> toMove;
  206. BOOST_FOREACH(auto const slot, t->Slots())
  207. {
  208. //can be merged woth another stack?
  209. TSlot dst = h->getSlotFor(slot.second->getCreatureID());
  210. if(h->hasStackAtSlot(dst))
  211. ret += t->getPower(slot.first);
  212. else
  213. toMove.push_back(slot.second);
  214. }
  215. boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
  216. {
  217. return lhs->getPower() < rhs->getPower();
  218. });
  219. BOOST_REVERSE_FOREACH(const CStackInstance *stack, toMove)
  220. {
  221. if(freeHeroSlots)
  222. {
  223. ret += stack->getPower();
  224. freeHeroSlots--;
  225. }
  226. else
  227. break;
  228. }
  229. return ret;
  230. }
  231. std::string strFromInt3(int3 pos)
  232. {
  233. std::ostringstream oss;
  234. oss << pos;
  235. return oss.str();
  236. }
  237. bool isCloser(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  238. {
  239. const CGPathNode *ln = cb->getPathInfo(lhs->visitablePos()), *rn = cb->getPathInfo(rhs->visitablePos());
  240. if(ln->turns != rn->turns)
  241. return ln->turns < rn->turns;
  242. return (ln->moveRemains > rn->moveRemains);
  243. };
  244. ui64 evaluateDanger(const CGObjectInstance *obj);
  245. ui64 evaluateDanger(crint3 tile)
  246. {
  247. const TerrainTile *t = cb->getTile(tile, false);
  248. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  249. return 190000000; //MUCH
  250. ui64 objectDanger = 0, guardDanger = 0;
  251. if(t->visitable)
  252. objectDanger = evaluateDanger(t->visitableObjects.back());
  253. int3 guardPos = cb->guardingCreaturePosition(tile);
  254. if(guardPos.x >= 0 && guardPos != tile)
  255. guardDanger = evaluateDanger(guardPos);
  256. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  257. return std::max(objectDanger, guardDanger);
  258. return 0;
  259. }
  260. ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
  261. {
  262. const TerrainTile *t = cb->getTile(tile, false);
  263. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  264. return 190000000; //MUCH
  265. ui64 objectDanger = 0, guardDanger = 0;
  266. CArmedInstance * dangerousObject;
  267. if(t->visitable)
  268. {
  269. dangerousObject = dynamic_cast<CArmedInstance*>(t->visitableObjects.back());
  270. objectDanger = evaluateDanger(t->visitableObjects.back()); //unguarded objects can also be dangerous or unhandled
  271. if (dangerousObject)
  272. {
  273. objectDanger *= fh->getTacticalAdvantage (visitor, dangerousObject);
  274. }
  275. }
  276. int3 guardPos = cb->guardingCreaturePosition(tile);
  277. if(guardPos.x >= 0 && guardPos != tile)
  278. guardDanger = evaluateDanger(guardPos, visitor);
  279. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  280. return std::max(objectDanger, guardDanger);
  281. return 0;
  282. }
  283. ui64 evaluateDanger(const CGObjectInstance *obj)
  284. {
  285. if(obj->tempOwner < GameConstants::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID)) //owned or allied objects don't pose any threat
  286. return 0;
  287. switch(obj->ID)
  288. {
  289. case GameConstants::HEROI_TYPE:
  290. {
  291. InfoAboutHero iah;
  292. cb->getHeroInfo(obj, iah);
  293. return iah.army.getStrength();
  294. }
  295. case GameConstants::TOWNI_TYPE:
  296. case Obj::GARRISON: case Obj::GARRISON2: //garrison
  297. {
  298. InfoAboutTown iat;
  299. cb->getTownInfo(obj, iat);
  300. return iat.army.getStrength();
  301. }
  302. case GameConstants::CREI_TYPE:
  303. {
  304. //TODO!!!!!!!!
  305. const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
  306. return cre->getArmyStrength();
  307. }
  308. case Obj::CREATURE_GENERATOR1:
  309. {
  310. const CGDwelling *d = dynamic_cast<const CGDwelling*>(obj);
  311. return d->getArmyStrength();
  312. }
  313. case Obj::CRYPT: //crypt
  314. case Obj::CREATURE_BANK: //crebank
  315. case Obj::DRAGON_UTOPIA:
  316. case Obj::SHIPWRECK: //shipwreck
  317. case Obj::DERELICT_SHIP: //derelict ship
  318. case Obj::PYRAMID:
  319. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  320. case Obj::WHIRLPOOL: //whirlpool
  321. case Obj::MONOLITH1:
  322. case Obj::MONOLITH2:
  323. case Obj::MONOLITH3:
  324. //TODO mechanism for handling monoliths
  325. return 1000000000;
  326. default:
  327. return 0;
  328. }
  329. }
  330. bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  331. {
  332. return evaluateDanger(lhs) < evaluateDanger(rhs);
  333. }
  334. VCAI::VCAI(void)
  335. {
  336. LOG_ENTRY;
  337. myCb = NULL;
  338. battleAIName = "StupidAI";
  339. makingTurn = NULL;
  340. }
  341. VCAI::~VCAI(void)
  342. {
  343. LOG_ENTRY;
  344. }
  345. void VCAI::availableCreaturesChanged(const CGDwelling *town)
  346. {
  347. NET_EVENT_HANDLER;
  348. LOG_ENTRY;
  349. }
  350. void VCAI::heroMoved(const TryMoveHero & details)
  351. {
  352. NET_EVENT_HANDLER;
  353. LOG_ENTRY;
  354. if(details.result == TryMoveHero::TELEPORTATION)
  355. {
  356. const TerrainTile *t1 = cb->getTile(CGHeroInstance::convertPosition(details.start, false), false),
  357. *t2 = cb->getTile(CGHeroInstance::convertPosition(details.end, false), false);
  358. if(!t1 || !t2) //enemy may have teleported to a tile we don't see
  359. return;
  360. if(t1->visitable && t2->visitable)
  361. {
  362. const CGObjectInstance *o1 = t1->visitableObjects.front(),
  363. *o2 = t2->visitableObjects.front();
  364. if(o1->ID == Obj::SUBTERRANEAN_GATE && o2->ID == Obj::SUBTERRANEAN_GATE)
  365. {
  366. knownSubterraneanGates[o1] = o2;
  367. knownSubterraneanGates[o2] = o1;
  368. }
  369. }
  370. }
  371. }
  372. void VCAI::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  373. {
  374. NET_EVENT_HANDLER;
  375. LOG_ENTRY;
  376. }
  377. void VCAI::heroInGarrisonChange(const CGTownInstance *town)
  378. {
  379. NET_EVENT_HANDLER;
  380. LOG_ENTRY;
  381. }
  382. void VCAI::centerView(int3 pos, int focusTime)
  383. {
  384. NET_EVENT_HANDLER;
  385. LOG_ENTRY;
  386. }
  387. void VCAI::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  388. {
  389. NET_EVENT_HANDLER;
  390. LOG_ENTRY;
  391. }
  392. void VCAI::artifactAssembled(const ArtifactLocation &al)
  393. {
  394. NET_EVENT_HANDLER;
  395. LOG_ENTRY;
  396. }
  397. void VCAI::showTavernWindow(const CGObjectInstance *townOrTavern)
  398. {
  399. NET_EVENT_HANDLER;
  400. LOG_ENTRY;
  401. }
  402. void VCAI::showThievesGuildWindow (const CGObjectInstance * obj)
  403. {
  404. NET_EVENT_HANDLER;
  405. LOG_ENTRY;
  406. }
  407. void VCAI::playerBlocked(int reason)
  408. {
  409. NET_EVENT_HANDLER;
  410. LOG_ENTRY;
  411. if (reason == PlayerBlocked::UPCOMING_BATTLE)
  412. status.setBattle(UPCOMING_BATTLE);
  413. }
  414. void VCAI::showPuzzleMap()
  415. {
  416. NET_EVENT_HANDLER;
  417. LOG_ENTRY;
  418. }
  419. void VCAI::showShipyardDialog(const IShipyard *obj)
  420. {
  421. NET_EVENT_HANDLER;
  422. LOG_ENTRY;
  423. }
  424. void VCAI::gameOver(ui8 player, bool victory)
  425. {
  426. NET_EVENT_HANDLER;
  427. LOG_ENTRY;
  428. BNLOG("Player %d: I heard that player %d %s.", playerID % (int)player % (victory ? "won" : "lost"));
  429. if(player == playerID)
  430. {
  431. if(victory)
  432. {
  433. tlog0 << "VCAI: I won! Incredible!\n";
  434. tlog0 << "Turn nr " << myCb->getDate() << std::endl;
  435. }
  436. else
  437. {
  438. tlog0 << "VCAI: Player " << (int)player << " lost. It's me. What a disappointment! :(\n";
  439. }
  440. // //let's make Impossible difficulty finally standing to its name :>
  441. // if(myCb->getStartInfo()->difficulty == 4 && !victory)
  442. // {
  443. // //play dirty: crash the whole engine to avoid lose
  444. // //that way AI is unbeatable!
  445. // *(int*)NULL = 666;
  446. // }
  447. // TODO - at least write some insults on stdout
  448. finish();
  449. }
  450. }
  451. void VCAI::artifactPut(const ArtifactLocation &al)
  452. {
  453. NET_EVENT_HANDLER;
  454. LOG_ENTRY;
  455. }
  456. void VCAI::artifactRemoved(const ArtifactLocation &al)
  457. {
  458. NET_EVENT_HANDLER;
  459. LOG_ENTRY;
  460. }
  461. void VCAI::stacksErased(const StackLocation &location)
  462. {
  463. NET_EVENT_HANDLER;
  464. LOG_ENTRY;
  465. }
  466. void VCAI::artifactDisassembled(const ArtifactLocation &al)
  467. {
  468. NET_EVENT_HANDLER;
  469. LOG_ENTRY;
  470. }
  471. void VCAI::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  472. {
  473. NET_EVENT_HANDLER;
  474. LOG_ENTRY;
  475. if (start)
  476. {
  477. visitedObject = const_cast<CGObjectInstance *>(visitedObj); // remember teh object and wait for return
  478. if(visitedObj->ID != Obj::MONSTER) //TODO: poll bank if it was cleared
  479. alreadyVisited.push_back(visitedObj);
  480. }
  481. }
  482. void VCAI::availableArtifactsChanged(const CGBlackMarket *bm /*= NULL*/)
  483. {
  484. NET_EVENT_HANDLER;
  485. LOG_ENTRY;
  486. }
  487. void VCAI::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  488. {
  489. NET_EVENT_HANDLER;
  490. LOG_ENTRY;
  491. //buildArmyIn(town);
  492. //moveCreaturesToHero(town);
  493. }
  494. void VCAI::tileHidden(const boost::unordered_set<int3, ShashInt3> &pos)
  495. {
  496. NET_EVENT_HANDLER;
  497. LOG_ENTRY;
  498. // BOOST_FOREACH(int3 tile, pos)
  499. // BOOST_FOREACH(const CGObjectInstance *obj, cb->getVisitableObjs(tile))
  500. // remove_if_present(visitableObjs, obj);
  501. visitableObjs.erase(boost::remove_if(visitableObjs, [&](const CGObjectInstance *obj){return !myCb->getObj(obj->id);}), visitableObjs.end());
  502. }
  503. void VCAI::tileRevealed(const boost::unordered_set<int3, ShashInt3> &pos)
  504. {
  505. NET_EVENT_HANDLER;
  506. LOG_ENTRY;
  507. BOOST_FOREACH(int3 tile, pos)
  508. BOOST_FOREACH(const CGObjectInstance *obj, myCb->getVisitableObjs(tile))
  509. addVisitableObj(obj);
  510. }
  511. void VCAI::heroExchangeStarted(si32 hero1, si32 hero2)
  512. {
  513. NET_EVENT_HANDLER;
  514. LOG_ENTRY;
  515. }
  516. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  517. {
  518. NET_EVENT_HANDLER;
  519. LOG_ENTRY;
  520. }
  521. void VCAI::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  522. {
  523. NET_EVENT_HANDLER;
  524. LOG_ENTRY;
  525. }
  526. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  527. {
  528. NET_EVENT_HANDLER;
  529. LOG_ENTRY;
  530. }
  531. void VCAI::stackChangedType(const StackLocation &location, const CCreature &newType)
  532. {
  533. NET_EVENT_HANDLER;
  534. LOG_ENTRY;
  535. }
  536. void VCAI::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  537. {
  538. NET_EVENT_HANDLER;
  539. LOG_ENTRY;
  540. }
  541. void VCAI::newObject(const CGObjectInstance * obj)
  542. {
  543. NET_EVENT_HANDLER;
  544. LOG_ENTRY;
  545. if(obj->isVisitable())
  546. addVisitableObj(obj);
  547. }
  548. void VCAI::objectRemoved(const CGObjectInstance *obj)
  549. {
  550. NET_EVENT_HANDLER;
  551. LOG_ENTRY;
  552. if(remove_if_present(visitableObjs, obj))
  553. assert(obj->isVisitable());
  554. }
  555. void VCAI::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  556. {
  557. NET_EVENT_HANDLER;
  558. LOG_ENTRY;
  559. }
  560. void VCAI::playerBonusChanged(const Bonus &bonus, bool gain)
  561. {
  562. NET_EVENT_HANDLER;
  563. LOG_ENTRY;
  564. }
  565. void VCAI::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  566. {
  567. NET_EVENT_HANDLER;
  568. LOG_ENTRY;
  569. }
  570. void VCAI::heroCreated(const CGHeroInstance*)
  571. {
  572. NET_EVENT_HANDLER;
  573. LOG_ENTRY;
  574. }
  575. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  576. {
  577. NET_EVENT_HANDLER;
  578. LOG_ENTRY;
  579. }
  580. void VCAI::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  581. {
  582. NET_EVENT_HANDLER;
  583. LOG_ENTRY;
  584. }
  585. void VCAI::requestRealized(PackageApplied *pa)
  586. {
  587. NET_EVENT_HANDLER;
  588. LOG_ENTRY;
  589. if(status.haveTurn())
  590. {
  591. if(pa->packType == typeList.getTypeID<EndTurn>())
  592. if(pa->result)
  593. status.madeTurn();
  594. }
  595. if(pa->packType == typeList.getTypeID<QueryReply>())
  596. {
  597. status.removeQuery();
  598. }
  599. }
  600. void VCAI::receivedResource(int type, int val)
  601. {
  602. NET_EVENT_HANDLER;
  603. LOG_ENTRY;
  604. }
  605. void VCAI::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  606. {
  607. NET_EVENT_HANDLER;
  608. LOG_ENTRY;
  609. }
  610. void VCAI::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  611. {
  612. NET_EVENT_HANDLER;
  613. LOG_ENTRY;
  614. }
  615. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  616. {
  617. NET_EVENT_HANDLER;
  618. LOG_ENTRY;
  619. }
  620. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  621. {
  622. NET_EVENT_HANDLER;
  623. LOG_ENTRY;
  624. }
  625. void VCAI::battleResultsApplied()
  626. {
  627. NET_EVENT_HANDLER;
  628. LOG_ENTRY;
  629. assert(status.getBattle() == ENDING_BATTLE);
  630. status.setBattle(NO_BATTLE);
  631. }
  632. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  633. {
  634. NET_EVENT_HANDLER;
  635. LOG_ENTRY;
  636. if(sop->what == ObjProperty::OWNER)
  637. {
  638. if(sop->val == playerID)
  639. remove_if_present(visitableObjs, myCb->getObj(sop->id));
  640. //TODO restore lost obj
  641. }
  642. }
  643. void VCAI::buildChanged(const CGTownInstance *town, int buildingID, int what)
  644. {
  645. NET_EVENT_HANDLER;
  646. LOG_ENTRY;
  647. }
  648. void VCAI::heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain)
  649. {
  650. NET_EVENT_HANDLER;
  651. LOG_ENTRY;
  652. }
  653. void VCAI::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  654. {
  655. NET_EVENT_HANDLER;
  656. LOG_ENTRY;
  657. }
  658. void VCAI::init(CCallback * CB)
  659. {
  660. myCb = CB;
  661. cbc = CB;
  662. NET_EVENT_HANDLER;
  663. LOG_ENTRY;
  664. playerID = myCb->getMyColor();
  665. myCb->waitTillRealize = true;
  666. myCb->unlockGsWhenWaiting = true;
  667. if(!fh)
  668. fh = new FuzzyHelper();
  669. retreiveVisitableObjs(visitableObjs);
  670. }
  671. void VCAI::yourTurn()
  672. {
  673. NET_EVENT_HANDLER;
  674. LOG_ENTRY;
  675. status.startedTurn();
  676. makingTurn = new boost::thread(&VCAI::makeTurn, this);
  677. }
  678. void VCAI::heroGotLevel(const CGHeroInstance *hero, int pskill, std::vector<ui16> &skills, boost::function<void(ui32)> &callback)
  679. {
  680. NET_EVENT_HANDLER;
  681. LOG_ENTRY;
  682. status.addQuery();
  683. callback(0);
  684. }
  685. void VCAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 askID, const int soundID, bool selection, bool cancel)
  686. {
  687. NET_EVENT_HANDLER;
  688. LOG_ENTRY;
  689. int sel = 0;
  690. status.addQuery();
  691. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  692. sel = components.size();
  693. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  694. sel = 1;
  695. cb->selectionMade(sel, askID);
  696. }
  697. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, boost::function<void()> &onEnd)
  698. {
  699. NET_EVENT_HANDLER;
  700. LOG_ENTRY;
  701. status.addQuery();
  702. //you can't request action from action-response thread
  703. //pickBestCreatures (down, up);
  704. onEnd();
  705. }
  706. void VCAI::serialize(COSer<CSaveFile> &h, const int version)
  707. {
  708. NET_EVENT_HANDLER;
  709. LOG_ENTRY;
  710. }
  711. void VCAI::serialize(CISer<CLoadFile> &h, const int version)
  712. {
  713. NET_EVENT_HANDLER;
  714. LOG_ENTRY;
  715. }
  716. void makePossibleUpgrades(const CArmedInstance *obj)
  717. {
  718. if(!obj)
  719. return;
  720. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  721. {
  722. if(const CStackInstance *s = obj->getStackPtr(i))
  723. {
  724. UpgradeInfo ui;
  725. cb->getUpgradeInfo(obj, i, ui);
  726. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  727. {
  728. cb->upgradeCreature(obj, i, ui.newID[0]);
  729. }
  730. }
  731. }
  732. }
  733. void VCAI::makeTurn()
  734. {
  735. MAKING_TURN;
  736. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  737. setThreadName(-1, "VCAI::makeTurn");
  738. BNLOG("Player %d starting turn", playerID);
  739. INDENT;
  740. switch(cb->getDate(1))
  741. {
  742. case 1:
  743. {
  744. townVisitsThisWeek.clear();
  745. std::vector<const CGObjectInstance *> objs;
  746. retreiveVisitableObjs(objs, true);
  747. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  748. {
  749. if (isWeeklyRevisitable(obj))
  750. {
  751. if (!vstd::contains(visitableObjs, obj))
  752. visitableObjs.push_back(obj);
  753. auto o = std::find (alreadyVisited.begin(), alreadyVisited.end(), obj);
  754. if (o != alreadyVisited.end())
  755. alreadyVisited.erase(o);
  756. }
  757. }
  758. }
  759. break;
  760. case 7: //reconsider strategy
  761. {
  762. const CGHeroInstance * h = primaryHero();
  763. if (h) //check if our primary hero can ahndle danger
  764. {
  765. ui64 totalDanger = 0;
  766. int dangerousObjects = 0;
  767. std::vector<const CGObjectInstance *> objs;
  768. retreiveVisitableObjs(objs, false);
  769. BOOST_FOREACH (auto obj, objs)
  770. {
  771. if (evaluateDanger(obj)) //potentilaly dnagerous
  772. {
  773. totalDanger += evaluateDanger (obj->visitablePos(), h);
  774. ++dangerousObjects;
  775. }
  776. }
  777. if (dangerousObjects && totalDanger / dangerousObjects > h->getHeroStrength())
  778. {
  779. setGoal (h, CGoal(GATHER_ARMY).sethero(h));
  780. }
  781. }
  782. }
  783. break;
  784. }
  785. if(cb->getSelectedHero())
  786. cb->recalculatePaths();
  787. makeTurnInternal();
  788. vstd::clear_pointer(makingTurn);
  789. return;
  790. }
  791. void VCAI::makeTurnInternal()
  792. {
  793. saving = 0;
  794. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  795. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  796. moveCreaturesToHero(t);
  797. try
  798. {
  799. striveToGoal(CGoal(WIN));
  800. for (auto hg = lockedHeroes.begin(); hg != lockedHeroes.end(); hg++) //continue our goals
  801. {
  802. striveToGoal (hg->second);
  803. }
  804. striveToGoal(CGoal(BUILD)); //TODO: smarter building management
  805. }
  806. catch(boost::thread_interrupted &e)
  807. {
  808. tlog0 << "Making turn thread has been interrupted. We'll end without calling endTurn.\n";
  809. return;
  810. }
  811. catch(std::exception &e)
  812. {
  813. tlog0 << "Making turn thread has caught an exception: " << e.what() << "\n";
  814. }
  815. endTurn();
  816. }
  817. bool VCAI::goVisitObj(const CGObjectInstance * obj, const CGHeroInstance * h)
  818. {
  819. int3 dst = obj->visitablePos();
  820. BNLOG("%s will try to visit %s at (%s)", h->name % obj->hoverName % strFromInt3(dst));
  821. return moveHeroToTile(dst, h);
  822. }
  823. void VCAI::performObjectInteraction(const CGObjectInstance * obj, const CGHeroInstance * h)
  824. {
  825. switch (obj->ID)
  826. {
  827. case Obj::CREATURE_GENERATOR1:
  828. recruitCreatures(dynamic_cast<const CGDwelling *>(obj));
  829. break;
  830. }
  831. }
  832. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  833. {
  834. if(t->visitingHero && t->armedGarrison())
  835. {
  836. pickBestCreatures (t->visitingHero, t);
  837. }
  838. }
  839. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  840. {
  841. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  842. const CArmedInstance *armies[] = {army, source};
  843. //we calculate total strength for each creature type available in armies
  844. std::map<const CCreature*, int> creToPower;
  845. BOOST_FOREACH(auto armyPtr, armies)
  846. BOOST_FOREACH(auto &i, armyPtr->Slots())
  847. creToPower[i.second->type] += i.second->getPower();
  848. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  849. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  850. 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
  851. {
  852. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  853. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  854. {
  855. return lhs.second < rhs.second;
  856. });
  857. bestArmy.push_back(creIt->first);
  858. creToPower.erase(creIt);
  859. if(creToPower.empty())
  860. break;
  861. }
  862. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  863. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  864. BOOST_FOREACH(auto armyPtr, armies)
  865. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  866. if(armyPtr->getCreature(j) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  867. cb->mergeOrSwapStacks(armyPtr, army, j, i);
  868. //TODO - having now strongest possible army, we may want to think about arranging stacks
  869. }
  870. void VCAI::recruitCreatures(const CGDwelling * d)
  871. {
  872. for(int i = 0; i < d->creatures.size(); i++)
  873. {
  874. if(!d->creatures[i].second.size())
  875. continue;
  876. int count = d->creatures[i].first;
  877. int creID = d->creatures[i].second.back();
  878. // const CCreature *c = VLC->creh->creatures[creID];
  879. // if(containsSavedRes(c->cost))
  880. // continue;
  881. TResources myRes = cb->getResourceAmount();
  882. myRes[Res::GOLD] -= GOLD_RESERVE;
  883. amin(count, myRes / VLC->creh->creatures[creID]->cost);
  884. if(count > 0)
  885. cb->recruitCreatures(d, creID, count, i);
  886. }
  887. }
  888. void VCAI::buildStructure(const CGTownInstance * t)
  889. {
  890. //TODO make *real* town development system
  891. const int buildings[] = {5, 11, 14, 16, 0, 12, 7, 8, 9, 13, 30, 31, 32, 33, 34, 35, 36, 37, 38,
  892. 39, 40, 41, 42, 43, 1, 2, 3, 4, 17, 18, 19, 21, 22, 23};
  893. for(int i = 0; i < ARRAY_COUNT(buildings); i++)
  894. {
  895. if(t->hasBuilt(buildings[i]))
  896. continue;
  897. const CBuilding *b = VLC->buildh->buildings[t->subID][buildings[i]];
  898. int canBuild = cb->canBuildStructure(t, buildings[i]);
  899. if(canBuild == EBuildingState::ALLOWED)
  900. {
  901. if(!containsSavedRes(b->resources))
  902. {
  903. BNLOG("Player %d will build %s in town of %s at %s", playerID % b->Name() % t->name % t->pos);
  904. cb->buildBuilding(t, buildings[i]);
  905. }
  906. break;
  907. }
  908. else if(canBuild == EBuildingState::NO_RESOURCES)
  909. {
  910. TResources mine = cb->getResourceAmount(), cost = VLC->buildh->buildings[t->subID][buildings[i]]->resources,
  911. income = estimateIncome();
  912. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  913. {
  914. int diff = mine[i] - cost[i] + income[i];
  915. if(diff < 0)
  916. saving[i] = 1;
  917. }
  918. continue;
  919. }
  920. }
  921. }
  922. bool isSafeToVisit(const CGHeroInstance *h, crint3 tile)
  923. {
  924. const ui64 heroStrength = h->getTotalStrength(),
  925. dangerStrength = evaluateDanger(tile, h);
  926. if(dangerStrength)
  927. {
  928. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  929. {
  930. BNLOG("It's, safe for %s to visit tile %s", h->name % tile);
  931. return true;
  932. }
  933. else
  934. return false;
  935. }
  936. return true; //there's no danger
  937. }
  938. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(const CGHeroInstance *h)
  939. {
  940. validateVisitableObjs();
  941. std::vector<const CGObjectInstance *> possibleDestinations;
  942. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  943. {
  944. if(cb->getPathInfo(obj->visitablePos())->reachable() &&
  945. (obj->tempOwner != playerID || isWeeklyRevisitable(obj))) //flag or get weekly resources / creatures
  946. possibleDestinations.push_back(obj);
  947. }
  948. boost::sort(possibleDestinations, isCloser);
  949. possibleDestinations.erase(boost::remove_if(possibleDestinations, [&](const CGObjectInstance *obj) -> bool
  950. {
  951. if(vstd::contains(alreadyVisited, obj))
  952. return true;
  953. if(!isSafeToVisit(h, obj->visitablePos()))
  954. return true;
  955. return false;
  956. }),possibleDestinations.end());
  957. return possibleDestinations;
  958. }
  959. void VCAI::wander(const CGHeroInstance * h)
  960. {
  961. while(1)
  962. {
  963. auto dests = getPossibleDestinations(h);
  964. if(!dests.size())
  965. {
  966. PNLOG("Nowhere more to go...\n");
  967. setGoal (h, INVALID);
  968. break;
  969. }
  970. const CGObjectInstance * obj = dests.front();
  971. if(!goVisitObj(obj, h))
  972. {
  973. BNLOG("Hero %s apparently used all MPs (%d left)\n", h->name % h->movement);
  974. alreadyVisited.push_back(obj); //reserve that object - we predict it will be reached soon
  975. setGoal(h, CGoal(VISIT_TILE).sethero(h).settile(obj->visitablePos()));
  976. break;
  977. }
  978. if(h->visitedTown)
  979. {
  980. townVisitsThisWeek[h].push_back(h->visitedTown);
  981. buildArmyIn(h->visitedTown);
  982. break;
  983. }
  984. }
  985. }
  986. void VCAI::setGoal (const CGHeroInstance *h, const CGoal goal)
  987. { //TODO: check for presence?
  988. lockedHeroes[h] = goal;
  989. }
  990. void VCAI::setGoal (const CGHeroInstance *h, EGoals goalType)
  991. {
  992. lockedHeroes[h] = CGoal(goalType);
  993. }
  994. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  995. {
  996. assert(playerID > GameConstants::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  997. status.setBattle(ONGOING_BATTLE);
  998. const TerrainTile *t = myCb->getTile(tile); //may be NULL in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
  999. battlename = boost::str(boost::format("battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (t ? t->visitableObjects.back()->hoverName : "unknown enemy") % tile);
  1000. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1001. }
  1002. void VCAI::battleEnd(const BattleResult *br)
  1003. {
  1004. assert(status.getBattle() == ONGOING_BATTLE);
  1005. status.setBattle(ENDING_BATTLE);
  1006. bool won = br->winner == myCb->battleGetMySide();
  1007. BNLOG("Player %d: I %s the %s!", playerID % (won ? "won" : "lost") % battlename);
  1008. battlename.clear();
  1009. CAdventureAI::battleEnd(br);
  1010. }
  1011. void VCAI::waitTillFree()
  1012. {
  1013. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1014. status.waitTillFree();
  1015. }
  1016. void VCAI::validateVisitableObjs()
  1017. {
  1018. std::vector<const CGObjectInstance *> hlp;
  1019. retreiveVisitableObjs(hlp, true);
  1020. start:
  1021. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1022. if(!vstd::contains(hlp, obj))
  1023. {
  1024. tlog1 << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << " shouldn't be on list!\n";
  1025. remove_if_present(visitableObjs, obj);
  1026. goto start;
  1027. }
  1028. }
  1029. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1030. {
  1031. for(int i = 0; i < cb->getMapSize().x; i++)
  1032. for(int j = 0; j < cb->getMapSize().y; j++)
  1033. for(int k = 0; k < cb->getMapSize().z; k++)
  1034. if(const TerrainTile *t = cb->getTile(int3(i,j,k), false))
  1035. {
  1036. BOOST_FOREACH(const CGObjectInstance *obj, t->visitableObjects)
  1037. {
  1038. if(includeOwned || obj->tempOwner != playerID)
  1039. out.push_back(obj);
  1040. }
  1041. }
  1042. }
  1043. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1044. {
  1045. std::vector<const CGObjectInstance *> ret;
  1046. retreiveVisitableObjs(ret, true);
  1047. erase_if(ret, [](const CGObjectInstance *obj)
  1048. {
  1049. return obj->tempOwner != ai->playerID;
  1050. });
  1051. return ret;
  1052. }
  1053. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1054. {
  1055. visitableObjs.push_back(obj);
  1056. helperObjInfo[obj] = ObjInfo(obj);
  1057. }
  1058. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1059. {
  1060. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  1061. {
  1062. if(obj->ID == 5 && obj->subID == aid)
  1063. return obj;
  1064. }
  1065. return NULL;
  1066. //TODO what if more than one artifact is available? return them all or some slection criteria
  1067. }
  1068. bool VCAI::isAccessible(const int3 &pos)
  1069. {
  1070. //TODO precalculate for speed
  1071. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1072. {
  1073. if(isAccessibleForHero(pos, h))
  1074. return true;
  1075. }
  1076. return false;
  1077. }
  1078. const CGHeroInstance * VCAI::getHeroWithGrail() const
  1079. {
  1080. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1081. if(h->hasArt(2)) //grail
  1082. return h;
  1083. return NULL;
  1084. }
  1085. const CGObjectInstance * VCAI::getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate)
  1086. {
  1087. //TODO smarter definition of unvisited
  1088. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1089. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1090. return obj;
  1091. return NULL;
  1092. }
  1093. bool VCAI::isAccessibleForHero(const int3 & pos, const CGHeroInstance * h) const
  1094. {
  1095. cb->setSelection(h);
  1096. return cb->getPathInfo(pos)->reachable();
  1097. }
  1098. class cannotFulfillGoalException : public std::exception
  1099. {
  1100. std::string msg;
  1101. public:
  1102. explicit cannotFulfillGoalException(crstring _Message) : msg(_Message)
  1103. {
  1104. }
  1105. virtual ~cannotFulfillGoalException() throw ()
  1106. {
  1107. };
  1108. const char *what() const throw () OVERRIDE
  1109. {
  1110. return msg.c_str();
  1111. }
  1112. };
  1113. bool VCAI::moveHeroToTile(int3 dst, const CGHeroInstance * h)
  1114. {
  1115. visitedObject = NULL;
  1116. int3 startHpos = h->visitablePos();
  1117. bool ret = false;
  1118. if(startHpos == dst)
  1119. {
  1120. assert(cb->getTile(dst)->visitableObjects.size() > 1); //there's no point in revisiting tile where there is no visitable object
  1121. cb->moveHero(h,CGHeroInstance::convertPosition(dst, true));
  1122. waitTillFree(); //movement may cause battle or blocking dialog
  1123. ret = true;
  1124. }
  1125. else
  1126. {
  1127. CGPath path;
  1128. cb->getPath2(dst, path);
  1129. if(path.nodes.empty())
  1130. {
  1131. tlog1 << "Hero " << h->name << " cannot reach " << dst << std::endl;
  1132. throw std::runtime_error("Wrong move order!");
  1133. }
  1134. int i=path.nodes.size()-1;
  1135. for(; i>0; i--)
  1136. {
  1137. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1138. if(path.nodes[i-1].turns)
  1139. {
  1140. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1141. break;
  1142. }
  1143. int3 endpos = path.nodes[i-1].coord;
  1144. if(endpos == h->visitablePos())
  1145. continue;
  1146. // if(i > 1)
  1147. // {
  1148. // int3 afterEndPos = path.nodes[i-2].coord;
  1149. // if(afterEndPos.z != endpos.z)
  1150. //
  1151. // }
  1152. //tlog0 << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos << std::endl;
  1153. cb->moveHero(h,CGHeroInstance::convertPosition(endpos, true));
  1154. waitTillFree(); //movement may cause battle or blocking dialog
  1155. boost::this_thread::interruption_point();
  1156. if(h->tempOwner != playerID) //we lost hero
  1157. {
  1158. remove_if_present(lockedHeroes, h);
  1159. break;
  1160. }
  1161. }
  1162. ret = !i;
  1163. }
  1164. if (visitedObject) //we step into something interesting
  1165. performObjectInteraction (visitedObject, h);
  1166. if(h->tempOwner == playerID) //lost hero after last move
  1167. cb->recalculatePaths();
  1168. BNLOG("Hero %s moved from %s to %s", h->name % startHpos % h->visitablePos());
  1169. return ret;
  1170. }
  1171. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  1172. {
  1173. int ret = 0;
  1174. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  1175. {
  1176. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  1177. {
  1178. int3 npos = int3(x,y,pos.z);
  1179. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  1180. {
  1181. ret++;
  1182. }
  1183. }
  1184. }
  1185. return ret;
  1186. }
  1187. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  1188. {
  1189. return howManyTilesWillBeDiscovered(pos + dir, radious);
  1190. }
  1191. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  1192. {
  1193. BOOST_FOREACH(const int3 &tile, tiles)
  1194. {
  1195. foreach_neighbour(tile, [&](int3 neighbour)
  1196. {
  1197. if(cb->isVisible(neighbour))
  1198. out.push_back(neighbour);
  1199. });
  1200. }
  1201. }
  1202. void VCAI::tryRealize(CGoal g)
  1203. {
  1204. BNLOG("Attempting realizing goal with code %d", g.goalType);
  1205. switch(g.goalType)
  1206. {
  1207. case EXPLORE:
  1208. {
  1209. assert(0); //this goal is not elementar!
  1210. }
  1211. break;
  1212. case RECRUIT_HERO:
  1213. {
  1214. if(const CGTownInstance *t = findTownWithTavern())
  1215. {
  1216. //TODO co jesli nie ma dostepnego bohatera?
  1217. //TODO jezeli miasto jest zablokowane, sprobowac oczyscic wejscie
  1218. cb->recruitHero(t, cb->getAvailableHeroes(t)[0]);
  1219. }
  1220. //TODO karkolomna alternatywa - tawerna na mapie przygod lub wiezienie (nie wiem, czy warto?)
  1221. }
  1222. break;
  1223. case VISIT_TILE:
  1224. {
  1225. if(!g.hero->movement)
  1226. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1227. if(!g.isBlockedBorderGate(g.tile))
  1228. {
  1229. if (ai->moveHeroToTile(g.tile, g.hero));
  1230. setGoal (g.hero, INVALID); //this hero reached target and no goal
  1231. }
  1232. else
  1233. throw cannotFulfillGoalException("There's a blocked gate!");
  1234. }
  1235. break;
  1236. case BUILD_STRUCTURE:
  1237. {
  1238. const CGTownInstance *t = g.town;
  1239. if(!t && g.hero)
  1240. t = g.hero->visitedTown;
  1241. if(!t)
  1242. {
  1243. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1244. {
  1245. switch(cb->canBuildStructure(t, g.bid))
  1246. {
  1247. case EBuildingState::ALLOWED:
  1248. cb->buildBuilding(t, g.bid);
  1249. return;
  1250. default:
  1251. break;
  1252. }
  1253. }
  1254. }
  1255. else if(cb->canBuildStructure(t, g.bid) == EBuildingState::ALLOWED)
  1256. {
  1257. cb->buildBuilding(t, g.bid);
  1258. return;
  1259. }
  1260. throw cannotFulfillGoalException("Cannot build a given structure!");
  1261. }
  1262. break;
  1263. case DIG_AT_TILE:
  1264. {
  1265. assert(g.hero->visitablePos() == g.tile);
  1266. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1267. {
  1268. cb->dig (g.hero);
  1269. setGoal (g.hero, INVALID); // finished digging
  1270. }
  1271. else
  1272. {
  1273. ai->lockedHeroes[g.hero] = g; //hero who tries to dig shouldn't do anything else
  1274. throw cannotFulfillGoalException("A hero can't dig!\n");
  1275. }
  1276. }
  1277. break;
  1278. case COLLECT_RES:
  1279. if(const CGObjectInstance *obj = cb->getObj(g.objid, false))
  1280. {
  1281. if(const IMarket *m = IMarket::castFrom(obj, false))
  1282. {
  1283. for (int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  1284. {
  1285. if(i == g.resID) continue;
  1286. int toGive, toGet;
  1287. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1288. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1289. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1290. if(cb->getResourceAmount(g.resID) >= g.value)
  1291. return;
  1292. }
  1293. }
  1294. else
  1295. {
  1296. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1297. }
  1298. }
  1299. else
  1300. {
  1301. saving[g.resID] = 1;
  1302. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1303. }
  1304. case CONQUER:
  1305. case GATHER_ARMY:
  1306. case BOOST_HERO:
  1307. // TODO: conquer??
  1308. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1309. case BUILD:
  1310. performTypicalActions();
  1311. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1312. case INVALID:
  1313. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1314. default:
  1315. throw cannotFulfillGoalException("Unknown type of goal !");
  1316. }
  1317. }
  1318. const CGTownInstance * VCAI::findTownWithTavern() const
  1319. {
  1320. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1321. if(vstd::contains(t->builtBuildings, EBuilding::TAVERN) && !t->visitingHero)
  1322. return t;
  1323. return NULL;
  1324. }
  1325. std::vector<const CGHeroInstance *> VCAI::getUnblockedHeroes() const
  1326. {
  1327. std::vector<const CGHeroInstance *> ret = cb->getHeroesInfo();
  1328. BOOST_FOREACH(auto h, lockedHeroes)
  1329. {
  1330. if (!h.second.invalid()) //we can use heroes without valid goal
  1331. remove_if_present(ret, h.first);
  1332. }
  1333. return ret;
  1334. }
  1335. const CGHeroInstance * VCAI::primaryHero() const
  1336. {
  1337. auto hs = cb->getHeroesInfo();
  1338. boost::sort(hs, compareHeroStrength);
  1339. if(hs.empty())
  1340. return NULL;
  1341. return hs.back();
  1342. }
  1343. void VCAI::endTurn()
  1344. {
  1345. tlog4 << "Player " << playerID << " ends turn\n";
  1346. if(!status.haveTurn())
  1347. {
  1348. tlog1 << "Not having turn at the end of turn???\n";
  1349. }
  1350. do
  1351. {
  1352. cb->endTurn();
  1353. } 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
  1354. tlog4 << "Player " << playerID << " ended turn\n";
  1355. }
  1356. void VCAI::striveToGoal(const CGoal &ultimateGoal)
  1357. {
  1358. if (ultimateGoal.invalid())
  1359. return;
  1360. while(1)
  1361. {
  1362. CGoal goal = ultimateGoal;
  1363. BNLOG("Striving to goal of type %d", ultimateGoal.goalType);
  1364. int maxGoals = 100; //preventing deadlock for mutually dependent goals
  1365. while(!goal.isElementar && maxGoals)
  1366. {
  1367. INDENT;
  1368. BNLOG("Considering goal %s", goalName(goal.goalType));
  1369. try
  1370. {
  1371. boost::this_thread::interruption_point();
  1372. goal = goal.whatToDoToAchieve();
  1373. --maxGoals;
  1374. }
  1375. catch(std::exception &e)
  1376. {
  1377. BNLOG("Goal %s decomposition failed: %s", goalName(goal.goalType) % e.what());
  1378. return;
  1379. }
  1380. }
  1381. try
  1382. {
  1383. boost::this_thread::interruption_point();
  1384. if (goal.hero) //lock this hero to fulfill ultimate goal
  1385. {
  1386. if (maxGoals)
  1387. {
  1388. setGoal (goal.hero, goal);
  1389. }
  1390. else
  1391. {
  1392. setGoal (goal.hero, INVALID); // we seemingly don't know what to do with hero
  1393. }
  1394. }
  1395. tryRealize(goal);
  1396. boost::this_thread::interruption_point();
  1397. }
  1398. catch(boost::thread_interrupted &e)
  1399. {
  1400. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1401. throw; //rethrow, we want to truly end this thread
  1402. }
  1403. catch(std::exception &e)
  1404. {
  1405. BNLOG("Failed to realize subgoal of type %d (greater goal type was %d), I will stop.", goal.goalType % ultimateGoal.goalType);
  1406. BNLOG("The error message was: %s", e.what());
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. void VCAI::performTypicalActions()
  1412. {
  1413. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1414. {
  1415. BNLOG("Looking into %s", t->name);
  1416. buildStructure(t);
  1417. buildArmyIn(t);
  1418. if(!ai->primaryHero() ||
  1419. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  1420. {
  1421. recruitHero(t);
  1422. buildArmyIn(t);
  1423. }
  1424. }
  1425. BOOST_FOREACH(const CGHeroInstance *h, getUnblockedHeroes())
  1426. {
  1427. BNLOG("Looking into %s, MP=%d", h->name.c_str() % h->movement);
  1428. INDENT;
  1429. makePossibleUpgrades(h);
  1430. cb->setSelection(h);
  1431. wander(h);
  1432. }
  1433. }
  1434. void VCAI::buildArmyIn(const CGTownInstance * t)
  1435. {
  1436. makePossibleUpgrades(t->visitingHero);
  1437. makePossibleUpgrades(t);
  1438. recruitCreatures(t);
  1439. moveCreaturesToHero(t);
  1440. }
  1441. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, const CGHeroInstance * h)
  1442. {
  1443. TimeCheck tc("looking for best exploration neighbour");
  1444. std::map<int3, int> dstToRevealedTiles;
  1445. BOOST_FOREACH(crint3 dir, dirs)
  1446. if(cb->isInTheMap(hpos+dir))
  1447. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  1448. auto best = dstToRevealedTiles.begin();
  1449. best->second *= cb->getPathInfo(best->first)->reachable();
  1450. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  1451. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  1452. {
  1453. const CGPathNode *pn = cb->getPathInfo(i->first);
  1454. //const TerrainTile *t = cb->getTile(i->first);
  1455. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  1456. best = i;
  1457. }
  1458. if(best->second)
  1459. return best->first;
  1460. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  1461. }
  1462. int3 VCAI::explorationNewPoint(int radius, const CGHeroInstance * h, std::vector<std::vector<int3> > &tiles)
  1463. {
  1464. TimeCheck tc("looking for new exploration point");
  1465. tlog0 << "Looking for an another place for exploration...\n";
  1466. tiles.resize(radius);
  1467. foreach_tile_pos([&](const int3 &pos)
  1468. {
  1469. if(!cb->isVisible(pos))
  1470. tiles[0].push_back(pos);
  1471. });
  1472. for (int i = 1; i < radius; i++)
  1473. {
  1474. getVisibleNeighbours(tiles[i-1], tiles[i]);
  1475. removeDuplicates(tiles[i]);
  1476. BOOST_FOREACH(const int3 &tile, tiles[i])
  1477. {
  1478. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius))
  1479. {
  1480. return tile;
  1481. }
  1482. }
  1483. }
  1484. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  1485. }
  1486. TResources VCAI::estimateIncome() const
  1487. {
  1488. TResources ret;
  1489. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1490. {
  1491. ret[Res::GOLD] += t->dailyIncome();
  1492. //TODO duplikuje newturn
  1493. if(t->hasBuilt(EBuilding::RESOURCE_SILO)) //there is resource silo
  1494. {
  1495. if(t->town->primaryRes == 127) //we'll give wood and ore
  1496. {
  1497. ret[Res::WOOD] ++;
  1498. ret[Res::ORE] ++;
  1499. }
  1500. else
  1501. {
  1502. ret[t->town->primaryRes] ++;
  1503. }
  1504. }
  1505. }
  1506. BOOST_FOREACH(const CGObjectInstance *obj, getFlaggedObjects())
  1507. {
  1508. if(obj->ID == Obj::MINE)
  1509. {
  1510. switch(obj->subID)
  1511. {
  1512. case Res::WOOD:
  1513. case Res::ORE:
  1514. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  1515. break;
  1516. case Res::GOLD:
  1517. case 7: //abandoned mine -> also gold
  1518. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  1519. break;
  1520. default:
  1521. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  1522. break;
  1523. }
  1524. }
  1525. }
  1526. return ret;
  1527. }
  1528. bool VCAI::containsSavedRes(const TResources &cost) const
  1529. {
  1530. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1531. {
  1532. if(saving[i] && cost[i])
  1533. return true;
  1534. }
  1535. return false;
  1536. }
  1537. void VCAI::recruitHero(const CGTownInstance * t)
  1538. {
  1539. BNLOG("Trying to recruit a hero in %s at %s", t->name % t->visitablePos())
  1540. cb->recruitHero(t, cb->getAvailableHeroes(t).front());
  1541. }
  1542. void VCAI::finish()
  1543. {
  1544. if(makingTurn)
  1545. makingTurn->interrupt();
  1546. }
  1547. AIStatus::AIStatus()
  1548. {
  1549. battle = NO_BATTLE;
  1550. remainingQueries = 0;
  1551. havingTurn = false;
  1552. }
  1553. AIStatus::~AIStatus()
  1554. {
  1555. }
  1556. void AIStatus::setBattle(BattleState BS)
  1557. {
  1558. boost::unique_lock<boost::mutex> lock(mx);
  1559. battle = BS;
  1560. cv.notify_all();
  1561. }
  1562. BattleState AIStatus::getBattle()
  1563. {
  1564. boost::unique_lock<boost::mutex> lock(mx);
  1565. return battle;
  1566. }
  1567. void AIStatus::addQueries(int val)
  1568. {
  1569. boost::unique_lock<boost::mutex> lock(mx);
  1570. remainingQueries += val;
  1571. BNLOG("Changing count of queries by %d, to a total of %d", val % remainingQueries);
  1572. assert(remainingQueries >= 0);
  1573. cv.notify_all();
  1574. }
  1575. void AIStatus::addQuery()
  1576. {
  1577. addQueries(1);
  1578. }
  1579. void AIStatus::removeQuery()
  1580. {
  1581. addQueries(-1);
  1582. }
  1583. int AIStatus::getQueriesCount()
  1584. {
  1585. boost::unique_lock<boost::mutex> lock(mx);
  1586. return remainingQueries;
  1587. }
  1588. void AIStatus::startedTurn()
  1589. {
  1590. boost::unique_lock<boost::mutex> lock(mx);
  1591. havingTurn = true;
  1592. cv.notify_all();
  1593. }
  1594. void AIStatus::madeTurn()
  1595. {
  1596. boost::unique_lock<boost::mutex> lock(mx);
  1597. havingTurn = false;
  1598. cv.notify_all();
  1599. }
  1600. void AIStatus::waitTillFree()
  1601. {
  1602. boost::unique_lock<boost::mutex> lock(mx);
  1603. while(battle != NO_BATTLE || remainingQueries)
  1604. cv.wait(lock);
  1605. }
  1606. bool AIStatus::haveTurn()
  1607. {
  1608. boost::unique_lock<boost::mutex> lock(mx);
  1609. return havingTurn;
  1610. }
  1611. int3 whereToExplore(const CGHeroInstance *h)
  1612. {
  1613. //TODO it's stupid and ineffective, write sth better
  1614. cb->setSelection(h);
  1615. int radius = h->getSightRadious();
  1616. int3 hpos = h->visitablePos();
  1617. //look for nearby objs -> visit them if they're close enouh
  1618. const int DIST_LIMIT = 3;
  1619. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  1620. BOOST_FOREACH(const CGObjectInstance *obj, ai->getPossibleDestinations(h))
  1621. {
  1622. int3 op = obj->visitablePos();
  1623. CGPath p;
  1624. cb->getPath2(op, p);
  1625. if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  1626. nearbyVisitableObjs.push_back(obj);
  1627. }
  1628. boost::sort(nearbyVisitableObjs, isCloser);
  1629. if(nearbyVisitableObjs.size())
  1630. return nearbyVisitableObjs.back()->visitablePos();
  1631. try
  1632. {
  1633. return ai->explorationBestNeighbour(hpos, radius, h);
  1634. }
  1635. catch(cannotFulfillGoalException &e)
  1636. {
  1637. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow], metryka taksówkowa
  1638. try
  1639. {
  1640. return ai->explorationNewPoint(radius, h, tiles);
  1641. }
  1642. catch(cannotFulfillGoalException &e)
  1643. {
  1644. std::map<int, std::vector<int3> > profits;
  1645. {
  1646. TimeCheck tc("Evaluating exploration possibilities");
  1647. tiles[0].clear(); //we can't reach FoW anyway
  1648. BOOST_FOREACH(auto &vt, tiles)
  1649. BOOST_FOREACH(auto &tile, vt)
  1650. profits[howManyTilesWillBeDiscovered(tile, radius)].push_back(tile);
  1651. }
  1652. if(profits.empty())
  1653. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  1654. auto bestDest = profits.end();
  1655. bestDest--;
  1656. return bestDest->second.front(); //TODO which is the real best tile?
  1657. }
  1658. }
  1659. }
  1660. TSubgoal CGoal::whatToDoToAchieve()
  1661. {
  1662. switch(goalType)
  1663. {
  1664. case WIN:
  1665. {
  1666. const CVictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  1667. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  1668. if(!vc.appliesToAI)
  1669. {
  1670. //TODO deduce victory from human loss condition
  1671. cond = EVictoryConditionType::WINSTANDARD;
  1672. }
  1673. switch(cond)
  1674. {
  1675. case EVictoryConditionType::ARTIFACT:
  1676. return CGoal(GET_ART_TYPE).setaid(vc.ID);
  1677. case EVictoryConditionType::BEATHERO:
  1678. return CGoal(GET_OBJ).setobjid(vc.ID);
  1679. case EVictoryConditionType::BEATMONSTER:
  1680. return CGoal(GET_OBJ).setobjid(vc.ID);
  1681. case EVictoryConditionType::BUILDCITY:
  1682. //TODO build castle/capitol
  1683. break;
  1684. case EVictoryConditionType::BUILDGRAIL:
  1685. {
  1686. if(const CGHeroInstance *h = ai->getHeroWithGrail())
  1687. {
  1688. //hero is in a town that can host Grail
  1689. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, EBuilding::GRAIL))
  1690. {
  1691. const CGTownInstance *t = h->visitedTown;
  1692. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::GRAIL).settown(t);
  1693. }
  1694. else
  1695. {
  1696. auto towns = cb->getTownsInfo();
  1697. towns.erase(boost::remove_if(towns,
  1698. [](const CGTownInstance *t) -> bool
  1699. {
  1700. return vstd::contains(t->forbiddenBuildings, EBuilding::GRAIL);
  1701. }),
  1702. towns.end());
  1703. boost::sort(towns, isCloser);
  1704. if(towns.size())
  1705. {
  1706. return CGoal(VISIT_TILE).sethero(h).settile(towns.front()->visitablePos());
  1707. }
  1708. }
  1709. }
  1710. double ratio = 0;
  1711. int3 grailPos = cb->getGrailPos(ratio);
  1712. if(ratio > 0.99)
  1713. {
  1714. return CGoal(DIG_AT_TILE).settile(grailPos);
  1715. }
  1716. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  1717. {
  1718. return CGoal(GET_OBJ).setobjid(obj->id);
  1719. }
  1720. else
  1721. return CGoal(EXPLORE);
  1722. }
  1723. break;
  1724. case EVictoryConditionType::CAPTURECITY:
  1725. return CGoal(GET_OBJ).setobjid(vc.ID);
  1726. case EVictoryConditionType::GATHERRESOURCE:
  1727. return CGoal(COLLECT_RES).setresID(vc.ID).setvalue(vc.count);
  1728. //TODO mines? piles? marketplace?
  1729. //save?
  1730. break;
  1731. case EVictoryConditionType::GATHERTROOP:
  1732. break;
  1733. case EVictoryConditionType::TAKEDWELLINGS:
  1734. break;
  1735. case EVictoryConditionType::TAKEMINES:
  1736. break;
  1737. case EVictoryConditionType::TRANSPORTITEM:
  1738. break;
  1739. case EVictoryConditionType::WINSTANDARD:
  1740. return CGoal(CONQUER);
  1741. default:
  1742. assert(0);
  1743. }
  1744. }
  1745. break;
  1746. case GET_OBJ:
  1747. {
  1748. const CGObjectInstance * obj = cb->getObj(objid);
  1749. if(!obj)
  1750. return CGoal(EXPLORE);
  1751. int3 pos = cb->getObj(objid)->visitablePos();
  1752. return CGoal(VISIT_TILE).settile(pos);
  1753. }
  1754. break;
  1755. case GET_ART_TYPE:
  1756. {
  1757. const CGObjectInstance *artInst = ai->lookForArt(aid);
  1758. if(!artInst)
  1759. {
  1760. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid);
  1761. if(alternativeWay.invalid())
  1762. return CGoal(EXPLORE);
  1763. else
  1764. return alternativeWay;
  1765. }
  1766. else
  1767. return CGoal(GET_OBJ).setobjid(artInst->id);
  1768. }
  1769. break;
  1770. case CLEAR_WAY_TO:
  1771. {
  1772. assert(tile.x >= 0); //set tile
  1773. if(!cb->isVisible(tile))
  1774. {
  1775. tlog1 << "Clear way should be used with visible tiles!\n";
  1776. return CGoal(EXPLORE);
  1777. }
  1778. const CGHeroInstance *h = hero ? hero : ai->primaryHero();
  1779. if(!h)
  1780. return CGoal(RECRUIT_HERO);
  1781. cb->setSelection(h);
  1782. SectorMap sm;
  1783. bool dropToFile = false;
  1784. if(dropToFile) //for debug purposes
  1785. sm.write("test.txt");
  1786. int3 tileToHit = sm.firstTileToGet(h, tile);
  1787. //if(isSafeToVisit(h, tileToHit))
  1788. if(isBlockedBorderGate(tileToHit))
  1789. throw cannotFulfillGoalException("There's blocked border gate!");
  1790. if(tileToHit == tile)
  1791. {
  1792. tlog1 << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  1793. % tileToHit % tile % h->name % h->visitablePos();
  1794. throw cannotFulfillGoalException("Retreiving first tile to hit failed (probably)!");
  1795. }
  1796. return CGoal(VISIT_TILE).settile(tileToHit).sethero(h);
  1797. //TODO czy istnieje lepsza droga?
  1798. }
  1799. throw cannotFulfillGoalException("Cannot reach given tile!");
  1800. //return CGoal(EXPLORE); // TODO improve
  1801. case EXPLORE:
  1802. {
  1803. auto hs = cb->getHeroesInfo();
  1804. int howManyHeroes = hs.size();
  1805. erase(hs, [](const CGHeroInstance *h)
  1806. {
  1807. return contains(ai->lockedHeroes, h);
  1808. });
  1809. if(hs.empty()) //all heroes are busy. buy new one
  1810. {
  1811. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  1812. return CGoal(RECRUIT_HERO);
  1813. else //find mobile hero with weakest army
  1814. {
  1815. hs = cb->getHeroesInfo();
  1816. erase_if(hs, [](const CGHeroInstance *h)
  1817. {
  1818. return !h->movement; //only hero with movement are of interest for us
  1819. });
  1820. if (hs.empty())
  1821. {
  1822. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  1823. return CGoal(RECRUIT_HERO);
  1824. else
  1825. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  1826. }
  1827. boost::sort(hs, compareHeroStrength);
  1828. }
  1829. }
  1830. const CGHeroInstance *h = hs.front();
  1831. CGoal ret(VISIT_TILE);
  1832. ret.sethero(h);
  1833. return ret.settile(whereToExplore(h));
  1834. }
  1835. I_AM_ELEMENTAR;
  1836. case RECRUIT_HERO:
  1837. {
  1838. const CGTownInstance *t = ai->findTownWithTavern();
  1839. if(!t)
  1840. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::TAVERN);
  1841. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  1842. return CGoal(COLLECT_RES).setresID(Res::GOLD).setvalue(HERO_GOLD_COST);
  1843. I_AM_ELEMENTAR;
  1844. }
  1845. break;
  1846. case VISIT_TILE:
  1847. {
  1848. if(!cb->isVisible(tile))
  1849. return CGoal(EXPLORE);
  1850. if(hero && !ai->isAccessibleForHero(tile, hero))
  1851. hero = NULL;
  1852. if(!hero)
  1853. {
  1854. if(cb->getHeroesInfo().empty())
  1855. return CGoal(RECRUIT_HERO);
  1856. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1857. {
  1858. if(ai->isAccessibleForHero(tile, h))
  1859. {
  1860. hero = h;
  1861. break;
  1862. }
  1863. }
  1864. }
  1865. if(hero)
  1866. {
  1867. if(isSafeToVisit(hero, tile))
  1868. return CGoal(*this).setisElementar(true);
  1869. else
  1870. return CGoal(GATHER_ARMY).sethero(hero);
  1871. }
  1872. else //inaccessible for all heroes
  1873. return CGoal(CLEAR_WAY_TO).settile(tile);
  1874. }
  1875. break;
  1876. case DIG_AT_TILE:
  1877. {
  1878. auto objs = cb->getTile(tile)->visitableObjects;
  1879. if(objs.size() && objs.front()->ID == GameConstants::HEROI_TYPE && objs.front()->tempOwner == ai->playerID) //we have hero at dest
  1880. {
  1881. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(objs.front());
  1882. return CGoal(*this).sethero(h).setisElementar(true);
  1883. }
  1884. return CGoal(VISIT_TILE).settile(tile);
  1885. }
  1886. break;
  1887. case BUILD_STRUCTURE:
  1888. //TODO check res
  1889. //look for town
  1890. //prerequisites?
  1891. I_AM_ELEMENTAR;
  1892. case COLLECT_RES:
  1893. {
  1894. std::vector<const IMarket*> markets;
  1895. std::vector<const CGObjectInstance*> visObjs;
  1896. ai->retreiveVisitableObjs(visObjs, true);
  1897. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  1898. {
  1899. if(const IMarket *m = IMarket::castFrom(obj, false))
  1900. {
  1901. if(obj->ID == GameConstants::TOWNI_TYPE && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  1902. markets.push_back(m);
  1903. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  1904. markets.push_back(m);
  1905. }
  1906. }
  1907. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  1908. {
  1909. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  1910. });
  1911. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  1912. {
  1913. return !(market->o->ID == GameConstants::TOWNI_TYPE && market->o->tempOwner == ai->playerID)
  1914. && !ai->isAccessible(market->o->visitablePos());
  1915. }),markets.end());
  1916. if(!markets.size())
  1917. {
  1918. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1919. {
  1920. if(cb->canBuildStructure(t, EBuilding::MARKETPLACE) == EBuildingState::ALLOWED)
  1921. return CGoal(BUILD_STRUCTURE).settown(t).setbid(EBuilding::MARKETPLACE);
  1922. }
  1923. }
  1924. else
  1925. {
  1926. const IMarket *m = markets.back();
  1927. //attempt trade at back (best prices)
  1928. int howManyCanWeBuy = 0;
  1929. for(int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  1930. {
  1931. if(i == resID) continue;
  1932. int toGive = -1, toReceive = -1;
  1933. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  1934. assert(toGive > 0 && toReceive > 0);
  1935. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  1936. }
  1937. if(howManyCanWeBuy + cb->getResourceAmount(resID) >= value)
  1938. {
  1939. if(cb->getTile(m->o->visitablePos())->visitableObjects.back()->tempOwner != ai->playerID)
  1940. return CGoal(GET_OBJ).setobjid(m->o->id);
  1941. return setobjid(m->o->id).setisElementar(true);
  1942. }
  1943. }
  1944. }
  1945. return CGoal(INVALID);
  1946. case CONQUER:
  1947. {
  1948. //TODO make use from many heroes
  1949. std::vector<const CGHeroInstance *> heroes = cb->getHeroesInfo();
  1950. erase_if(heroes, [](const CGHeroInstance *h)
  1951. {
  1952. return vstd::contains(ai->lockedHeroes, h) || !h->movement;
  1953. });
  1954. boost::sort(heroes, compareHeroStrength);
  1955. if(heroes.empty())
  1956. I_AM_ELEMENTAR;
  1957. const CGHeroInstance *h = heroes.back();
  1958. cb->setSelection(h);
  1959. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  1960. ai->retreiveVisitableObjs(objs);
  1961. erase_if(objs, [&](const CGObjectInstance *obj)
  1962. {
  1963. return (obj->ID != GameConstants::TOWNI_TYPE && obj->ID != GameConstants::HEROI_TYPE) //not town/hero
  1964. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != 0; //not enemy
  1965. });
  1966. if(objs.empty())
  1967. return CGoal(EXPLORE); //we need to find an enemy
  1968. erase_if(objs, [&](const CGObjectInstance *obj)
  1969. {
  1970. return !isSafeToVisit(h, obj->visitablePos());
  1971. });
  1972. if(objs.empty())
  1973. I_AM_ELEMENTAR;
  1974. boost::sort(objs, isCloser);
  1975. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  1976. {
  1977. if(ai->isAccessibleForHero(obj->visitablePos(), h))
  1978. return CGoal(VISIT_TILE).sethero(h).settile(obj->visitablePos());
  1979. }
  1980. return CGoal(EXPLORE); //enemy is inaccessible
  1981. }
  1982. break;
  1983. case BUILD:
  1984. I_AM_ELEMENTAR;
  1985. case INVALID:
  1986. I_AM_ELEMENTAR;
  1987. case GATHER_ARMY:
  1988. {
  1989. const CGHeroInstance *h = hero;
  1990. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  1991. {
  1992. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1993. };
  1994. std::vector<const CGTownInstance *> townsReachable;
  1995. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1996. {
  1997. if(!t->visitingHero && howManyReinforcementsCanGet(h,t))
  1998. {
  1999. if(isReachable(t))
  2000. townsReachable.push_back(t);
  2001. }
  2002. }
  2003. if(townsReachable.size()) //try towns first
  2004. {
  2005. boost::sort(townsReachable, compareReinforcements);
  2006. return CGoal(VISIT_TILE).sethero(hero).settile(townsReachable.back()->visitablePos());
  2007. }
  2008. else
  2009. {
  2010. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  2011. ai->retreiveVisitableObjs(objs);
  2012. erase_if(objs, [&](const CGObjectInstance *obj)
  2013. {
  2014. return (obj->ID != Obj::CREATURE_GENERATOR1); //not town/ dwelling
  2015. });
  2016. if(objs.empty()) //no possible objects, we did eveyrthing already
  2017. return CGoal(EXPLORE).sethero(hero);
  2018. //TODO: check if we can recruit any creatures there, evaluate army
  2019. boost::sort(objs, isCloser);
  2020. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  2021. { //find safe dwelling
  2022. if (isSafeToVisit(hero, obj->visitablePos())) //TODO: make use of multiple heroes
  2023. return CGoal(VISIT_TILE).sethero(hero).settile(obj->visitablePos());
  2024. }
  2025. }
  2026. return CGoal(EXPLORE); //find dwelling
  2027. }
  2028. break;
  2029. default:
  2030. assert(0);
  2031. }
  2032. return CGoal(EXPLORE);
  2033. }
  2034. TSubgoal CGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  2035. {
  2036. if(obj)
  2037. return CGoal(GET_OBJ).setobjid(obj->id);
  2038. else
  2039. return CGoal(EXPLORE);
  2040. }
  2041. TSubgoal CGoal::lookForArtSmart(int aid)
  2042. {
  2043. return CGoal(INVALID);
  2044. }
  2045. bool CGoal::invalid() const
  2046. {
  2047. return goalType == INVALID;
  2048. }
  2049. bool CGoal::isBlockedBorderGate(int3 tileToHit)
  2050. {
  2051. return cb->getTile(tileToHit)->topVisitableID() == Obj::BORDER_GATE
  2052. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  2053. }
  2054. SectorMap::SectorMap()
  2055. {
  2056. // int3 sizes = cb->getMapSize();
  2057. // sector.resize(sizes.x);
  2058. // BOOST_FOREACH(auto &i, sector)
  2059. // i.resize(sizes.y);
  2060. //
  2061. // BOOST_FOREACH(auto &i, sector)
  2062. // BOOST_FOREACH(auto &j, i)
  2063. // j.resize(sizes.z, 0);
  2064. update();
  2065. }
  2066. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  2067. {
  2068. if(t->blocked && !t->visitable)
  2069. {
  2070. sec = NOT_AVAILABLE;
  2071. return true;
  2072. }
  2073. return false;
  2074. }
  2075. bool markIfBlocked(ui8 &sec, crint3 pos)
  2076. {
  2077. return markIfBlocked(sec, pos, cb->getTile(pos));
  2078. }
  2079. void SectorMap::update()
  2080. {
  2081. clear();
  2082. int curSector = 3; //0 is invisible, 1 is not explored
  2083. foreach_tile_pos([&](crint3 pos)
  2084. {
  2085. if(retreiveTile(pos) == NOT_CHECKED)
  2086. {
  2087. if(!markIfBlocked(retreiveTile(pos), pos))
  2088. exploreNewSector(pos, curSector++);
  2089. }
  2090. });
  2091. valid = true;
  2092. }
  2093. void SectorMap::clear()
  2094. {
  2095. sector = cb->getVisibilityMap();
  2096. valid = false;
  2097. }
  2098. bool canBeEmbarkmentPoint(const TerrainTile *t)
  2099. {
  2100. //tile must be free of with unoccupied boat
  2101. return !t->blocked
  2102. || (t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT);
  2103. }
  2104. void SectorMap::exploreNewSector(crint3 pos, int num)
  2105. {
  2106. Sector &s = infoOnSectors[num];
  2107. s.id = num;
  2108. s.water = cb->getTile(pos)->isWater();
  2109. std::queue<int3> toVisit;
  2110. toVisit.push(pos);
  2111. while(toVisit.size())
  2112. {
  2113. int3 curPos = toVisit.front();
  2114. toVisit.pop();
  2115. ui8 &sec = retreiveTile(curPos);
  2116. if(sec == NOT_CHECKED)
  2117. {
  2118. const TerrainTile *t = cb->getTile(curPos);
  2119. if(!markIfBlocked(sec, curPos, t))
  2120. {
  2121. if(t->isWater() == s.water) //sector is only-water or only-land
  2122. {
  2123. sec = num;
  2124. s.tiles.push_back(curPos);
  2125. foreach_neighbour(curPos, [&](crint3 neighPos)
  2126. {
  2127. if(retreiveTile(neighPos) == NOT_CHECKED)
  2128. {
  2129. toVisit.push(neighPos);
  2130. //parent[neighPos] = curPos;
  2131. }
  2132. const TerrainTile *nt = cb->getTile(neighPos, false);
  2133. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  2134. {
  2135. s.embarkmentPoints.push_back(neighPos);
  2136. }
  2137. });
  2138. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  2139. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->pos);
  2140. }
  2141. }
  2142. }
  2143. }
  2144. removeDuplicates(s.embarkmentPoints);
  2145. }
  2146. void SectorMap::write(crstring fname)
  2147. {
  2148. std::ofstream out(fname);
  2149. for(int k = 0; k < cb->getMapSize().z; k++)
  2150. {
  2151. for(int j = 0; j < cb->getMapSize().y; j++)
  2152. {
  2153. for(int i = 0; i < cb->getMapSize().x; i++)
  2154. {
  2155. out << (int)sector[i][j][k] << '\t';
  2156. }
  2157. out << std::endl;
  2158. }
  2159. out << std::endl;
  2160. }
  2161. }
  2162. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  2163. { //TODO: allow polling of remaining creatures in dwelling
  2164. if (dynamic_cast<const CGVisitableOPW *>(obj) || dynamic_cast<const CGDwelling *>(obj)) //ensures future compatibility, unlike IDs
  2165. return true;
  2166. switch (obj->ID)
  2167. {
  2168. case Obj::STABLES: //any other potential visitable objects?
  2169. return true;
  2170. }
  2171. return false;
  2172. }
  2173. int3 SectorMap::firstTileToGet(const CGHeroInstance *h, crint3 dst)
  2174. {
  2175. int sourceSector = retreiveTile(h->visitablePos()),
  2176. destinationSector = retreiveTile(dst);
  2177. if(sourceSector != destinationSector)
  2178. {
  2179. const Sector *src = &infoOnSectors[sourceSector],
  2180. *dst = &infoOnSectors[destinationSector];
  2181. std::map<const Sector*, const Sector*> preds;
  2182. std::queue<const Sector *> sq;
  2183. sq.push(src);
  2184. while(!sq.empty())
  2185. {
  2186. const Sector *s = sq.front();
  2187. sq.pop();
  2188. BOOST_FOREACH(int3 ep, s->embarkmentPoints)
  2189. {
  2190. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  2191. //preds[s].push_back(neigh);
  2192. if(!preds[neigh])
  2193. {
  2194. preds[neigh] = s;
  2195. sq.push(neigh);
  2196. }
  2197. }
  2198. //TODO consider other types of connections between sectors?
  2199. }
  2200. if(!preds[dst])
  2201. {
  2202. write("test.txt");
  2203. throw cannotFulfillGoalException(str(format("Cannot found connection between sectors %d and %d") % src->id % dst->id));
  2204. }
  2205. std::vector<const Sector*> toTraverse;
  2206. toTraverse.push_back(dst);
  2207. while(toTraverse.back() != src)
  2208. {
  2209. toTraverse.push_back(preds[toTraverse.back()]);
  2210. }
  2211. if(preds[dst])
  2212. {
  2213. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  2214. if(!src->water && sectorToReach->water) //embark
  2215. {
  2216. //embark on ship -> look for an EP with a boat
  2217. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  2218. {
  2219. const TerrainTile *t = cb->getTile(pos);
  2220. return t && t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT
  2221. && retreiveTile(pos) == sectorToReach->id;
  2222. });
  2223. if(firstEP != src->embarkmentPoints.end())
  2224. {
  2225. return *firstEP;
  2226. }
  2227. else
  2228. {
  2229. //we need to find a shipyard with an access to the desired sector's EP
  2230. //TODO what about Summon Boat spell?
  2231. std::vector<const IShipyard *> shipyards;
  2232. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2233. {
  2234. if(t->hasBuilt(EBuilding::SHIPYARD))
  2235. shipyards.push_back(t);
  2236. }
  2237. std::vector<const CGObjectInstance*> visObjs;
  2238. ai->retreiveVisitableObjs(visObjs, true);
  2239. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  2240. {
  2241. if(obj->ID != GameConstants::TOWNI_TYPE) //towns were handled in the previous loop
  2242. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  2243. shipyards.push_back(shipyard);
  2244. }
  2245. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  2246. {
  2247. return shipyard->state() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  2248. }),shipyards.end());
  2249. if(!shipyards.size())
  2250. {
  2251. //TODO consider possibility of building shipyard in a town
  2252. throw cannotFulfillGoalException("There is no known shipyard!");
  2253. }
  2254. //we have only shipyards that possibly can build ships onto the appropriate EP
  2255. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  2256. {
  2257. return s->o->tempOwner == ai->playerID;
  2258. });
  2259. if(ownedGoodShipyard != shipyards.end())
  2260. {
  2261. const IShipyard *s = *ownedGoodShipyard;
  2262. TResources shipCost;
  2263. s->getBoatCost(shipCost);
  2264. if(cb->getResourceAmount().canAfford(shipCost))
  2265. {
  2266. int3 ret = s->bestLocation();
  2267. cb->buildBoat(s);
  2268. return ret;
  2269. }
  2270. else
  2271. {
  2272. //TODO gather res
  2273. throw cannotFulfillGoalException("Not enough resources to build a boat");
  2274. }
  2275. }
  2276. else
  2277. {
  2278. //TODO pick best shipyard to take over
  2279. return shipyards.front()->o->pos;
  2280. }
  2281. }
  2282. }
  2283. else if(src->water && !sectorToReach->water)
  2284. {
  2285. //TODO
  2286. //disembark
  2287. }
  2288. else
  2289. {
  2290. //TODO
  2291. //transition between two land/water sectors. Monolith? Whirlpool? ...
  2292. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  2293. }
  2294. }
  2295. else
  2296. {
  2297. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  2298. }
  2299. }
  2300. else
  2301. {
  2302. makeParentBFS(h->visitablePos());
  2303. int3 curtile = dst;
  2304. while(curtile != h->visitablePos())
  2305. {
  2306. if(cb->getPathInfo(curtile)->reachable())
  2307. {
  2308. return curtile;
  2309. }
  2310. else
  2311. {
  2312. auto i = parent.find(curtile);
  2313. if(i != parent.end())
  2314. {
  2315. assert(curtile != i->second);
  2316. curtile = i->second;
  2317. }
  2318. else
  2319. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  2320. }
  2321. }
  2322. }
  2323. throw cannotFulfillGoalException("Impossible happened.");
  2324. }
  2325. void SectorMap::makeParentBFS(crint3 source)
  2326. {
  2327. parent.clear();
  2328. int mySector = retreiveTile(source);
  2329. std::queue<int3> toVisit;
  2330. toVisit.push(source);
  2331. while(toVisit.size())
  2332. {
  2333. int3 curPos = toVisit.front();
  2334. toVisit.pop();
  2335. ui8 &sec = retreiveTile(curPos);
  2336. assert(sec == mySector); //consider only tiles from the same sector
  2337. //const TerrainTile *t = cb->getTile(curPos);
  2338. foreach_neighbour(curPos, [&](crint3 neighPos)
  2339. {
  2340. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  2341. {
  2342. toVisit.push(neighPos);
  2343. parent[neighPos] = curPos;
  2344. }
  2345. });
  2346. }
  2347. }
  2348. unsigned char & SectorMap::retreiveTile(crint3 pos)
  2349. {
  2350. return retreiveTileN(sector, pos);
  2351. }