VCAI.cpp 83 KB

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