VCAI.cpp 76 KB

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