VCAI.cpp 96 KB

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