VCAI.cpp 85 KB

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