VCAI.cpp 112 KB

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