VCAI.cpp 66 KB

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