VCAI.cpp 102 KB

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