VCAI.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292
  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::showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 askID, const int soundID, bool selection, bool cancel)
  710. {
  711. NET_EVENT_HANDLER;
  712. LOG_ENTRY;
  713. int sel = 0;
  714. status.addQuery();
  715. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  716. sel = components.size();
  717. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  718. sel = 1;
  719. requestActionASAP([=]()
  720. {
  721. cb->selectionMade(sel, askID);
  722. });
  723. }
  724. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, boost::function<void()> &onEnd)
  725. {
  726. NET_EVENT_HANDLER;
  727. LOG_ENTRY;
  728. status.addQuery();
  729. //you can't request action from action-response thread
  730. requestActionASAP([=]()
  731. {
  732. pickBestCreatures (down, up);
  733. onEnd();
  734. });
  735. }
  736. void VCAI::serialize(COSer<CSaveFile> &h, const int version)
  737. {
  738. NET_EVENT_HANDLER;
  739. LOG_ENTRY;
  740. }
  741. void VCAI::serialize(CISer<CLoadFile> &h, const int version)
  742. {
  743. NET_EVENT_HANDLER;
  744. LOG_ENTRY;
  745. }
  746. void makePossibleUpgrades(const CArmedInstance *obj)
  747. {
  748. if(!obj)
  749. return;
  750. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  751. {
  752. if(const CStackInstance *s = obj->getStackPtr(i))
  753. {
  754. UpgradeInfo ui;
  755. cb->getUpgradeInfo(obj, i, ui);
  756. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  757. {
  758. cb->upgradeCreature(obj, i, ui.newID[0]);
  759. }
  760. }
  761. }
  762. }
  763. void VCAI::makeTurn()
  764. {
  765. MAKING_TURN;
  766. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  767. setThreadName("VCAI::makeTurn");
  768. BNLOG("Player %d starting turn", playerID);
  769. INDENT;
  770. switch(cb->getDate(1))
  771. {
  772. case 1:
  773. {
  774. townVisitsThisWeek.clear();
  775. std::vector<const CGObjectInstance *> objs;
  776. retreiveVisitableObjs(objs, true);
  777. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  778. {
  779. if (isWeeklyRevisitable(obj))
  780. {
  781. if (!vstd::contains(visitableObjs, obj))
  782. visitableObjs.push_back(obj);
  783. auto o = std::find (alreadyVisited.begin(), alreadyVisited.end(), obj);
  784. if (o != alreadyVisited.end())
  785. alreadyVisited.erase(o);
  786. }
  787. }
  788. }
  789. break;
  790. case 7: //reconsider strategy
  791. {
  792. if(auto h = primaryHero()) //check if our primary hero can handle danger
  793. {
  794. ui64 totalDanger = 0;
  795. int dangerousObjects = 0;
  796. std::vector<const CGObjectInstance *> objs;
  797. retreiveVisitableObjs(objs, false);
  798. BOOST_FOREACH (auto obj, objs)
  799. {
  800. if (evaluateDanger(obj)) //potentilaly dnagerous
  801. {
  802. totalDanger += evaluateDanger(obj->visitablePos(), *h);
  803. ++dangerousObjects;
  804. }
  805. }
  806. if (dangerousObjects && totalDanger / dangerousObjects > h->getHeroStrength())
  807. {
  808. setGoal (h, CGoal(GATHER_ARMY).sethero(h));
  809. }
  810. }
  811. }
  812. break;
  813. }
  814. if(cb->getSelectedHero())
  815. cb->recalculatePaths();
  816. makeTurnInternal();
  817. vstd::clear_pointer(makingTurn);
  818. return;
  819. }
  820. void VCAI::makeTurnInternal()
  821. {
  822. saving = 0;
  823. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  824. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  825. moveCreaturesToHero(t);
  826. try
  827. {
  828. //Pick objects reserved in previous turn - we expect only nerby objects there
  829. BOOST_FOREACH (auto hero, reservedHeroesMap)
  830. {
  831. cb->setSelection(hero.first.get());
  832. boost::sort (hero.second, isCloser);
  833. BOOST_FOREACH (auto obj, hero.second)
  834. {
  835. striveToGoal (CGoal(VISIT_TILE).sethero(hero.first).settile(obj->visitablePos()));
  836. }
  837. }
  838. //now try to win
  839. striveToGoal(CGoal(WIN));
  840. //finally, continue our abstract long-term goals
  841. //heroes tend to die in the process and loose their goals, unsafe to iterate it
  842. std::vector<std::pair<HeroPtr, CGoal> > safeCopy;
  843. boost::copy(lockedHeroes, std::back_inserter(safeCopy));
  844. typedef decltype(*safeCopy.begin()) TItrType;
  845. auto lockedHeroesSorter = [](TItrType h1, TItrType h2) -> bool
  846. {
  847. return compareMovement (h1.first, h2.first);
  848. };
  849. boost::sort(safeCopy, lockedHeroesSorter);
  850. while (safeCopy.size()) //continue our goals
  851. {
  852. auto it = safeCopy.begin();
  853. if (it->first && it->first->tempOwner == playerID && vstd::contains(lockedHeroes, it->first)) //make sure hero still has his goal
  854. {
  855. cb->setSelection(*it->first);
  856. striveToGoal (it->second);
  857. }
  858. safeCopy.erase(it);
  859. }
  860. striveToGoal(CGoal(BUILD)); //TODO: smarter building management
  861. }
  862. catch(boost::thread_interrupted &e)
  863. {
  864. tlog0 << "Making turn thread has been interrupted. We'll end without calling endTurn.\n";
  865. return;
  866. }
  867. catch(std::exception &e)
  868. {
  869. tlog0 << "Making turn thread has caught an exception: " << e.what() << "\n";
  870. }
  871. endTurn();
  872. }
  873. bool VCAI::goVisitObj(const CGObjectInstance * obj, HeroPtr h)
  874. {
  875. int3 dst = obj->visitablePos();
  876. BNLOG("%s will try to visit %s at (%s)", h->name % obj->hoverName % strFromInt3(dst));
  877. return moveHeroToTile(dst, h);
  878. }
  879. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  880. {
  881. switch (obj->ID)
  882. {
  883. case Obj::CREATURE_GENERATOR1:
  884. recruitCreatures (dynamic_cast<const CGDwelling *>(obj));
  885. break;
  886. case GameConstants::TOWNI_TYPE:
  887. moveCreaturesToHero (dynamic_cast<const CGTownInstance *>(obj));
  888. break;
  889. break;
  890. }
  891. }
  892. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  893. {
  894. if(t->visitingHero && t->armedGarrison())
  895. {
  896. pickBestCreatures (t->visitingHero, t);
  897. }
  898. }
  899. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  900. {
  901. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  902. const CArmedInstance *armies[] = {army, source};
  903. //we calculate total strength for each creature type available in armies
  904. std::map<const CCreature*, int> creToPower;
  905. BOOST_FOREACH(auto armyPtr, armies)
  906. BOOST_FOREACH(auto &i, armyPtr->Slots())
  907. creToPower[i.second->type] += i.second->getPower();
  908. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  909. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  910. 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
  911. {
  912. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  913. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  914. {
  915. return lhs.second < rhs.second;
  916. });
  917. bestArmy.push_back(creIt->first);
  918. creToPower.erase(creIt);
  919. if(creToPower.empty())
  920. break;
  921. }
  922. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  923. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  924. BOOST_FOREACH(auto armyPtr, armies)
  925. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  926. if(armyPtr->getCreature(j) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  927. cb->mergeOrSwapStacks(armyPtr, army, j, i);
  928. //TODO - having now strongest possible army, we may want to think about arranging stacks
  929. }
  930. void VCAI::recruitCreatures(const CGDwelling * d)
  931. {
  932. for(int i = 0; i < d->creatures.size(); i++)
  933. {
  934. if(!d->creatures[i].second.size())
  935. continue;
  936. int count = d->creatures[i].first;
  937. int creID = d->creatures[i].second.back();
  938. // const CCreature *c = VLC->creh->creatures[creID];
  939. // if(containsSavedRes(c->cost))
  940. // continue;
  941. TResources myRes = cb->getResourceAmount();
  942. myRes[Res::GOLD] -= GOLD_RESERVE;
  943. amin(count, myRes / VLC->creh->creatures[creID]->cost);
  944. if(count > 0)
  945. cb->recruitCreatures(d, creID, count, i);
  946. }
  947. }
  948. bool VCAI::tryBuildStructure(const CGTownInstance * t, int building, unsigned int maxDays)
  949. {
  950. if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  951. return true;
  952. std::set<int> toBuild = cb->getBuildingRequiments(t, building);
  953. toBuild.insert(building);
  954. if (maxDays && toBuild.size() > maxDays)
  955. return false;
  956. TResources currentRes = cb->getResourceAmount();
  957. TResources income = estimateIncome();
  958. //TODO: calculate if we have enough resources to build it in maxDays
  959. BOOST_FOREACH(int buildID, toBuild)
  960. {
  961. const CBuilding *b = VLC->buildh->buildings[t->subID][buildID];
  962. int canBuild = cb->canBuildStructure(t, buildID);
  963. if(canBuild == EBuildingState::ALLOWED)
  964. {
  965. if(!containsSavedRes(b->resources))
  966. {
  967. BNLOG("Player %d will build %s in town of %s at %s", playerID % b->Name() % t->name % t->pos);
  968. cb->buildBuilding(t, buildID);
  969. return true;
  970. }
  971. continue;
  972. }
  973. else if(canBuild == EBuildingState::NO_RESOURCES)
  974. {
  975. TResources cost = VLC->buildh->buildings[t->subID][buildID]->resources;
  976. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  977. {
  978. int diff = currentRes[i] - cost[i] + income[i];
  979. if(diff < 0)
  980. saving[i] = 1;
  981. }
  982. continue;
  983. }
  984. }
  985. return false;
  986. }
  987. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays)
  988. {
  989. BOOST_FOREACH(int building, buildList)
  990. {
  991. if(t->hasBuilt(building))
  992. continue;
  993. if (tryBuildStructure(t, building, maxDays))
  994. return true;
  995. }
  996. return false; //Can't build anything
  997. }
  998. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays)
  999. {
  1000. BOOST_FOREACH(int building, buildList)
  1001. {
  1002. if(t->hasBuilt(building))
  1003. continue;
  1004. return tryBuildStructure(t, building, maxDays);
  1005. }
  1006. return false;//Nothing to build
  1007. }
  1008. void VCAI::buildStructure(const CGTownInstance * t)
  1009. {
  1010. using namespace EBuilding;
  1011. //TODO make *real* town development system
  1012. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  1013. //TODO: build resource silo, defences when needed
  1014. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  1015. //Set of buildings for different goals. Does not include any prerequisites.
  1016. const int essential[] = {TAVERN, TOWN_HALL};
  1017. const int goldSource[] = {TOWN_HALL, CITY_HALL, CAPITOL};
  1018. const int unitsSource[] = { 30, 31, 32, 33, 34, 35, 36};
  1019. const int unitsUpgrade[] = { 37, 38, 39, 40, 41, 42, 43};
  1020. const int unitGrowth[] = { FORT, CITADEL, CASTLE, HORDE_1, HORDE_1_UPGR, HORDE_2, HORDE_2_UPGR};
  1021. const int spells[] = {MAGES_GUILD_1, MAGES_GUILD_2, MAGES_GUILD_3, MAGES_GUILD_4, MAGES_GUILD_5};
  1022. const int extra[] = {RESOURCE_SILO, SPECIAL_1, SPECIAL_2, SPECIAL_3, SPECIAL_4, SHIPYARD}; // all remaining buildings
  1023. TResources currentRes = cb->getResourceAmount();
  1024. TResources income = estimateIncome();
  1025. if (tryBuildAnyStructure(t, std::vector<int>(essential, essential + ARRAY_COUNT(essential))))
  1026. return;
  1027. //we're running out of gold - try to build something gold-producing. Multiplier can be tweaked
  1028. if (currentRes[Res::GOLD] < income[Res::GOLD] * 4)
  1029. if (tryBuildNextStructure(t, std::vector<int>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1030. return;
  1031. if (cb->getDate(1) > 6)// last 2 days of week - try to focus on growth
  1032. {
  1033. if (tryBuildNextStructure(t, std::vector<int>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  1034. return;
  1035. }
  1036. // first in-game week or second half of any week: try build dwellings
  1037. if (cb->getDate(0) < 7 || cb->getDate(1) > 3)
  1038. if (tryBuildAnyStructure(t, std::vector<int>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(1)))
  1039. return;
  1040. //try to upgrade dwelling
  1041. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  1042. {
  1043. if (t->hasBuilt(unitsSource[i]))
  1044. {
  1045. if (tryBuildStructure(t, unitsUpgrade[i]))
  1046. return;
  1047. }
  1048. }
  1049. //remaining tasks
  1050. if (tryBuildNextStructure(t, std::vector<int>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1051. return;
  1052. if (tryBuildNextStructure(t, std::vector<int>(spells, spells + ARRAY_COUNT(spells))))
  1053. return;
  1054. if (tryBuildAnyStructure(t, std::vector<int>(extra, extra + ARRAY_COUNT(extra))))
  1055. return;
  1056. }
  1057. bool isSafeToVisit(HeroPtr h, crint3 tile)
  1058. {
  1059. const ui64 heroStrength = h->getTotalStrength(),
  1060. dangerStrength = evaluateDanger(tile, *h);
  1061. if(dangerStrength)
  1062. {
  1063. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  1064. {
  1065. BNLOG("It's, safe for %s to visit tile %s", h->name % tile);
  1066. return true;
  1067. }
  1068. else
  1069. return false;
  1070. }
  1071. return true; //there's no danger
  1072. }
  1073. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(HeroPtr h)
  1074. {
  1075. validateVisitableObjs();
  1076. std::vector<const CGObjectInstance *> possibleDestinations;
  1077. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1078. {
  1079. if(cb->getPathInfo(obj->visitablePos())->reachable() && !obj->wasVisited(playerID) &&
  1080. (obj->tempOwner != playerID || isWeeklyRevisitable(obj))) //flag or get weekly resources / creatures
  1081. possibleDestinations.push_back(obj);
  1082. }
  1083. boost::sort(possibleDestinations, isCloser);
  1084. possibleDestinations.erase(boost::remove_if(possibleDestinations, [&](const CGObjectInstance *obj) -> bool
  1085. {
  1086. const int3 pos = obj->visitablePos();
  1087. if(vstd::contains(alreadyVisited, obj))
  1088. return true;
  1089. if(!isSafeToVisit(h, pos))
  1090. return true;
  1091. if (!shouldVisit(h, obj))
  1092. return true;
  1093. if (vstd::contains(reservedObjs, obj)) //does checking for our own reserved objects make sense? here?
  1094. return true;
  1095. const CGObjectInstance *topObj = cb->getVisitableObjs(pos).back(); //it may be hero visiting this obj
  1096. //we don't try visiting object on which allied or owned hero stands
  1097. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1098. if(topObj->ID == GameConstants::HEROI_TYPE && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != 0)
  1099. return true;
  1100. return false;
  1101. }),possibleDestinations.end());
  1102. return possibleDestinations;
  1103. }
  1104. void VCAI::wander(HeroPtr h)
  1105. {
  1106. while(1)
  1107. {
  1108. std::vector <ObjectIdRef> dests;
  1109. range::copy(reservedHeroesMap[h], std::back_inserter(dests));
  1110. if (!dests.size())
  1111. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  1112. if(!dests.size())
  1113. {
  1114. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  1115. {
  1116. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1117. };
  1118. std::vector<const CGTownInstance *> townsReachable;
  1119. std::vector<const CGTownInstance *> townsNotReachable;
  1120. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1121. {
  1122. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  1123. {
  1124. if(isReachable(t))
  1125. townsReachable.push_back(t);
  1126. else
  1127. townsNotReachable.push_back(t);
  1128. }
  1129. }
  1130. if(townsReachable.size())
  1131. {
  1132. boost::sort(townsReachable, compareReinforcements);
  1133. dests.emplace_back(townsReachable.back());
  1134. }
  1135. else if(townsNotReachable.size())
  1136. {
  1137. boost::sort(townsNotReachable, compareReinforcements);
  1138. //TODO pick the truly best
  1139. const CGTownInstance *t = townsNotReachable.back();
  1140. BNLOG("%s can't reach any town, we'll try to make our way to %s at %s", h->name % t->name % t->visitablePos());
  1141. int3 pos1 = h->pos;
  1142. striveToGoal(CGoal(CLEAR_WAY_TO).settile(t->visitablePos()).sethero(h));
  1143. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  1144. {
  1145. if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size())
  1146. recruitHero(t);
  1147. }
  1148. break;
  1149. }
  1150. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  1151. {
  1152. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1153. erase_if(towns, [](const CGTownInstance *t) -> bool
  1154. {
  1155. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1156. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1157. return true;
  1158. return false;
  1159. });
  1160. boost::sort(towns, compareArmyStrength);
  1161. if(towns.size())
  1162. recruitHero(towns.back());
  1163. break;
  1164. }
  1165. else
  1166. {
  1167. PNLOG("Nowhere more to go...\n");
  1168. break;
  1169. }
  1170. }
  1171. const ObjectIdRef&dest = dests.front();
  1172. if(!goVisitObj(dest, h))
  1173. {
  1174. if(!dest)
  1175. {
  1176. BNLOG("Visit attempt made the object (id=%d) gone...", dest.id);
  1177. }
  1178. else
  1179. {
  1180. BNLOG("Hero %s apparently used all MPs (%d left)\n", h->name % h->movement);
  1181. reserveObject(h, dest); //reserve that object - we predict it will be reached soon
  1182. //removed - do not forget abstract goal so easily
  1183. //setGoal(h, CGoal(VISIT_TILE).sethero(h).settile(dest->visitablePos()));
  1184. }
  1185. break;
  1186. }
  1187. if(h->visitedTown)
  1188. {
  1189. townVisitsThisWeek[h].push_back(h->visitedTown);
  1190. buildArmyIn(h->visitedTown);
  1191. break;
  1192. }
  1193. }
  1194. }
  1195. void VCAI::setGoal(HeroPtr h, const CGoal goal)
  1196. { //TODO: check for presence?
  1197. if (goal.goalType == EGoals::INVALID)
  1198. remove_if_present(lockedHeroes, h);
  1199. else
  1200. lockedHeroes[h] = CGoal(goal).setisElementar(false); //always evaluate goals before realizing
  1201. }
  1202. void VCAI::setGoal(HeroPtr h, EGoals goalType)
  1203. {
  1204. if (goalType == EGoals::INVALID)
  1205. remove_if_present(lockedHeroes, h);
  1206. else
  1207. lockedHeroes[h] = CGoal(goalType).setisElementar(false); //always evaluate goals before realizing;
  1208. }
  1209. void VCAI::completeGoal (const CGoal goal)
  1210. {
  1211. if (const CGHeroInstance * h = goal.hero.get(true))
  1212. {
  1213. auto it = lockedHeroes.find(h);
  1214. if (it != lockedHeroes.end())
  1215. if (it->second.goalType == goal.goalType)
  1216. lockedHeroes.erase(it); //goal fulfilled, free hero
  1217. }
  1218. }
  1219. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1220. {
  1221. NET_EVENT_HANDLER;
  1222. assert(playerID > GameConstants::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1223. status.setBattle(ONGOING_BATTLE);
  1224. 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
  1225. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->hoverName : "unknown enemy") % tile);
  1226. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1227. }
  1228. void VCAI::battleEnd(const BattleResult *br)
  1229. {
  1230. NET_EVENT_HANDLER;
  1231. assert(status.getBattle() == ONGOING_BATTLE);
  1232. status.setBattle(ENDING_BATTLE);
  1233. bool won = br->winner == myCb->battleGetMySide();
  1234. BNLOG("Player %d: I %s the %s!", playerID % (won ? "won" : "lost") % battlename);
  1235. battlename.clear();
  1236. CAdventureAI::battleEnd(br);
  1237. }
  1238. void VCAI::waitTillFree()
  1239. {
  1240. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1241. status.waitTillFree();
  1242. }
  1243. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1244. {
  1245. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1246. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1247. (obj->ID == Obj::MONSTER))
  1248. return;
  1249. alreadyVisited.push_back(obj);
  1250. }
  1251. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj)
  1252. {
  1253. reservedObjs.push_back(obj);
  1254. reservedHeroesMap[h].push_back(obj);
  1255. }
  1256. void VCAI::validateVisitableObjs()
  1257. {
  1258. std::vector<const CGObjectInstance *> hlp;
  1259. retreiveVisitableObjs(hlp, true);
  1260. start:
  1261. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1262. if(!vstd::contains(hlp, obj))
  1263. {
  1264. tlog1 << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << " shouldn't be on list!\n";
  1265. remove_if_present(visitableObjs, obj);
  1266. goto start;
  1267. }
  1268. }
  1269. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1270. {
  1271. foreach_tile_pos([&](const int3 &pos)
  1272. {
  1273. BOOST_FOREACH(const CGObjectInstance *obj, cb->getVisitableObjs(pos, false))
  1274. {
  1275. if(includeOwned || obj->tempOwner != playerID)
  1276. out.push_back(obj);
  1277. }
  1278. });
  1279. }
  1280. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1281. {
  1282. std::vector<const CGObjectInstance *> ret;
  1283. retreiveVisitableObjs(ret, true);
  1284. erase_if(ret, [](const CGObjectInstance *obj)
  1285. {
  1286. return obj->tempOwner != ai->playerID;
  1287. });
  1288. return ret;
  1289. }
  1290. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1291. {
  1292. visitableObjs.push_back(obj);
  1293. helperObjInfo[obj] = ObjInfo(obj);
  1294. }
  1295. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1296. {
  1297. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  1298. {
  1299. if(obj->ID == 5 && obj->subID == aid)
  1300. return obj;
  1301. }
  1302. return NULL;
  1303. //TODO what if more than one artifact is available? return them all or some slection criteria
  1304. }
  1305. bool VCAI::isAccessible(const int3 &pos)
  1306. {
  1307. //TODO precalculate for speed
  1308. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1309. {
  1310. if(isAccessibleForHero(pos, h))
  1311. return true;
  1312. }
  1313. return false;
  1314. }
  1315. HeroPtr VCAI::getHeroWithGrail() const
  1316. {
  1317. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1318. if(h->hasArt(2)) //grail
  1319. return h;
  1320. return NULL;
  1321. }
  1322. const CGObjectInstance * VCAI::getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate)
  1323. {
  1324. //TODO smarter definition of unvisited
  1325. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1326. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1327. return obj;
  1328. return NULL;
  1329. }
  1330. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies /*= false*/) const
  1331. {
  1332. cb->setSelection(*h);
  1333. if (!includeAllies)
  1334. { //don't visit tile occupied by allied hero
  1335. BOOST_FOREACH (auto obj, cb->getVisitableObjs(pos))
  1336. {
  1337. if (obj->ID == GameConstants::HEROI_TYPE && obj->tempOwner == h->tempOwner && obj != h)
  1338. return false;
  1339. }
  1340. }
  1341. return cb->getPathInfo(pos)->reachable();
  1342. }
  1343. class cannotFulfillGoalException : public std::exception
  1344. {
  1345. std::string msg;
  1346. public:
  1347. explicit cannotFulfillGoalException(crstring _Message) : msg(_Message)
  1348. {
  1349. }
  1350. virtual ~cannotFulfillGoalException() throw ()
  1351. {
  1352. };
  1353. const char *what() const throw () OVERRIDE
  1354. {
  1355. return msg.c_str();
  1356. }
  1357. };
  1358. class goalFulfilledException : public std::exception
  1359. {
  1360. std::string msg;
  1361. public:
  1362. explicit goalFulfilledException(crstring _Message) : msg(_Message)
  1363. {
  1364. }
  1365. virtual ~goalFulfilledException() throw ()
  1366. {
  1367. };
  1368. const char *what() const throw () OVERRIDE
  1369. {
  1370. return msg.c_str();
  1371. }
  1372. };
  1373. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1374. {
  1375. visitedObject = NULL;
  1376. int3 startHpos = h->visitablePos();
  1377. bool ret = false;
  1378. if(startHpos == dst)
  1379. {
  1380. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1381. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1382. waitTillFree(); //movement may cause battle or blocking dialog
  1383. ret = true;
  1384. }
  1385. else
  1386. {
  1387. CGPath path;
  1388. cb->getPath2(dst, path);
  1389. if(path.nodes.empty())
  1390. {
  1391. tlog1 << "Hero " << h->name << " cannot reach " << dst << std::endl;
  1392. //setGoal(h, INVALID);
  1393. completeGoal (CGoal(VISIT_TILE).sethero(h));
  1394. cb->recalculatePaths();
  1395. throw std::runtime_error("Wrong move order!");
  1396. }
  1397. int i=path.nodes.size()-1;
  1398. for(; i>0; i--)
  1399. {
  1400. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1401. if(path.nodes[i-1].turns)
  1402. {
  1403. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1404. break;
  1405. }
  1406. int3 endpos = path.nodes[i-1].coord;
  1407. if(endpos == h->visitablePos())
  1408. //if (endpos == h->pos)
  1409. continue;
  1410. // if(i > 1)
  1411. // {
  1412. // int3 afterEndPos = path.nodes[i-2].coord;
  1413. // if(afterEndPos.z != endpos.z)
  1414. //
  1415. // }
  1416. //tlog0 << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos << std::endl;
  1417. cb->moveHero(*h, CGHeroInstance::convertPosition(endpos, true));
  1418. waitTillFree(); //movement may cause battle or blocking dialog
  1419. boost::this_thread::interruption_point();
  1420. if(h->tempOwner != playerID) //we lost hero - remove all tasks assigned to him/her
  1421. {
  1422. lostHero(h);
  1423. //we need to throw, otherwise hero will be assigned to sth again
  1424. throw std::runtime_error("Hero was lost!");
  1425. break;
  1426. }
  1427. }
  1428. ret = !i;
  1429. }
  1430. if (visitedObject) //we step into something interesting
  1431. {
  1432. performObjectInteraction (visitedObject, h);
  1433. }
  1434. if(h->tempOwner == playerID) //we could have lost hero after last move
  1435. {
  1436. cb->recalculatePaths();
  1437. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1438. {
  1439. throw cannotFulfillGoalException("Invalid path found!");
  1440. }
  1441. }
  1442. BNLOG("Hero %s moved from %s to %s", h->name % startHpos % h->visitablePos());
  1443. return ret;
  1444. }
  1445. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  1446. {
  1447. int ret = 0;
  1448. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  1449. {
  1450. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  1451. {
  1452. int3 npos = int3(x,y,pos.z);
  1453. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  1454. {
  1455. ret++;
  1456. }
  1457. }
  1458. }
  1459. return ret;
  1460. }
  1461. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  1462. {
  1463. return howManyTilesWillBeDiscovered(pos + dir, radious);
  1464. }
  1465. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  1466. {
  1467. BOOST_FOREACH(const int3 &tile, tiles)
  1468. {
  1469. foreach_neighbour(tile, [&](int3 neighbour)
  1470. {
  1471. if(cb->isVisible(neighbour))
  1472. out.push_back(neighbour);
  1473. });
  1474. }
  1475. }
  1476. void VCAI::tryRealize(CGoal g)
  1477. {
  1478. BNLOG("Attempting realizing goal with code %s", goalName(g.goalType));
  1479. switch(g.goalType)
  1480. {
  1481. case EXPLORE:
  1482. {
  1483. throw cannotFulfillGoalException("EXPLORE is not a elementar goal!");
  1484. }
  1485. break;
  1486. case RECRUIT_HERO:
  1487. {
  1488. if(const CGTownInstance *t = findTownWithTavern())
  1489. {
  1490. //TODO co jesli nie ma dostepnego bohatera?
  1491. //TODO jezeli miasto jest zablokowane, sprobowac oczyscic wejscie
  1492. cb->recruitHero(t, cb->getAvailableHeroes(t)[0]);
  1493. }
  1494. //TODO karkolomna alternatywa - tawerna na mapie przygod lub wiezienie (nie wiem, czy warto?)
  1495. }
  1496. break;
  1497. case VISIT_TILE:
  1498. {
  1499. //cb->recalculatePaths();
  1500. if(!g.hero->movement)
  1501. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1502. if(!g.isBlockedBorderGate(g.tile))
  1503. {
  1504. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1505. {
  1506. throw goalFulfilledException("");
  1507. }
  1508. }
  1509. else
  1510. throw cannotFulfillGoalException("There's a blocked gate!");
  1511. }
  1512. break;
  1513. case BUILD_STRUCTURE:
  1514. {
  1515. const CGTownInstance *t = g.town;
  1516. if(!t && g.hero)
  1517. t = g.hero->visitedTown;
  1518. if(!t)
  1519. {
  1520. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1521. {
  1522. switch(cb->canBuildStructure(t, g.bid))
  1523. {
  1524. case EBuildingState::ALLOWED:
  1525. cb->buildBuilding(t, g.bid);
  1526. return;
  1527. default:
  1528. break;
  1529. }
  1530. }
  1531. }
  1532. else if(cb->canBuildStructure(t, g.bid) == EBuildingState::ALLOWED)
  1533. {
  1534. cb->buildBuilding(t, g.bid);
  1535. return;
  1536. }
  1537. throw cannotFulfillGoalException("Cannot build a given structure!");
  1538. }
  1539. break;
  1540. case DIG_AT_TILE:
  1541. {
  1542. assert(g.hero->visitablePos() == g.tile);
  1543. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1544. {
  1545. cb->dig(g.hero.get());
  1546. setGoal(g.hero, INVALID); // finished digging
  1547. }
  1548. else
  1549. {
  1550. ai->lockedHeroes[g.hero] = g; //hero who tries to dig shouldn't do anything else
  1551. throw cannotFulfillGoalException("A hero can't dig!\n");
  1552. }
  1553. }
  1554. break;
  1555. case COLLECT_RES:
  1556. if(const CGObjectInstance *obj = cb->getObj(g.objid, false))
  1557. {
  1558. if(const IMarket *m = IMarket::castFrom(obj, false))
  1559. {
  1560. for (int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  1561. {
  1562. if(i == g.resID) continue;
  1563. int toGive, toGet;
  1564. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1565. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1566. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1567. if(cb->getResourceAmount(g.resID) >= g.value)
  1568. return;
  1569. }
  1570. }
  1571. else
  1572. {
  1573. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1574. }
  1575. }
  1576. else
  1577. {
  1578. saving[g.resID] = 1;
  1579. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1580. }
  1581. case CONQUER:
  1582. case GATHER_ARMY:
  1583. case BOOST_HERO:
  1584. // TODO: conquer??
  1585. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1586. case BUILD:
  1587. performTypicalActions();
  1588. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1589. case INVALID:
  1590. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1591. default:
  1592. throw cannotFulfillGoalException("Unknown type of goal !");
  1593. }
  1594. }
  1595. const CGTownInstance * VCAI::findTownWithTavern() const
  1596. {
  1597. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1598. if(vstd::contains(t->builtBuildings, EBuilding::TAVERN) && !t->visitingHero)
  1599. return t;
  1600. return NULL;
  1601. }
  1602. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1603. {
  1604. std::vector<HeroPtr> ret;
  1605. boost::copy(cb->getHeroesInfo(), std::back_inserter(ret));
  1606. BOOST_FOREACH(auto h, lockedHeroes)
  1607. {
  1608. if (!h.second.invalid()) //we can use heroes without valid goal
  1609. remove_if_present(ret, h.first);
  1610. }
  1611. return ret;
  1612. }
  1613. HeroPtr VCAI::primaryHero() const
  1614. {
  1615. auto hs = cb->getHeroesInfo();
  1616. boost::sort(hs, compareHeroStrength);
  1617. if(hs.empty())
  1618. return NULL;
  1619. return hs.back();
  1620. }
  1621. void VCAI::endTurn()
  1622. {
  1623. tlog4 << "Player " << playerID << " ends turn\n";
  1624. if(!status.haveTurn())
  1625. {
  1626. tlog1 << "Not having turn at the end of turn???\n";
  1627. }
  1628. do
  1629. {
  1630. cb->endTurn();
  1631. } 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
  1632. tlog4 << "Player " << playerID << " ended turn\n";
  1633. }
  1634. void VCAI::striveToGoal(const CGoal &ultimateGoal)
  1635. {
  1636. if (ultimateGoal.invalid())
  1637. return;
  1638. CGoal abstractGoal;
  1639. while(1)
  1640. {
  1641. CGoal goal = ultimateGoal;
  1642. BNLOG("Striving to goal of type %s", goalName(ultimateGoal.goalType));
  1643. int maxGoals = 100; //preventing deadlock for mutually dependent goals
  1644. while(!goal.isElementar && !goal.isAbstract && maxGoals)
  1645. {
  1646. INDENT;
  1647. BNLOG("Considering goal %s", goalName(goal.goalType));
  1648. try
  1649. {
  1650. boost::this_thread::interruption_point();
  1651. goal = goal.whatToDoToAchieve();
  1652. --maxGoals;
  1653. }
  1654. catch(std::exception &e)
  1655. {
  1656. BNLOG("Goal %s decomposition failed: %s", goalName(goal.goalType) % e.what());
  1657. return;
  1658. }
  1659. }
  1660. try
  1661. {
  1662. boost::this_thread::interruption_point();
  1663. if (goal.hero) //lock this hero to fulfill ultimate goal
  1664. {
  1665. if (maxGoals)
  1666. {
  1667. setGoal(goal.hero, goal);
  1668. }
  1669. else
  1670. {
  1671. setGoal(goal.hero, INVALID); // we seemingly don't know what to do with hero
  1672. }
  1673. }
  1674. if (goal.isAbstract)
  1675. {
  1676. abstractGoal = goal; //allow only one abstract goal per call
  1677. BNLOG("Choosing abstract goal %s", goalName(goal.goalType));
  1678. break;
  1679. }
  1680. else
  1681. tryRealize(goal);
  1682. boost::this_thread::interruption_point();
  1683. }
  1684. catch(boost::thread_interrupted &e)
  1685. {
  1686. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1687. throw; //rethrow, we want to truly end this thread
  1688. }
  1689. catch(goalFulfilledException &e)
  1690. {
  1691. completeGoal (goal);
  1692. if (maxGoals > 98) //completed goal was main goal
  1693. //TODO: find better condition
  1694. return;
  1695. }
  1696. catch(std::exception &e)
  1697. {
  1698. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goalName(goal.goalType) % goalName(ultimateGoal.goalType));
  1699. BNLOG("The error message was: %s", e.what());
  1700. break;
  1701. }
  1702. }
  1703. //TODO: save abstract goals not related to hero
  1704. if (!abstractGoal.invalid()) //try to realize our one goal
  1705. {
  1706. while (1)
  1707. {
  1708. CGoal goal = CGoal(abstractGoal).setisAbstract(false);
  1709. int maxGoals = 50;
  1710. while (!goal.isElementar && maxGoals) //find elementar goal and fulfill it
  1711. {
  1712. try
  1713. {
  1714. boost::this_thread::interruption_point();
  1715. goal = goal.whatToDoToAchieve();
  1716. --maxGoals;
  1717. }
  1718. catch(std::exception &e)
  1719. {
  1720. BNLOG("Goal %s decomposition failed: %s", goalName(goal.goalType) % e.what());
  1721. return;
  1722. }
  1723. }
  1724. try
  1725. {
  1726. boost::this_thread::interruption_point();
  1727. tryRealize(goal);
  1728. boost::this_thread::interruption_point();
  1729. }
  1730. catch(boost::thread_interrupted &e)
  1731. {
  1732. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1733. throw; //rethrow, we want to truly end this thread
  1734. }
  1735. catch(goalFulfilledException &e)
  1736. {
  1737. completeGoal (goal);
  1738. if (maxGoals > 98) //completed goal was main goal
  1739. //TODO: find better condition
  1740. return;
  1741. }
  1742. catch(std::exception &e)
  1743. {
  1744. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goalName(goal.goalType) % goalName(ultimateGoal.goalType));
  1745. BNLOG("The error message was: %s", e.what());
  1746. break;
  1747. }
  1748. }
  1749. }
  1750. }
  1751. void VCAI::performTypicalActions()
  1752. {
  1753. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1754. {
  1755. BNLOG("Looking into %s", t->name);
  1756. buildStructure(t);
  1757. buildArmyIn(t);
  1758. if(!ai->primaryHero() ||
  1759. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  1760. {
  1761. recruitHero(t);
  1762. buildArmyIn(t);
  1763. }
  1764. }
  1765. BOOST_FOREACH(auto h, getUnblockedHeroes())
  1766. {
  1767. BNLOG("Looking into %s, MP=%d", h->name.c_str() % h->movement);
  1768. INDENT;
  1769. makePossibleUpgrades(*h);
  1770. cb->setSelection(*h);
  1771. try
  1772. {
  1773. wander(h);
  1774. }
  1775. catch(std::exception &e)
  1776. {
  1777. BNLOG("Cannot use this hero anymore, received exception: %s", e.what());
  1778. continue;
  1779. }
  1780. }
  1781. }
  1782. void VCAI::buildArmyIn(const CGTownInstance * t)
  1783. {
  1784. makePossibleUpgrades(t->visitingHero);
  1785. makePossibleUpgrades(t);
  1786. recruitCreatures(t);
  1787. moveCreaturesToHero(t);
  1788. }
  1789. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  1790. {
  1791. TimeCheck tc("looking for best exploration neighbour");
  1792. std::map<int3, int> dstToRevealedTiles;
  1793. BOOST_FOREACH(crint3 dir, dirs)
  1794. if(cb->isInTheMap(hpos+dir))
  1795. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  1796. auto best = dstToRevealedTiles.begin();
  1797. best->second *= cb->getPathInfo(best->first)->reachable();
  1798. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  1799. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  1800. {
  1801. const CGPathNode *pn = cb->getPathInfo(i->first);
  1802. //const TerrainTile *t = cb->getTile(i->first);
  1803. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  1804. best = i;
  1805. }
  1806. if(best->second)
  1807. return best->first;
  1808. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  1809. }
  1810. int3 VCAI::explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles)
  1811. {
  1812. TimeCheck tc("looking for new exploration point");
  1813. PNLOG("Looking for an another place for exploration...");
  1814. tiles.resize(radius);
  1815. foreach_tile_pos([&](const int3 &pos)
  1816. {
  1817. if(!cb->isVisible(pos))
  1818. tiles[0].push_back(pos);
  1819. });
  1820. for (int i = 1; i < radius; i++)
  1821. {
  1822. getVisibleNeighbours(tiles[i-1], tiles[i]);
  1823. removeDuplicates(tiles[i]);
  1824. BOOST_FOREACH(const int3 &tile, tiles[i])
  1825. {
  1826. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius))
  1827. {
  1828. return tile;
  1829. }
  1830. }
  1831. }
  1832. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  1833. }
  1834. TResources VCAI::estimateIncome() const
  1835. {
  1836. TResources ret;
  1837. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1838. {
  1839. ret[Res::GOLD] += t->dailyIncome();
  1840. //TODO duplikuje newturn
  1841. if(t->hasBuilt(EBuilding::RESOURCE_SILO)) //there is resource silo
  1842. {
  1843. if(t->town->primaryRes == 127) //we'll give wood and ore
  1844. {
  1845. ret[Res::WOOD] ++;
  1846. ret[Res::ORE] ++;
  1847. }
  1848. else
  1849. {
  1850. ret[t->town->primaryRes] ++;
  1851. }
  1852. }
  1853. }
  1854. BOOST_FOREACH(const CGObjectInstance *obj, getFlaggedObjects())
  1855. {
  1856. if(obj->ID == Obj::MINE)
  1857. {
  1858. switch(obj->subID)
  1859. {
  1860. case Res::WOOD:
  1861. case Res::ORE:
  1862. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  1863. break;
  1864. case Res::GOLD:
  1865. case 7: //abandoned mine -> also gold
  1866. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  1867. break;
  1868. default:
  1869. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  1870. break;
  1871. }
  1872. }
  1873. }
  1874. return ret;
  1875. }
  1876. bool VCAI::containsSavedRes(const TResources &cost) const
  1877. {
  1878. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1879. {
  1880. if(saving[i] && cost[i])
  1881. return true;
  1882. }
  1883. return false;
  1884. }
  1885. void VCAI::recruitHero(const CGTownInstance * t)
  1886. {
  1887. BNLOG("Trying to recruit a hero in %s at %s", t->name % t->visitablePos())
  1888. cb->recruitHero(t, cb->getAvailableHeroes(t).front());
  1889. }
  1890. void VCAI::finish()
  1891. {
  1892. if(makingTurn)
  1893. makingTurn->interrupt();
  1894. }
  1895. void VCAI::requestActionASAP(boost::function<void()> whatToDo)
  1896. {
  1897. boost::barrier b(2);
  1898. boost::thread newThread([&b,this,whatToDo]()
  1899. {
  1900. setThreadName("VCAI::requestActionASAP::helper");
  1901. SET_GLOBAL_STATE(this);
  1902. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  1903. b.wait();
  1904. whatToDo();
  1905. });
  1906. b.wait();
  1907. }
  1908. void VCAI::lostHero(HeroPtr h)
  1909. {
  1910. BNLOG("I lost my hero %s. It's best to forget and move on.\n", h.name);
  1911. remove_if_present(lockedHeroes, h);
  1912. BOOST_FOREACH(auto obj, reservedHeroesMap[h])
  1913. {
  1914. remove_if_present(reservedObjs, obj); //unreserve all objects for that hero
  1915. }
  1916. remove_if_present(reservedHeroesMap, h);
  1917. }
  1918. AIStatus::AIStatus()
  1919. {
  1920. battle = NO_BATTLE;
  1921. remainingQueries = 0;
  1922. havingTurn = false;
  1923. }
  1924. AIStatus::~AIStatus()
  1925. {
  1926. }
  1927. void AIStatus::setBattle(BattleState BS)
  1928. {
  1929. boost::unique_lock<boost::mutex> lock(mx);
  1930. battle = BS;
  1931. cv.notify_all();
  1932. }
  1933. BattleState AIStatus::getBattle()
  1934. {
  1935. boost::unique_lock<boost::mutex> lock(mx);
  1936. return battle;
  1937. }
  1938. void AIStatus::addQueries(int val)
  1939. {
  1940. boost::unique_lock<boost::mutex> lock(mx);
  1941. remainingQueries += val;
  1942. BNLOG("Changing count of queries by %d, to a total of %d", val % remainingQueries);
  1943. assert(remainingQueries >= 0);
  1944. cv.notify_all();
  1945. }
  1946. void AIStatus::addQuery()
  1947. {
  1948. addQueries(1);
  1949. }
  1950. void AIStatus::removeQuery()
  1951. {
  1952. addQueries(-1);
  1953. }
  1954. int AIStatus::getQueriesCount()
  1955. {
  1956. boost::unique_lock<boost::mutex> lock(mx);
  1957. return remainingQueries;
  1958. }
  1959. void AIStatus::startedTurn()
  1960. {
  1961. boost::unique_lock<boost::mutex> lock(mx);
  1962. havingTurn = true;
  1963. cv.notify_all();
  1964. }
  1965. void AIStatus::madeTurn()
  1966. {
  1967. boost::unique_lock<boost::mutex> lock(mx);
  1968. havingTurn = false;
  1969. cv.notify_all();
  1970. }
  1971. void AIStatus::waitTillFree()
  1972. {
  1973. boost::unique_lock<boost::mutex> lock(mx);
  1974. while(battle != NO_BATTLE || remainingQueries)
  1975. cv.wait(lock);
  1976. }
  1977. bool AIStatus::haveTurn()
  1978. {
  1979. boost::unique_lock<boost::mutex> lock(mx);
  1980. return havingTurn;
  1981. }
  1982. int3 whereToExplore(HeroPtr h)
  1983. {
  1984. //TODO it's stupid and ineffective, write sth better
  1985. cb->setSelection(*h);
  1986. int radius = h->getSightRadious();
  1987. int3 hpos = h->visitablePos();
  1988. //look for nearby objs -> visit them if they're close enouh
  1989. const int DIST_LIMIT = 3;
  1990. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  1991. BOOST_FOREACH(const CGObjectInstance *obj, ai->getPossibleDestinations(h))
  1992. {
  1993. int3 op = obj->visitablePos();
  1994. CGPath p;
  1995. cb->getPath2(op, p);
  1996. if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  1997. nearbyVisitableObjs.push_back(obj);
  1998. }
  1999. boost::sort(nearbyVisitableObjs, isCloser);
  2000. if(nearbyVisitableObjs.size())
  2001. return nearbyVisitableObjs.back()->visitablePos();
  2002. try
  2003. {
  2004. return ai->explorationBestNeighbour(hpos, radius, h);
  2005. }
  2006. catch(cannotFulfillGoalException &e)
  2007. {
  2008. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow], metryka taksówkowa
  2009. try
  2010. {
  2011. return ai->explorationNewPoint(radius, h, tiles);
  2012. }
  2013. catch(cannotFulfillGoalException &e)
  2014. {
  2015. std::map<int, std::vector<int3> > profits;
  2016. {
  2017. TimeCheck tc("Evaluating exploration possibilities");
  2018. tiles[0].clear(); //we can't reach FoW anyway
  2019. BOOST_FOREACH(auto &vt, tiles)
  2020. BOOST_FOREACH(auto &tile, vt)
  2021. profits[howManyTilesWillBeDiscovered(tile, radius)].push_back(tile);
  2022. }
  2023. if(profits.empty())
  2024. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  2025. auto bestDest = profits.end();
  2026. bestDest--;
  2027. return bestDest->second.front(); //TODO which is the real best tile?
  2028. }
  2029. }
  2030. }
  2031. TSubgoal CGoal::whatToDoToAchieve()
  2032. {
  2033. BNLOG("Decomposing goal of type %s", goalName(goalType));
  2034. INDENT;
  2035. switch(goalType)
  2036. {
  2037. case WIN:
  2038. {
  2039. const CVictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  2040. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  2041. if(!vc.appliesToAI)
  2042. {
  2043. //TODO deduce victory from human loss condition
  2044. cond = EVictoryConditionType::WINSTANDARD;
  2045. }
  2046. switch(cond)
  2047. {
  2048. case EVictoryConditionType::ARTIFACT:
  2049. return CGoal(GET_ART_TYPE).setaid(vc.ID);
  2050. case EVictoryConditionType::BEATHERO:
  2051. return CGoal(GET_OBJ).setobjid(vc.ID);
  2052. case EVictoryConditionType::BEATMONSTER:
  2053. return CGoal(GET_OBJ).setobjid(vc.ID);
  2054. case EVictoryConditionType::BUILDCITY:
  2055. //TODO build castle/capitol
  2056. break;
  2057. case EVictoryConditionType::BUILDGRAIL:
  2058. {
  2059. if(auto h = ai->getHeroWithGrail())
  2060. {
  2061. //hero is in a town that can host Grail
  2062. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, EBuilding::GRAIL))
  2063. {
  2064. const CGTownInstance *t = h->visitedTown;
  2065. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::GRAIL).settown(t);
  2066. }
  2067. else
  2068. {
  2069. auto towns = cb->getTownsInfo();
  2070. towns.erase(boost::remove_if(towns,
  2071. [](const CGTownInstance *t) -> bool
  2072. {
  2073. return vstd::contains(t->forbiddenBuildings, EBuilding::GRAIL);
  2074. }),
  2075. towns.end());
  2076. boost::sort(towns, isCloser);
  2077. if(towns.size())
  2078. {
  2079. return CGoal(VISIT_TILE).sethero(h).settile(towns.front()->visitablePos());
  2080. }
  2081. }
  2082. }
  2083. double ratio = 0;
  2084. int3 grailPos = cb->getGrailPos(ratio);
  2085. if(ratio > 0.99)
  2086. {
  2087. return CGoal(DIG_AT_TILE).settile(grailPos);
  2088. }
  2089. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  2090. {
  2091. return CGoal(GET_OBJ).setobjid(obj->id);
  2092. }
  2093. else
  2094. return CGoal(EXPLORE);
  2095. }
  2096. break;
  2097. case EVictoryConditionType::CAPTURECITY:
  2098. return CGoal(GET_OBJ).setobjid(vc.ID);
  2099. case EVictoryConditionType::GATHERRESOURCE:
  2100. return CGoal(COLLECT_RES).setresID(vc.ID).setvalue(vc.count);
  2101. //TODO mines? piles? marketplace?
  2102. //save?
  2103. break;
  2104. case EVictoryConditionType::GATHERTROOP:
  2105. break;
  2106. case EVictoryConditionType::TAKEDWELLINGS:
  2107. break;
  2108. case EVictoryConditionType::TAKEMINES:
  2109. break;
  2110. case EVictoryConditionType::TRANSPORTITEM:
  2111. break;
  2112. case EVictoryConditionType::WINSTANDARD:
  2113. return CGoal(CONQUER);
  2114. default:
  2115. assert(0);
  2116. }
  2117. }
  2118. break;
  2119. case GET_OBJ:
  2120. {
  2121. const CGObjectInstance * obj = cb->getObj(objid);
  2122. if(!obj)
  2123. return CGoal(EXPLORE);
  2124. int3 pos = cb->getObj(objid)->visitablePos();
  2125. return CGoal(VISIT_TILE).settile(pos);
  2126. }
  2127. break;
  2128. case GET_ART_TYPE:
  2129. {
  2130. const CGObjectInstance *artInst = ai->lookForArt(aid);
  2131. if(!artInst)
  2132. {
  2133. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid);
  2134. if(alternativeWay.invalid())
  2135. return CGoal(EXPLORE);
  2136. else
  2137. return alternativeWay;
  2138. }
  2139. else
  2140. return CGoal(GET_OBJ).setobjid(artInst->id);
  2141. }
  2142. break;
  2143. case CLEAR_WAY_TO:
  2144. {
  2145. assert(tile.x >= 0); //set tile
  2146. if(!cb->isVisible(tile))
  2147. {
  2148. tlog1 << "Clear way should be used with visible tiles!\n";
  2149. return CGoal(EXPLORE);
  2150. }
  2151. HeroPtr h = hero ? hero : ai->primaryHero();
  2152. if(!h)
  2153. return CGoal(RECRUIT_HERO);
  2154. cb->setSelection(*h);
  2155. SectorMap sm;
  2156. bool dropToFile = false;
  2157. if(dropToFile) //for debug purposes
  2158. sm.write("test.txt");
  2159. int3 tileToHit = sm.firstTileToGet(h, tile);
  2160. //if(isSafeToVisit(h, tileToHit))
  2161. if(isBlockedBorderGate(tileToHit))
  2162. throw cannotFulfillGoalException("There's blocked border gate!");
  2163. if(tileToHit == tile)
  2164. {
  2165. tlog1 << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  2166. % tileToHit % tile % h->name % h->visitablePos();
  2167. throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  2168. }
  2169. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  2170. if(topObj && topObj->ID == GameConstants::HEROI_TYPE && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != 0)
  2171. {
  2172. std::string problem = boost::str(boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText());
  2173. throw cannotFulfillGoalException(problem);
  2174. }
  2175. return CGoal(VISIT_TILE).settile(tileToHit).sethero(h);
  2176. //TODO czy istnieje lepsza droga?
  2177. }
  2178. throw cannotFulfillGoalException("Cannot reach given tile!");
  2179. //return CGoal(EXPLORE); // TODO improve
  2180. case EXPLORE:
  2181. {
  2182. if (hero)
  2183. {
  2184. return CGoal(VISIT_TILE).settile(whereToExplore(hero)).sethero(hero);
  2185. }
  2186. auto hs = cb->getHeroesInfo();
  2187. int howManyHeroes = hs.size();
  2188. erase(hs, [](const CGHeroInstance *h)
  2189. {
  2190. return contains(ai->lockedHeroes, h);
  2191. });
  2192. if(hs.empty()) //all heroes are busy. buy new one
  2193. {
  2194. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2195. return CGoal(RECRUIT_HERO);
  2196. else //find mobile hero with weakest army
  2197. {
  2198. hs = cb->getHeroesInfo();
  2199. erase_if(hs, [](const CGHeroInstance *h)
  2200. {
  2201. return !h->movement; //only hero with movement are of interest for us
  2202. });
  2203. if (hs.empty())
  2204. {
  2205. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2206. return CGoal(RECRUIT_HERO);
  2207. else
  2208. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2209. }
  2210. boost::sort(hs, compareMovement); //closer to what?
  2211. }
  2212. }
  2213. const CGHeroInstance *h = hs.front();
  2214. return (*this).sethero(h).setisAbstract(true);
  2215. }
  2216. I_AM_ELEMENTAR;
  2217. case RECRUIT_HERO:
  2218. {
  2219. const CGTownInstance *t = ai->findTownWithTavern();
  2220. if(!t)
  2221. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::TAVERN);
  2222. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  2223. return CGoal(COLLECT_RES).setresID(Res::GOLD).setvalue(HERO_GOLD_COST);
  2224. I_AM_ELEMENTAR;
  2225. }
  2226. break;
  2227. case VISIT_TILE:
  2228. {
  2229. if(!cb->isVisible(tile))
  2230. return CGoal(EXPLORE);
  2231. if(hero && !ai->isAccessibleForHero(tile, hero))
  2232. hero = NULL;
  2233. if(!hero)
  2234. {
  2235. if(cb->getHeroesInfo().empty())
  2236. {
  2237. return CGoal(RECRUIT_HERO);
  2238. }
  2239. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  2240. {
  2241. if(ai->isAccessibleForHero(tile, h))
  2242. {
  2243. hero = h;
  2244. break;
  2245. }
  2246. }
  2247. }
  2248. if(hero)
  2249. {
  2250. if(isSafeToVisit(hero, tile))
  2251. return CGoal(*this).setisElementar(true);
  2252. else
  2253. {
  2254. return CGoal(GATHER_ARMY).sethero(hero);
  2255. }
  2256. }
  2257. else //inaccessible for all heroes
  2258. {
  2259. return CGoal(CLEAR_WAY_TO).settile(tile);
  2260. }
  2261. }
  2262. break;
  2263. case DIG_AT_TILE:
  2264. {
  2265. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  2266. if(firstObj && firstObj->ID == GameConstants::HEROI_TYPE && firstObj->tempOwner == ai->playerID) //we have hero at dest
  2267. {
  2268. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  2269. return CGoal(*this).sethero(h).setisElementar(true);
  2270. }
  2271. return CGoal(VISIT_TILE).settile(tile);
  2272. }
  2273. break;
  2274. case BUILD_STRUCTURE:
  2275. //TODO check res
  2276. //look for town
  2277. //prerequisites?
  2278. I_AM_ELEMENTAR;
  2279. case COLLECT_RES:
  2280. {
  2281. std::vector<const IMarket*> markets;
  2282. std::vector<const CGObjectInstance*> visObjs;
  2283. ai->retreiveVisitableObjs(visObjs, true);
  2284. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  2285. {
  2286. if(const IMarket *m = IMarket::castFrom(obj, false))
  2287. {
  2288. if(obj->ID == GameConstants::TOWNI_TYPE && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  2289. markets.push_back(m);
  2290. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  2291. markets.push_back(m);
  2292. }
  2293. }
  2294. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  2295. {
  2296. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  2297. });
  2298. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  2299. {
  2300. return !(market->o->ID == GameConstants::TOWNI_TYPE && market->o->tempOwner == ai->playerID)
  2301. && !ai->isAccessible(market->o->visitablePos());
  2302. }),markets.end());
  2303. if(!markets.size())
  2304. {
  2305. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2306. {
  2307. if(cb->canBuildStructure(t, EBuilding::MARKETPLACE) == EBuildingState::ALLOWED)
  2308. return CGoal(BUILD_STRUCTURE).settown(t).setbid(EBuilding::MARKETPLACE);
  2309. }
  2310. }
  2311. else
  2312. {
  2313. const IMarket *m = markets.back();
  2314. //attempt trade at back (best prices)
  2315. int howManyCanWeBuy = 0;
  2316. for(int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  2317. {
  2318. if(i == resID) continue;
  2319. int toGive = -1, toReceive = -1;
  2320. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  2321. assert(toGive > 0 && toReceive > 0);
  2322. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  2323. }
  2324. if(howManyCanWeBuy + cb->getResourceAmount(resID) >= value)
  2325. {
  2326. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  2327. assert(backObj);
  2328. if(backObj->tempOwner != ai->playerID)
  2329. return CGoal(GET_OBJ).setobjid(m->o->id);
  2330. return setobjid(m->o->id).setisElementar(true);
  2331. }
  2332. }
  2333. }
  2334. return CGoal(INVALID);
  2335. case CONQUER: //TODO: put it into a function?
  2336. {
  2337. auto hs = cb->getHeroesInfo();
  2338. int howManyHeroes = hs.size();
  2339. erase(hs, [](const CGHeroInstance *h)
  2340. {
  2341. return contains(ai->lockedHeroes, h);
  2342. });
  2343. if(hs.empty()) //all heroes are busy. buy new one
  2344. {
  2345. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2346. return CGoal(RECRUIT_HERO);
  2347. else //find mobile hero with weakest army
  2348. {
  2349. hs = cb->getHeroesInfo();
  2350. erase_if(hs, [](const CGHeroInstance *h)
  2351. {
  2352. return !h->movement; //only hero with movement are of interest for us
  2353. });
  2354. if (hs.empty())
  2355. {
  2356. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2357. return CGoal(RECRUIT_HERO);
  2358. else
  2359. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2360. }
  2361. boost::sort(hs, compareHeroStrength);
  2362. }
  2363. }
  2364. const CGHeroInstance *h = hs.back();
  2365. cb->setSelection(h);
  2366. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  2367. ai->retreiveVisitableObjs(objs);
  2368. erase_if(objs, [&](const CGObjectInstance *obj)
  2369. {
  2370. return (obj->ID != GameConstants::TOWNI_TYPE && obj->ID != GameConstants::HEROI_TYPE) //not town/hero
  2371. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != 0; //not enemy
  2372. });
  2373. if(objs.empty())
  2374. return CGoal(EXPLORE); //we need to find an enemy
  2375. erase_if(objs, [&](const CGObjectInstance *obj)
  2376. {
  2377. return !isSafeToVisit(h, obj->visitablePos());
  2378. });
  2379. if(objs.empty())
  2380. I_AM_ELEMENTAR;
  2381. boost::sort(objs, isCloser);
  2382. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  2383. {
  2384. if(ai->isAccessibleForHero(obj->visitablePos(), h))
  2385. return CGoal(VISIT_TILE).sethero(h).settile(obj->visitablePos());
  2386. }
  2387. return CGoal(EXPLORE); //enemy is inaccessible
  2388. }
  2389. break;
  2390. case BUILD:
  2391. I_AM_ELEMENTAR;
  2392. case INVALID:
  2393. I_AM_ELEMENTAR;
  2394. case GATHER_ARMY:
  2395. {
  2396. //TODO: find hero if none set
  2397. assert(hero);
  2398. cb->setSelection(*hero);
  2399. auto compareReinforcements = [this](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  2400. {
  2401. return howManyReinforcementsCanGet(hero, lhs) < howManyReinforcementsCanGet(hero, rhs);
  2402. };
  2403. std::vector<const CGTownInstance *> townsReachable;
  2404. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2405. {
  2406. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  2407. {
  2408. if(isReachable(t))
  2409. townsReachable.push_back(t);
  2410. }
  2411. }
  2412. if(townsReachable.size()) //try towns first
  2413. {
  2414. boost::sort(townsReachable, compareReinforcements);
  2415. return CGoal(VISIT_TILE).sethero(hero).settile(townsReachable.back()->visitablePos());
  2416. }
  2417. else
  2418. {
  2419. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  2420. ai->retreiveVisitableObjs(objs);
  2421. erase_if(objs, [&](const CGObjectInstance *obj)
  2422. {
  2423. return (obj->ID != Obj::CREATURE_GENERATOR1); //not town/ dwelling
  2424. });
  2425. if(objs.empty()) //no possible objects, we did eveyrthing already
  2426. return CGoal(EXPLORE).sethero(hero);
  2427. //TODO: check if we can recruit any creatures there, evaluate army
  2428. boost::sort(objs, isCloser);
  2429. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  2430. { //find safe dwelling
  2431. if (isSafeToVisit(hero, obj->visitablePos())) //TODO: make use of multiple heroes
  2432. return CGoal(VISIT_TILE).sethero(hero).settile(obj->visitablePos());
  2433. }
  2434. }
  2435. return CGoal(EXPLORE); //find dwelling
  2436. }
  2437. break;
  2438. default:
  2439. assert(0);
  2440. }
  2441. return CGoal(EXPLORE);
  2442. }
  2443. TSubgoal CGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  2444. {
  2445. if(obj)
  2446. return CGoal(GET_OBJ).setobjid(obj->id);
  2447. else
  2448. return CGoal(EXPLORE);
  2449. }
  2450. TSubgoal CGoal::lookForArtSmart(int aid)
  2451. {
  2452. return CGoal(INVALID);
  2453. }
  2454. bool CGoal::invalid() const
  2455. {
  2456. return goalType == INVALID;
  2457. }
  2458. bool CGoal::isBlockedBorderGate(int3 tileToHit)
  2459. {
  2460. return cb->getTile(tileToHit)->topVisitableID() == Obj::BORDER_GATE
  2461. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  2462. }
  2463. SectorMap::SectorMap()
  2464. {
  2465. // int3 sizes = cb->getMapSize();
  2466. // sector.resize(sizes.x);
  2467. // BOOST_FOREACH(auto &i, sector)
  2468. // i.resize(sizes.y);
  2469. //
  2470. // BOOST_FOREACH(auto &i, sector)
  2471. // BOOST_FOREACH(auto &j, i)
  2472. // j.resize(sizes.z, 0);
  2473. update();
  2474. }
  2475. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  2476. {
  2477. if(t->blocked && !t->visitable)
  2478. {
  2479. sec = NOT_AVAILABLE;
  2480. return true;
  2481. }
  2482. return false;
  2483. }
  2484. bool markIfBlocked(ui8 &sec, crint3 pos)
  2485. {
  2486. return markIfBlocked(sec, pos, cb->getTile(pos));
  2487. }
  2488. void SectorMap::update()
  2489. {
  2490. clear();
  2491. int curSector = 3; //0 is invisible, 1 is not explored
  2492. foreach_tile_pos([&](crint3 pos)
  2493. {
  2494. if(retreiveTile(pos) == NOT_CHECKED)
  2495. {
  2496. if(!markIfBlocked(retreiveTile(pos), pos))
  2497. exploreNewSector(pos, curSector++);
  2498. }
  2499. });
  2500. valid = true;
  2501. }
  2502. void SectorMap::clear()
  2503. {
  2504. sector = cb->getVisibilityMap();
  2505. valid = false;
  2506. }
  2507. bool canBeEmbarkmentPoint(const TerrainTile *t)
  2508. {
  2509. //tile must be free of with unoccupied boat
  2510. return !t->blocked
  2511. || (t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT);
  2512. }
  2513. void SectorMap::exploreNewSector(crint3 pos, int num)
  2514. {
  2515. Sector &s = infoOnSectors[num];
  2516. s.id = num;
  2517. s.water = cb->getTile(pos)->isWater();
  2518. std::queue<int3> toVisit;
  2519. toVisit.push(pos);
  2520. while(toVisit.size())
  2521. {
  2522. int3 curPos = toVisit.front();
  2523. toVisit.pop();
  2524. ui8 &sec = retreiveTile(curPos);
  2525. if(sec == NOT_CHECKED)
  2526. {
  2527. const TerrainTile *t = cb->getTile(curPos);
  2528. if(!markIfBlocked(sec, curPos, t))
  2529. {
  2530. if(t->isWater() == s.water) //sector is only-water or only-land
  2531. {
  2532. sec = num;
  2533. s.tiles.push_back(curPos);
  2534. foreach_neighbour(curPos, [&](crint3 neighPos)
  2535. {
  2536. if(retreiveTile(neighPos) == NOT_CHECKED)
  2537. {
  2538. toVisit.push(neighPos);
  2539. //parent[neighPos] = curPos;
  2540. }
  2541. const TerrainTile *nt = cb->getTile(neighPos, false);
  2542. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  2543. {
  2544. s.embarkmentPoints.push_back(neighPos);
  2545. }
  2546. });
  2547. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  2548. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->pos);
  2549. }
  2550. }
  2551. }
  2552. }
  2553. removeDuplicates(s.embarkmentPoints);
  2554. }
  2555. void SectorMap::write(crstring fname)
  2556. {
  2557. std::ofstream out(fname);
  2558. for(int k = 0; k < cb->getMapSize().z; k++)
  2559. {
  2560. for(int j = 0; j < cb->getMapSize().y; j++)
  2561. {
  2562. for(int i = 0; i < cb->getMapSize().x; i++)
  2563. {
  2564. out << (int)sector[i][j][k] << '\t';
  2565. }
  2566. out << std::endl;
  2567. }
  2568. out << std::endl;
  2569. }
  2570. }
  2571. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  2572. { //TODO: allow polling of remaining creatures in dwelling
  2573. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  2574. dynamic_cast<const CGDwelling *>(obj) ||
  2575. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2576. return true;
  2577. switch (obj->ID)
  2578. {
  2579. case Obj::STABLES: //any other potential visitable objects?
  2580. return true;
  2581. }
  2582. return false;
  2583. }
  2584. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2585. {
  2586. switch (obj->ID)
  2587. {
  2588. case Obj::CREATURE_GENERATOR1:
  2589. {
  2590. if (obj->tempOwner != h->tempOwner)
  2591. return true; //flag just in case
  2592. bool canRecruitCreatures = false;
  2593. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2594. BOOST_FOREACH(auto level, d->creatures)
  2595. {
  2596. BOOST_FOREACH(auto c, level.second)
  2597. {
  2598. if (h->getSlotFor(c) != -1)
  2599. canRecruitCreatures = true;
  2600. }
  2601. }
  2602. return canRecruitCreatures;
  2603. }
  2604. case Obj::MONOLITH1:
  2605. case Obj::MONOLITH2:
  2606. case Obj::MONOLITH3:
  2607. case Obj::WHIRLPOOL:
  2608. //TODO: mehcanism for handling monoliths
  2609. return false;
  2610. case Obj::SCHOOL_OF_MAGIC:
  2611. case Obj::SCHOOL_OF_WAR:
  2612. {
  2613. TResources myRes = ai->myCb->getResourceAmount();
  2614. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  2615. return false;
  2616. }
  2617. break;
  2618. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2619. if (h->level < 12)
  2620. return false;
  2621. case Obj::TREE_OF_KNOWLEDGE:
  2622. {
  2623. TResources myRes = ai->myCb->getResourceAmount();
  2624. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  2625. return false;
  2626. }
  2627. break;
  2628. }
  2629. if (obj->wasVisited(h))
  2630. return false;
  2631. return true;
  2632. }
  2633. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  2634. {
  2635. int sourceSector = retreiveTile(h->visitablePos()),
  2636. destinationSector = retreiveTile(dst);
  2637. if(sourceSector != destinationSector)
  2638. {
  2639. const Sector *src = &infoOnSectors[sourceSector],
  2640. *dst = &infoOnSectors[destinationSector];
  2641. std::map<const Sector*, const Sector*> preds;
  2642. std::queue<const Sector *> sq;
  2643. sq.push(src);
  2644. while(!sq.empty())
  2645. {
  2646. const Sector *s = sq.front();
  2647. sq.pop();
  2648. BOOST_FOREACH(int3 ep, s->embarkmentPoints)
  2649. {
  2650. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  2651. //preds[s].push_back(neigh);
  2652. if(!preds[neigh])
  2653. {
  2654. preds[neigh] = s;
  2655. sq.push(neigh);
  2656. }
  2657. }
  2658. //TODO consider other types of connections between sectors?
  2659. }
  2660. if(!preds[dst])
  2661. {
  2662. write("test.txt");
  2663. ai->completeGoal (CGoal(EXPLORE).sethero(h)); //if we can't find the way, seemingly all tiles were explored
  2664. //TODO: more organized way?
  2665. throw cannotFulfillGoalException(str(format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  2666. }
  2667. std::vector<const Sector*> toTraverse;
  2668. toTraverse.push_back(dst);
  2669. while(toTraverse.back() != src)
  2670. {
  2671. toTraverse.push_back(preds[toTraverse.back()]);
  2672. }
  2673. if(preds[dst])
  2674. {
  2675. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  2676. if(!src->water && sectorToReach->water) //embark
  2677. {
  2678. //embark on ship -> look for an EP with a boat
  2679. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  2680. {
  2681. const TerrainTile *t = cb->getTile(pos);
  2682. return t && t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT
  2683. && retreiveTile(pos) == sectorToReach->id;
  2684. });
  2685. if(firstEP != src->embarkmentPoints.end())
  2686. {
  2687. return *firstEP;
  2688. }
  2689. else
  2690. {
  2691. //we need to find a shipyard with an access to the desired sector's EP
  2692. //TODO what about Summon Boat spell?
  2693. std::vector<const IShipyard *> shipyards;
  2694. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2695. {
  2696. if(t->hasBuilt(EBuilding::SHIPYARD))
  2697. shipyards.push_back(t);
  2698. }
  2699. std::vector<const CGObjectInstance*> visObjs;
  2700. ai->retreiveVisitableObjs(visObjs, true);
  2701. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  2702. {
  2703. if(obj->ID != GameConstants::TOWNI_TYPE) //towns were handled in the previous loop
  2704. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  2705. shipyards.push_back(shipyard);
  2706. }
  2707. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  2708. {
  2709. return shipyard->state() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  2710. }),shipyards.end());
  2711. if(!shipyards.size())
  2712. {
  2713. //TODO consider possibility of building shipyard in a town
  2714. throw cannotFulfillGoalException("There is no known shipyard!");
  2715. }
  2716. //we have only shipyards that possibly can build ships onto the appropriate EP
  2717. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  2718. {
  2719. return s->o->tempOwner == ai->playerID;
  2720. });
  2721. if(ownedGoodShipyard != shipyards.end())
  2722. {
  2723. const IShipyard *s = *ownedGoodShipyard;
  2724. TResources shipCost;
  2725. s->getBoatCost(shipCost);
  2726. if(cb->getResourceAmount().canAfford(shipCost))
  2727. {
  2728. int3 ret = s->bestLocation();
  2729. cb->buildBoat(s);
  2730. return ret;
  2731. }
  2732. else
  2733. {
  2734. //TODO gather res
  2735. throw cannotFulfillGoalException("Not enough resources to build a boat");
  2736. }
  2737. }
  2738. else
  2739. {
  2740. //TODO pick best shipyard to take over
  2741. return shipyards.front()->o->pos;
  2742. }
  2743. }
  2744. }
  2745. else if(src->water && !sectorToReach->water)
  2746. {
  2747. //TODO
  2748. //disembark
  2749. }
  2750. else
  2751. {
  2752. //TODO
  2753. //transition between two land/water sectors. Monolith? Whirlpool? ...
  2754. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  2755. }
  2756. }
  2757. else
  2758. {
  2759. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  2760. }
  2761. }
  2762. else
  2763. {
  2764. makeParentBFS(h->visitablePos());
  2765. int3 curtile = dst;
  2766. while(curtile != h->visitablePos())
  2767. {
  2768. if(cb->getPathInfo(curtile)->reachable())
  2769. {
  2770. return curtile;
  2771. }
  2772. else
  2773. {
  2774. auto i = parent.find(curtile);
  2775. if(i != parent.end())
  2776. {
  2777. assert(curtile != i->second);
  2778. curtile = i->second;
  2779. }
  2780. else
  2781. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  2782. }
  2783. }
  2784. }
  2785. throw cannotFulfillGoalException("Impossible happened.");
  2786. }
  2787. void SectorMap::makeParentBFS(crint3 source)
  2788. {
  2789. parent.clear();
  2790. int mySector = retreiveTile(source);
  2791. std::queue<int3> toVisit;
  2792. toVisit.push(source);
  2793. while(toVisit.size())
  2794. {
  2795. int3 curPos = toVisit.front();
  2796. toVisit.pop();
  2797. ui8 &sec = retreiveTile(curPos);
  2798. assert(sec == mySector); //consider only tiles from the same sector
  2799. //const TerrainTile *t = cb->getTile(curPos);
  2800. foreach_neighbour(curPos, [&](crint3 neighPos)
  2801. {
  2802. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  2803. {
  2804. toVisit.push(neighPos);
  2805. parent[neighPos] = curPos;
  2806. }
  2807. });
  2808. }
  2809. }
  2810. unsigned char & SectorMap::retreiveTile(crint3 pos)
  2811. {
  2812. return retreiveTileN(sector, pos);
  2813. }
  2814. const CGObjectInstance * ObjectIdRef::operator->() const
  2815. {
  2816. return cb->getObj(id, false);
  2817. }
  2818. ObjectIdRef::operator const CGObjectInstance*() const
  2819. {
  2820. return cb->getObj(id, false);
  2821. }
  2822. ObjectIdRef::ObjectIdRef(int _id) : id(_id)
  2823. {
  2824. }
  2825. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  2826. {
  2827. }
  2828. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  2829. {
  2830. return id < rhs.id;
  2831. }
  2832. HeroPtr::HeroPtr(const CGHeroInstance *H)
  2833. {
  2834. if(!H)
  2835. {
  2836. //init from nullptr should equal to default init
  2837. *this = HeroPtr();
  2838. return;
  2839. }
  2840. h = H;
  2841. name = h->name;
  2842. hid = H->subID;
  2843. // infosCount[ai->playerID][hid]++;
  2844. }
  2845. HeroPtr::HeroPtr()
  2846. {
  2847. h = nullptr;
  2848. hid = -1;
  2849. }
  2850. HeroPtr::~HeroPtr()
  2851. {
  2852. // if(hid >= 0)
  2853. // infosCount[ai->playerID][hid]--;
  2854. }
  2855. bool HeroPtr::operator<(const HeroPtr &rhs) const
  2856. {
  2857. return hid < rhs.hid;
  2858. }
  2859. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
  2860. {
  2861. //TODO? check if these all assertions every time we get info about hero affect efficiency
  2862. //
  2863. //behave terribly when attempting unauthorised access to hero that is not ours (or was lost)
  2864. assert(doWeExpectNull || h);
  2865. if(h)
  2866. {
  2867. assert(cb->getObj(h->id));
  2868. assert(h->tempOwner == ai->playerID);
  2869. }
  2870. return h;
  2871. }
  2872. const CGHeroInstance * HeroPtr::operator->() const
  2873. {
  2874. return get();
  2875. }
  2876. bool HeroPtr::validAndSet() const
  2877. {
  2878. return get(true);
  2879. }
  2880. const CGHeroInstance * HeroPtr::operator*() const
  2881. {
  2882. return get();
  2883. }