VCAI.cpp 65 KB

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