VCAI.cpp 72 KB

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