VCAI.cpp 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992
  1. #include "StdInc.h"
  2. #include "VCAI.h"
  3. #include "../../lib/UnlockGuard.h"
  4. #include "../../lib/CObjectHandler.h"
  5. #include "../../lib/CConfigHandler.h"
  6. #include "../../lib/CHeroHandler.h"
  7. #define I_AM_ELEMENTAR return CGoal(*this).setisElementar(true)
  8. CLogger &aiLogger = tlog6;
  9. extern FuzzyHelper *fh;
  10. class CGVisitableOPW;
  11. const int ACTUAL_RESOURCE_COUNT = 7;
  12. const double SAFE_ATTACK_CONSTANT = 1.5;
  13. using namespace vstd;
  14. //one thread may be turn of AI and another will be handling a side effect for AI2
  15. boost::thread_specific_ptr<CCallback> cb;
  16. boost::thread_specific_ptr<VCAI> ai;
  17. //std::map<int, std::map<int, int> > HeroView::infosCount;
  18. // CCallback *cb;
  19. // VCAI *ai;
  20. //helper RAII to manage global ai/cb ptrs
  21. struct SetGlobalState
  22. {
  23. SetGlobalState(VCAI * AI)
  24. {
  25. assert(!ai.get());
  26. assert(!cb.get());
  27. ai.reset(AI);
  28. cb.reset(AI->myCb);
  29. }
  30. ~SetGlobalState()
  31. {
  32. ai.release();
  33. cb.release();
  34. }
  35. };
  36. template <typename Container>
  37. typename Container::value_type backOrNull(const Container &c) //returns last element of container or NULL if it is empty (to be used with containers of pointers)
  38. {
  39. if(c.size())
  40. return c.back();
  41. else
  42. return NULL;
  43. }
  44. template <typename Container>
  45. typename Container::value_type frontOrNull(const Container &c) //returns first element of container or NULL if it is empty (to be used with containers of pointers)
  46. {
  47. if(c.size())
  48. return c.front();
  49. else
  50. return NULL;
  51. }
  52. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  53. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  54. #define MAKING_TURN SET_GLOBAL_STATE(this)
  55. 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)
  56. const int HERO_GOLD_COST = 2500;
  57. const int ALLOWED_ROAMING_HEROES = 8;
  58. const int GOLD_MINE_PRODUCTION = 1000, WOOD_ORE_MINE_PRODUCTION = 2, RESOURCE_MINE_PRODUCTION = 1;
  59. std::string CGoal::name() const
  60. {
  61. switch (goalType)
  62. {
  63. case INVALID:
  64. return "INVALID";
  65. case WIN:
  66. return "WIN";
  67. case DO_NOT_LOSE:
  68. return "DO NOT LOOSE";
  69. case CONQUER:
  70. return "CONQUER";
  71. case BUILD:
  72. return "BUILD";
  73. case EXPLORE:
  74. return "EXPLORE";
  75. case GATHER_ARMY:
  76. return "GATHER ARMY";
  77. case BOOST_HERO:
  78. return "BOOST_HERO (unsupported)";
  79. case RECRUIT_HERO:
  80. return "RECRUIT HERO";
  81. case BUILD_STRUCTURE:
  82. return "BUILD STRUCTURE";
  83. case COLLECT_RES:
  84. return "COLLECT RESOURCE";
  85. case GATHER_TROOPS:
  86. return "GATHER TROOPS";
  87. case GET_OBJ:
  88. return "GET OBJECT " + boost::lexical_cast<std::string>(objid);
  89. case FIND_OBJ:
  90. return "FIND OBJECT " + boost::lexical_cast<std::string>(objid);
  91. case VISIT_HERO:
  92. return "VISIT HERO " + boost::lexical_cast<std::string>(objid);
  93. case GET_ART_TYPE:
  94. return "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  95. case ISSUE_COMMAND:
  96. return "ISSUE COMMAND (unsupported)";
  97. case VISIT_TILE:
  98. return "VISIT TILE " + tile();
  99. case CLEAR_WAY_TO:
  100. return "CLEAR WAY TO " + tile();
  101. case DIG_AT_TILE:
  102. return "DIG AT TILE " + tile();
  103. default:
  104. return boost::lexical_cast<std::string>(goalType);
  105. }
  106. }
  107. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  108. {
  109. return h1->getTotalStrength() < h2->getTotalStrength();
  110. }
  111. bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
  112. {
  113. return a1->getArmyStrength() < a2->getArmyStrength();
  114. }
  115. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  116. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  117. struct AILogger
  118. {
  119. AILogger()
  120. {
  121. lvl = 0;
  122. }
  123. int lvl;
  124. struct Tab
  125. {
  126. Tab();
  127. ~Tab();
  128. };
  129. } logger;
  130. AILogger::Tab::Tab()
  131. {
  132. logger.lvl++;
  133. }
  134. AILogger::Tab::~Tab()
  135. {
  136. logger.lvl--;
  137. }
  138. struct TimeCheck
  139. {
  140. CStopWatch time;
  141. std::string txt;
  142. TimeCheck(crstring TXT) : txt(TXT)
  143. {
  144. }
  145. ~TimeCheck()
  146. {
  147. BNLOG("Time of %s was %d ms.", txt % time.getDiff());
  148. }
  149. };
  150. template<typename T>
  151. void removeDuplicates(std::vector<T> &vec)
  152. {
  153. boost::sort(vec);
  154. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  155. }
  156. struct AtScopeExit
  157. {
  158. boost::function<void()> foo;
  159. AtScopeExit(const boost::function<void()> &FOO) : foo(FOO)
  160. {}
  161. ~AtScopeExit()
  162. {
  163. foo();
  164. }
  165. };
  166. void foreach_tile_pos(boost::function<void(const int3& pos)> foo)
  167. {
  168. for(int i = 0; i < cb->getMapSize().x; i++)
  169. for(int j = 0; j < cb->getMapSize().y; j++)
  170. for(int k = 0; k < cb->getMapSize().z; k++)
  171. foo(int3(i,j,k));
  172. }
  173. void foreach_neighbour(const int3 &pos, boost::function<void(const int3& pos)> foo)
  174. {
  175. BOOST_FOREACH(const int3 &dir, dirs)
  176. {
  177. const int3 n = pos + dir;
  178. if(cb->isInTheMap(n))
  179. foo(pos+dir);
  180. }
  181. }
  182. unsigned char &retreiveTileN(std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  183. {
  184. return vectors[pos.x][pos.y][pos.z];
  185. }
  186. const unsigned char &retreiveTileN(const std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  187. {
  188. return vectors[pos.x][pos.y][pos.z];
  189. }
  190. void foreach_tile(std::vector< std::vector< std::vector<unsigned char> > > &vectors, boost::function<void(unsigned char &in)> foo)
  191. {
  192. for(auto i = vectors.begin(); i != vectors.end(); i++)
  193. for(auto j = i->begin(); j != i->end(); j++)
  194. for(auto z = j->begin(); z != j->end(); z++)
  195. foo(*z);
  196. }
  197. struct ObjInfo
  198. {
  199. int3 pos;
  200. std::string name;
  201. ObjInfo(){}
  202. ObjInfo(const CGObjectInstance *obj)
  203. {
  204. pos = obj->pos;
  205. name = obj->getHoverText();
  206. }
  207. };
  208. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  209. template <typename Container, typename Item>
  210. bool remove_if_present(Container &c, const Item &item)
  211. {
  212. auto i = std::find(c.begin(), c.end(), item);
  213. if (i != c.end())
  214. {
  215. c.erase(i);
  216. return true;
  217. }
  218. return false;
  219. }
  220. template <typename V, typename Item, typename Item2>
  221. bool remove_if_present(std::map<Item,V> & c, const Item2 &item)
  222. {
  223. auto i = c.find(item);
  224. if (i != c.end())
  225. {
  226. c.erase(i);
  227. return true;
  228. }
  229. return false;
  230. }
  231. template <typename Container, typename Pred>
  232. void erase(Container &c, Pred pred)
  233. {
  234. c.erase(boost::remove_if(c, pred), c.end());
  235. }
  236. bool isReachable(const CGObjectInstance *obj)
  237. {
  238. return cb->getPathInfo(obj->visitablePos())->turns < 255;
  239. }
  240. ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t)
  241. {
  242. ui64 ret = 0;
  243. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  244. std::vector<const CStackInstance *> toMove;
  245. BOOST_FOREACH(auto const slot, t->Slots())
  246. {
  247. //can be merged woth another stack?
  248. TSlot dst = h->getSlotFor(slot.second->getCreatureID());
  249. if(h->hasStackAtSlot(dst))
  250. ret += t->getPower(slot.first);
  251. else
  252. toMove.push_back(slot.second);
  253. }
  254. boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
  255. {
  256. return lhs->getPower() < rhs->getPower();
  257. });
  258. BOOST_REVERSE_FOREACH(const CStackInstance *stack, toMove)
  259. {
  260. if(freeHeroSlots)
  261. {
  262. ret += stack->getPower();
  263. freeHeroSlots--;
  264. }
  265. else
  266. break;
  267. }
  268. return ret;
  269. }
  270. std::string strFromInt3(int3 pos)
  271. {
  272. std::ostringstream oss;
  273. oss << pos;
  274. return oss.str();
  275. }
  276. bool isCloser(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  277. {
  278. const CGPathNode *ln = cb->getPathInfo(lhs->visitablePos()), *rn = cb->getPathInfo(rhs->visitablePos());
  279. if(ln->turns != rn->turns)
  280. return ln->turns < rn->turns;
  281. return (ln->moveRemains > rn->moveRemains);
  282. }
  283. bool compareMovement(HeroPtr lhs, HeroPtr rhs)
  284. {
  285. return lhs->movement > rhs->movement;
  286. }
  287. ui64 evaluateDanger(const CGObjectInstance *obj);
  288. ui64 evaluateDanger(crint3 tile)
  289. {
  290. const TerrainTile *t = cb->getTile(tile, false);
  291. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  292. return 190000000; //MUCH
  293. ui64 objectDanger = 0, guardDanger = 0;
  294. auto visObjs = cb->getVisitableObjs(tile);
  295. if(visObjs.size())
  296. objectDanger = evaluateDanger(visObjs.back());
  297. int3 guardPos = cb->guardingCreaturePosition(tile);
  298. if(guardPos.x >= 0 && guardPos != tile)
  299. guardDanger = evaluateDanger(guardPos);
  300. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  301. return std::max(objectDanger, guardDanger);
  302. return 0;
  303. }
  304. ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
  305. {
  306. const TerrainTile *t = cb->getTile(tile, false);
  307. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  308. return 190000000; //MUCH
  309. ui64 objectDanger = 0, guardDanger = 0;
  310. auto visitableObjects = cb->getVisitableObjs(tile);
  311. // in some scenarios hero happens to be "under" the object (eg town). Then we consider ONLY the hero.
  312. if(vstd::contains_if(visitableObjects, objWithID<Obj::HERO>))
  313. erase_if(visitableObjects, ! boost::bind(objWithID<Obj::HERO>, _1));
  314. if(const CGObjectInstance * dangerousObject = backOrNull(visitableObjects))
  315. {
  316. objectDanger = evaluateDanger(dangerousObject); //unguarded objects can also be dangerous or unhandled
  317. if (objectDanger)
  318. {
  319. //TODO: don't downcast objects AI shouldnt know about!
  320. auto armedObj = dynamic_cast<const CArmedInstance*>(dangerousObject);
  321. if(armedObj)
  322. objectDanger *= fh->getTacticalAdvantage(visitor, armedObj); //this line tends to go infinite for allied towns (?)
  323. }
  324. }
  325. auto guards = cb->getGuardingCreatures(tile);
  326. BOOST_FOREACH (auto cre, guards)
  327. {
  328. amax (guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre))); //we are interested in strongest monster around
  329. }
  330. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  331. return std::max(objectDanger, guardDanger);
  332. }
  333. ui64 evaluateDanger(const CGObjectInstance *obj)
  334. {
  335. if(obj->tempOwner < GameConstants::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES) //owned or allied objects don't pose any threat
  336. return 0;
  337. switch(obj->ID)
  338. {
  339. case Obj::HERO:
  340. {
  341. InfoAboutHero iah;
  342. cb->getHeroInfo(obj, iah);
  343. return iah.army.getStrength();
  344. }
  345. case Obj::TOWN:
  346. case Obj::GARRISON: case Obj::GARRISON2: //garrison
  347. {
  348. InfoAboutTown iat;
  349. cb->getTownInfo(obj, iat);
  350. return iat.army.getStrength();
  351. }
  352. case Obj::MONSTER:
  353. {
  354. //TODO!!!!!!!!
  355. const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
  356. return cre->getArmyStrength();
  357. }
  358. case Obj::CREATURE_GENERATOR1:
  359. {
  360. const CGDwelling *d = dynamic_cast<const CGDwelling*>(obj);
  361. return d->getArmyStrength();
  362. }
  363. case Obj::MINE:
  364. case Obj::ABANDONED_MINE:
  365. {
  366. const CArmedInstance * a = dynamic_cast<const CArmedInstance*>(obj);
  367. return a->getArmyStrength();
  368. }
  369. case Obj::CRYPT: //crypt
  370. case Obj::CREATURE_BANK: //crebank
  371. case Obj::DRAGON_UTOPIA:
  372. case Obj::SHIPWRECK: //shipwreck
  373. case Obj::DERELICT_SHIP: //derelict ship
  374. // case Obj::PYRAMID:
  375. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  376. case Obj::PYRAMID:
  377. {
  378. if(obj->subID == 0)
  379. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  380. else
  381. return 0;
  382. }
  383. default:
  384. return 0;
  385. }
  386. }
  387. bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  388. {
  389. return evaluateDanger(lhs) < evaluateDanger(rhs);
  390. }
  391. VCAI::VCAI(void)
  392. {
  393. LOG_ENTRY;
  394. myCb = NULL;
  395. makingTurn = NULL;
  396. }
  397. VCAI::~VCAI(void)
  398. {
  399. LOG_ENTRY;
  400. }
  401. void VCAI::availableCreaturesChanged(const CGDwelling *town)
  402. {
  403. NET_EVENT_HANDLER;
  404. LOG_ENTRY;
  405. }
  406. void VCAI::heroMoved(const TryMoveHero & details)
  407. {
  408. NET_EVENT_HANDLER;
  409. LOG_ENTRY;
  410. if(details.result == TryMoveHero::TELEPORTATION)
  411. {
  412. const int3 from = CGHeroInstance::convertPosition(details.start, false),
  413. to = CGHeroInstance::convertPosition(details.end, false);
  414. const CGObjectInstance *o1 = frontOrNull(cb->getVisitableObjs(from)),
  415. *o2 = frontOrNull(cb->getVisitableObjs(to));
  416. if(o1 && o2 && o1->ID == Obj::SUBTERRANEAN_GATE && o2->ID == Obj::SUBTERRANEAN_GATE)
  417. {
  418. knownSubterraneanGates[o1] = o2;
  419. knownSubterraneanGates[o2] = o1;
  420. BNLOG("Found a pair of subterranean gates between %s and %s!", from % to);
  421. }
  422. }
  423. }
  424. void VCAI::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  425. {
  426. NET_EVENT_HANDLER;
  427. LOG_ENTRY;
  428. }
  429. void VCAI::heroInGarrisonChange(const CGTownInstance *town)
  430. {
  431. NET_EVENT_HANDLER;
  432. LOG_ENTRY;
  433. }
  434. void VCAI::centerView(int3 pos, int focusTime)
  435. {
  436. NET_EVENT_HANDLER;
  437. LOG_ENTRY;
  438. }
  439. void VCAI::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  440. {
  441. NET_EVENT_HANDLER;
  442. LOG_ENTRY;
  443. }
  444. void VCAI::artifactAssembled(const ArtifactLocation &al)
  445. {
  446. NET_EVENT_HANDLER;
  447. LOG_ENTRY;
  448. }
  449. void VCAI::showTavernWindow(const CGObjectInstance *townOrTavern)
  450. {
  451. NET_EVENT_HANDLER;
  452. LOG_ENTRY;
  453. }
  454. void VCAI::showThievesGuildWindow (const CGObjectInstance * obj)
  455. {
  456. NET_EVENT_HANDLER;
  457. LOG_ENTRY;
  458. }
  459. void VCAI::playerBlocked(int reason)
  460. {
  461. NET_EVENT_HANDLER;
  462. LOG_ENTRY;
  463. if (reason == PlayerBlocked::UPCOMING_BATTLE)
  464. status.setBattle(UPCOMING_BATTLE);
  465. }
  466. void VCAI::showPuzzleMap()
  467. {
  468. NET_EVENT_HANDLER;
  469. LOG_ENTRY;
  470. }
  471. void VCAI::showShipyardDialog(const IShipyard *obj)
  472. {
  473. NET_EVENT_HANDLER;
  474. LOG_ENTRY;
  475. }
  476. void VCAI::gameOver(ui8 player, bool victory)
  477. {
  478. NET_EVENT_HANDLER;
  479. LOG_ENTRY;
  480. BNLOG("Player %d: I heard that player %d %s.", playerID % (int)player % (victory ? "won" : "lost"));
  481. if(player == playerID)
  482. {
  483. if(victory)
  484. {
  485. tlog0 << "VCAI: I won! Incredible!\n";
  486. tlog0 << "Turn nr " << myCb->getDate() << std::endl;
  487. }
  488. else
  489. {
  490. tlog0 << "VCAI: Player " << (int)player << " lost. It's me. What a disappointment! :(\n";
  491. }
  492. // //let's make Impossible difficulty finally standing to its name :>
  493. // if(myCb->getStartInfo()->difficulty == 4 && !victory)
  494. // {
  495. // //play dirty: crash the whole engine to avoid lose
  496. // //that way AI is unbeatable!
  497. // *(int*)NULL = 666;
  498. // }
  499. // TODO - at least write some insults on stdout
  500. finish();
  501. }
  502. }
  503. void VCAI::artifactPut(const ArtifactLocation &al)
  504. {
  505. NET_EVENT_HANDLER;
  506. LOG_ENTRY;
  507. }
  508. void VCAI::artifactRemoved(const ArtifactLocation &al)
  509. {
  510. NET_EVENT_HANDLER;
  511. LOG_ENTRY;
  512. }
  513. void VCAI::stacksErased(const StackLocation &location)
  514. {
  515. NET_EVENT_HANDLER;
  516. LOG_ENTRY;
  517. }
  518. void VCAI::artifactDisassembled(const ArtifactLocation &al)
  519. {
  520. NET_EVENT_HANDLER;
  521. LOG_ENTRY;
  522. }
  523. void VCAI::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  524. {
  525. NET_EVENT_HANDLER;
  526. LOG_ENTRY;
  527. if (start)
  528. {
  529. visitedObject = const_cast<CGObjectInstance *>(visitedObj); // remember the object and wait for return
  530. markObjectVisited (visitedObj);
  531. remove_if_present(reservedObjs, visitedObj); //unreserve objects
  532. remove_if_present(reservedHeroesMap[visitor], visitedObj);
  533. completeGoal (CGoal(GET_OBJ).sethero(visitor)); //we don't need to visit in anymore
  534. }
  535. }
  536. void VCAI::availableArtifactsChanged(const CGBlackMarket *bm /*= NULL*/)
  537. {
  538. NET_EVENT_HANDLER;
  539. LOG_ENTRY;
  540. }
  541. void VCAI::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  542. {
  543. NET_EVENT_HANDLER;
  544. LOG_ENTRY;
  545. //buildArmyIn(town);
  546. //moveCreaturesToHero(town);
  547. }
  548. void VCAI::tileHidden(const boost::unordered_set<int3, ShashInt3> &pos)
  549. {
  550. NET_EVENT_HANDLER;
  551. LOG_ENTRY;
  552. // BOOST_FOREACH(int3 tile, pos)
  553. // BOOST_FOREACH(const CGObjectInstance *obj, cb->getVisitableObjs(tile))
  554. // remove_if_present(visitableObjs, obj);
  555. visitableObjs.erase(boost::remove_if(visitableObjs, [&](const CGObjectInstance *obj){return !myCb->getObj(obj->id);}), visitableObjs.end());
  556. }
  557. void VCAI::tileRevealed(const boost::unordered_set<int3, ShashInt3> &pos)
  558. {
  559. NET_EVENT_HANDLER;
  560. LOG_ENTRY;
  561. BOOST_FOREACH(int3 tile, pos)
  562. BOOST_FOREACH(const CGObjectInstance *obj, myCb->getVisitableObjs(tile))
  563. addVisitableObj(obj);
  564. }
  565. void VCAI::heroExchangeStarted(si32 hero1, si32 hero2)
  566. {
  567. NET_EVENT_HANDLER;
  568. LOG_ENTRY;
  569. auto firstHero = cb->getHero(hero1);
  570. auto secondHero = cb->getHero(hero2);
  571. requestActionASAP([=]()
  572. {
  573. if (firstHero->getHeroStrength() > secondHero->getHeroStrength() && canGetArmy (firstHero, secondHero))
  574. pickBestCreatures (firstHero, secondHero);
  575. else if (canGetArmy (secondHero, firstHero))
  576. pickBestCreatures (secondHero, firstHero);
  577. completeGoal(CGoal(VISIT_HERO).sethero(firstHero)); //TODO: what if we were visited by other hero in the meantime?
  578. completeGoal(CGoal(VISIT_HERO).sethero(secondHero));
  579. //TODO: exchange artifacts
  580. });
  581. }
  582. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  583. {
  584. NET_EVENT_HANDLER;
  585. LOG_ENTRY;
  586. }
  587. void VCAI::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  588. {
  589. NET_EVENT_HANDLER;
  590. LOG_ENTRY;
  591. }
  592. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  593. {
  594. NET_EVENT_HANDLER;
  595. LOG_ENTRY;
  596. }
  597. void VCAI::stackChangedType(const StackLocation &location, const CCreature &newType)
  598. {
  599. NET_EVENT_HANDLER;
  600. LOG_ENTRY;
  601. }
  602. void VCAI::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  603. {
  604. NET_EVENT_HANDLER;
  605. LOG_ENTRY;
  606. }
  607. void VCAI::newObject(const CGObjectInstance * obj)
  608. {
  609. NET_EVENT_HANDLER;
  610. LOG_ENTRY;
  611. if(obj->isVisitable())
  612. addVisitableObj(obj);
  613. }
  614. void VCAI::objectRemoved(const CGObjectInstance *obj)
  615. {
  616. NET_EVENT_HANDLER;
  617. LOG_ENTRY;
  618. if(remove_if_present(visitableObjs, obj))
  619. assert(obj->isVisitable());
  620. BOOST_FOREACH(auto &p, reservedHeroesMap)
  621. remove_if_present(p.second, obj);
  622. //TODO
  623. //there are other places where CGObjectinstance ptrs are stored...
  624. //
  625. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  626. {
  627. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is killed just before actual deletion
  628. }
  629. }
  630. void VCAI::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  631. {
  632. NET_EVENT_HANDLER;
  633. LOG_ENTRY;
  634. requestActionASAP([=]()
  635. {
  636. makePossibleUpgrades(visitor);
  637. });
  638. }
  639. void VCAI::playerBonusChanged(const Bonus &bonus, bool gain)
  640. {
  641. NET_EVENT_HANDLER;
  642. LOG_ENTRY;
  643. }
  644. void VCAI::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  645. {
  646. NET_EVENT_HANDLER;
  647. LOG_ENTRY;
  648. }
  649. void VCAI::heroCreated(const CGHeroInstance*)
  650. {
  651. NET_EVENT_HANDLER;
  652. LOG_ENTRY;
  653. }
  654. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  655. {
  656. NET_EVENT_HANDLER;
  657. LOG_ENTRY;
  658. }
  659. void VCAI::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  660. {
  661. NET_EVENT_HANDLER;
  662. LOG_ENTRY;
  663. }
  664. void VCAI::requestRealized(PackageApplied *pa)
  665. {
  666. NET_EVENT_HANDLER;
  667. LOG_ENTRY;
  668. if(status.haveTurn())
  669. {
  670. if(pa->packType == typeList.getTypeID<EndTurn>())
  671. if(pa->result)
  672. status.madeTurn();
  673. }
  674. if(pa->packType == typeList.getTypeID<QueryReply>())
  675. {
  676. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  677. }
  678. }
  679. void VCAI::receivedResource(int type, int val)
  680. {
  681. NET_EVENT_HANDLER;
  682. LOG_ENTRY;
  683. }
  684. void VCAI::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  685. {
  686. NET_EVENT_HANDLER;
  687. LOG_ENTRY;
  688. }
  689. void VCAI::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  690. {
  691. NET_EVENT_HANDLER;
  692. LOG_ENTRY;
  693. }
  694. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  695. {
  696. NET_EVENT_HANDLER;
  697. LOG_ENTRY;
  698. }
  699. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  700. {
  701. NET_EVENT_HANDLER;
  702. LOG_ENTRY;
  703. }
  704. void VCAI::battleResultsApplied()
  705. {
  706. NET_EVENT_HANDLER;
  707. LOG_ENTRY;
  708. assert(status.getBattle() == ENDING_BATTLE);
  709. status.setBattle(NO_BATTLE);
  710. }
  711. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  712. {
  713. NET_EVENT_HANDLER;
  714. LOG_ENTRY;
  715. if(sop->what == ObjProperty::OWNER)
  716. {
  717. if(sop->val == playerID)
  718. remove_if_present(visitableObjs, myCb->getObj(sop->id));
  719. //TODO restore lost obj
  720. }
  721. }
  722. void VCAI::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what)
  723. {
  724. NET_EVENT_HANDLER;
  725. LOG_ENTRY;
  726. }
  727. void VCAI::heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain)
  728. {
  729. NET_EVENT_HANDLER;
  730. LOG_ENTRY;
  731. }
  732. void VCAI::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  733. {
  734. NET_EVENT_HANDLER;
  735. LOG_ENTRY;
  736. }
  737. void VCAI::init(CCallback * CB)
  738. {
  739. myCb = CB;
  740. cbc = CB;
  741. NET_EVENT_HANDLER;
  742. LOG_ENTRY;
  743. playerID = *myCb->getMyColor();
  744. myCb->waitTillRealize = true;
  745. myCb->unlockGsWhenWaiting = true;
  746. if(!fh)
  747. fh = new FuzzyHelper();
  748. retreiveVisitableObjs(visitableObjs);
  749. }
  750. void VCAI::yourTurn()
  751. {
  752. NET_EVENT_HANDLER;
  753. LOG_ENTRY;
  754. status.startedTurn();
  755. makingTurn = new boost::thread(&VCAI::makeTurn, this);
  756. }
  757. void VCAI::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill::SecondarySkill> &skills, int queryID)
  758. {
  759. NET_EVENT_HANDLER;
  760. LOG_ENTRY;
  761. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  762. requestActionASAP([=]{ answerQuery(queryID, 0); });
  763. }
  764. void VCAI::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, int queryID)
  765. {
  766. NET_EVENT_HANDLER;
  767. LOG_ENTRY;
  768. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  769. requestActionASAP([=]{ answerQuery(queryID, 0); });
  770. }
  771. void VCAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 askID, const int soundID, bool selection, bool cancel)
  772. {
  773. NET_EVENT_HANDLER;
  774. LOG_ENTRY;
  775. int sel = 0;
  776. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  777. % components.size() % text));
  778. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  779. sel = components.size();
  780. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  781. sel = 1;
  782. requestActionASAP([=]()
  783. {
  784. answerQuery(askID, sel);
  785. });
  786. }
  787. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, int queryID)
  788. {
  789. NET_EVENT_HANDLER;
  790. LOG_ENTRY;
  791. std::string s1 = up ? up->nodeName() : "NONE";
  792. std::string s2 = down ? down->nodeName() : "NONE";
  793. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  794. //you can't request action from action-response thread
  795. requestActionASAP([=]()
  796. {
  797. pickBestCreatures (down, up);
  798. answerQuery(queryID, 0);
  799. });
  800. }
  801. void VCAI::serialize(COSer<CSaveFile> &h, const int version)
  802. {
  803. NET_EVENT_HANDLER;
  804. LOG_ENTRY;
  805. }
  806. void VCAI::serialize(CISer<CLoadFile> &h, const int version)
  807. {
  808. NET_EVENT_HANDLER;
  809. LOG_ENTRY;
  810. }
  811. void makePossibleUpgrades(const CArmedInstance *obj)
  812. {
  813. if(!obj)
  814. return;
  815. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  816. {
  817. if(const CStackInstance *s = obj->getStackPtr(i))
  818. {
  819. UpgradeInfo ui;
  820. cb->getUpgradeInfo(obj, i, ui);
  821. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  822. {
  823. cb->upgradeCreature(obj, i, ui.newID[0]);
  824. }
  825. }
  826. }
  827. }
  828. void VCAI::makeTurn()
  829. {
  830. MAKING_TURN;
  831. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  832. setThreadName("VCAI::makeTurn");
  833. BNLOG("Player %d starting turn", playerID);
  834. INDENT;
  835. switch(cb->getDate(Date::DAY_OF_WEEK))
  836. {
  837. case 1:
  838. {
  839. townVisitsThisWeek.clear();
  840. std::vector<const CGObjectInstance *> objs;
  841. retreiveVisitableObjs(objs, true);
  842. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  843. {
  844. if (isWeeklyRevisitable(obj))
  845. {
  846. if (!vstd::contains(visitableObjs, obj))
  847. visitableObjs.push_back(obj);
  848. auto o = std::find (alreadyVisited.begin(), alreadyVisited.end(), obj);
  849. if (o != alreadyVisited.end())
  850. alreadyVisited.erase(o);
  851. }
  852. }
  853. }
  854. break;
  855. case 7: //reconsider strategy
  856. {
  857. if(auto h = primaryHero()) //check if our primary hero can handle danger
  858. {
  859. ui64 totalDanger = 0;
  860. int dangerousObjects = 0;
  861. std::vector<const CGObjectInstance *> objs;
  862. retreiveVisitableObjs(objs, false);
  863. BOOST_FOREACH (auto obj, objs)
  864. {
  865. if (evaluateDanger(obj)) //potentilaly dnagerous
  866. {
  867. totalDanger += evaluateDanger(obj->visitablePos(), *h);
  868. ++dangerousObjects;
  869. }
  870. }
  871. ui64 averageDanger = totalDanger / std::max(dangerousObjects, 1);
  872. if (dangerousObjects && averageDanger > h->getHeroStrength())
  873. {
  874. setGoal (h, CGoal(GATHER_ARMY).sethero(h).setvalue(averageDanger * SAFE_ATTACK_CONSTANT).setisAbstract(true));
  875. }
  876. }
  877. }
  878. break;
  879. }
  880. if(cb->getSelectedHero())
  881. cb->recalculatePaths();
  882. makeTurnInternal();
  883. vstd::clear_pointer(makingTurn);
  884. return;
  885. }
  886. void VCAI::makeTurnInternal()
  887. {
  888. saving = 0;
  889. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  890. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  891. moveCreaturesToHero(t);
  892. try
  893. {
  894. //Pick objects reserved in previous turn - we expect only nerby objects there
  895. auto reservedHeroesCopy = reservedHeroesMap; //work on copy => the map may be changed while iterating (eg because hero died when attempting a goal)
  896. BOOST_FOREACH (auto hero, reservedHeroesCopy)
  897. {
  898. cb->setSelection(hero.first.get());
  899. boost::sort (hero.second, isCloser);
  900. BOOST_FOREACH (auto obj, hero.second)
  901. {
  902. striveToGoal (CGoal(VISIT_TILE).sethero(hero.first).settile(obj->visitablePos()));
  903. }
  904. }
  905. //now try to win
  906. striveToGoal(CGoal(WIN));
  907. //finally, continue our abstract long-term goals
  908. //heroes tend to die in the process and loose their goals, unsafe to iterate it
  909. std::vector<std::pair<HeroPtr, CGoal> > safeCopy;
  910. boost::copy(lockedHeroes, std::back_inserter(safeCopy));
  911. typedef std::pair<HeroPtr, CGoal> TItrType;
  912. auto lockedHeroesSorter = [](TItrType h1, TItrType h2) -> bool
  913. {
  914. return compareMovement (h1.first, h2.first);
  915. };
  916. boost::sort(safeCopy, lockedHeroesSorter);
  917. while (safeCopy.size()) //continue our goals
  918. {
  919. auto it = safeCopy.begin();
  920. if (it->first && it->first->tempOwner == playerID && vstd::contains(lockedHeroes, it->first)) //make sure hero still has his goal
  921. {
  922. cb->setSelection(*it->first);
  923. striveToGoal (it->second);
  924. }
  925. safeCopy.erase(it);
  926. }
  927. auto quests = myCb->getMyQuests();
  928. BOOST_FOREACH (auto quest, quests)
  929. {
  930. striveToQuest (quest);
  931. }
  932. striveToGoal(CGoal(BUILD)); //TODO: smarter building management
  933. }
  934. catch(boost::thread_interrupted &e)
  935. {
  936. tlog0 << "Making turn thread has been interrupted. We'll end without calling endTurn.\n";
  937. return;
  938. }
  939. catch(std::exception &e)
  940. {
  941. tlog0 << "Making turn thread has caught an exception: " << e.what() << "\n";
  942. }
  943. endTurn();
  944. }
  945. bool VCAI::goVisitObj(const CGObjectInstance * obj, HeroPtr h)
  946. {
  947. int3 dst = obj->visitablePos();
  948. BNLOG("%s will try to visit %s at (%s)", h->name % obj->getHoverText() % strFromInt3(dst));
  949. return moveHeroToTile(dst, h);
  950. }
  951. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  952. {
  953. switch (obj->ID)
  954. {
  955. case Obj::CREATURE_GENERATOR1:
  956. recruitCreatures (dynamic_cast<const CGDwelling *>(obj));
  957. checkHeroArmy (h);
  958. break;
  959. case Obj::TOWN:
  960. moveCreaturesToHero (dynamic_cast<const CGTownInstance *>(obj));
  961. if (h->visitedTown) //we are inside, not just attacking
  962. {
  963. townVisitsThisWeek[h].push_back(h->visitedTown);
  964. if (!h->hasSpellbook() && cb->getResourceAmount(Res::GOLD) >= GameConstants::SPELLBOOK_GOLD_COST + saving[Res::GOLD] &&
  965. h->visitedTown->hasBuilt (BuildingID::MAGES_GUILD_1))
  966. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  967. }
  968. break;
  969. }
  970. }
  971. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  972. {
  973. if(t->visitingHero && t->armedGarrison())
  974. {
  975. pickBestCreatures (t->visitingHero, t);
  976. }
  977. }
  978. bool VCAI::canGetArmy (const CGHeroInstance * army, const CGHeroInstance * source)
  979. { //TODO: merge with pickBestCreatures
  980. const CArmedInstance *armies[] = {army, source};
  981. int armySize = 0;
  982. //we calculate total strength for each creature type available in armies
  983. std::map<const CCreature*, int> creToPower;
  984. BOOST_FOREACH(auto armyPtr, armies)
  985. BOOST_FOREACH(auto &i, armyPtr->Slots())
  986. {
  987. ++armySize;//TODO: allow splitting stacks?
  988. creToPower[i.second->type] += i.second->getPower();
  989. }
  990. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  991. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  992. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  993. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  994. {
  995. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  996. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  997. {
  998. return lhs.second < rhs.second;
  999. });
  1000. bestArmy.push_back(creIt->first);
  1001. creToPower.erase(creIt);
  1002. if(creToPower.empty())
  1003. break;
  1004. }
  1005. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  1006. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  1007. {
  1008. BOOST_FOREACH(auto armyPtr, armies)
  1009. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  1010. {
  1011. if(armyPtr->getCreature(j) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  1012. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army)) //can't take away last creature
  1013. return true; //at least one exchange will be performed
  1014. }
  1015. }
  1016. return false;
  1017. }
  1018. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  1019. {
  1020. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  1021. const CArmedInstance *armies[] = {army, source};
  1022. int armySize = 0;
  1023. //we calculate total strength for each creature type available in armies
  1024. std::map<const CCreature*, int> creToPower;
  1025. BOOST_FOREACH(auto armyPtr, armies)
  1026. BOOST_FOREACH(auto &i, armyPtr->Slots())
  1027. {
  1028. ++armySize;//TODO: allow splitting stacks?
  1029. creToPower[i.second->type] += i.second->getPower();
  1030. }
  1031. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  1032. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  1033. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  1034. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  1035. {
  1036. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  1037. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  1038. {
  1039. return lhs.second < rhs.second;
  1040. });
  1041. bestArmy.push_back(creIt->first);
  1042. creToPower.erase(creIt);
  1043. if(creToPower.empty())
  1044. break;
  1045. }
  1046. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  1047. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  1048. {
  1049. BOOST_FOREACH(auto armyPtr, armies)
  1050. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  1051. {
  1052. if(armyPtr->getCreature(j) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  1053. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army))
  1054. cb->mergeOrSwapStacks(armyPtr, army, j, i);
  1055. }
  1056. }
  1057. //TODO - having now strongest possible army, we may want to think about arranging stacks
  1058. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  1059. if (hero)
  1060. {
  1061. checkHeroArmy (hero);
  1062. }
  1063. }
  1064. void VCAI::recruitCreatures(const CGDwelling * d)
  1065. {
  1066. for(int i = 0; i < d->creatures.size(); i++)
  1067. {
  1068. if(!d->creatures[i].second.size())
  1069. continue;
  1070. int count = d->creatures[i].first;
  1071. CreatureID creID = d->creatures[i].second.back();
  1072. // const CCreature *c = VLC->creh->creatures[creID];
  1073. // if(containsSavedRes(c->cost))
  1074. // continue;
  1075. TResources myRes = cb->getResourceAmount();
  1076. myRes[Res::GOLD] -= GOLD_RESERVE;
  1077. amin(count, myRes / VLC->creh->creatures[creID]->cost);
  1078. if(count > 0)
  1079. cb->recruitCreatures(d, creID, count, i);
  1080. }
  1081. }
  1082. bool VCAI::tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays)
  1083. {
  1084. if (!vstd::contains(t->town->buildings, building))
  1085. return false; // no such building in town
  1086. if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  1087. return true;
  1088. std::set<BuildingID> toBuild = cb->getBuildingRequiments(t, building);
  1089. //erase all already built buildings
  1090. for (auto buildIter = toBuild.begin(); buildIter != toBuild.end();)
  1091. {
  1092. if (t->hasBuilt(*buildIter))
  1093. toBuild.erase(buildIter++);
  1094. else
  1095. buildIter++;
  1096. }
  1097. toBuild.insert(building);
  1098. BOOST_FOREACH(BuildingID buildID, toBuild)
  1099. {
  1100. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  1101. if (canBuild == EBuildingState::HAVE_CAPITAL
  1102. || canBuild == EBuildingState::FORBIDDEN
  1103. || canBuild == EBuildingState::NO_WATER)
  1104. return false; //we won't be able to build this
  1105. }
  1106. if (maxDays && toBuild.size() > maxDays)
  1107. return false;
  1108. TResources currentRes = cb->getResourceAmount();
  1109. TResources income = estimateIncome();
  1110. //TODO: calculate if we have enough resources to build it in maxDays
  1111. BOOST_FOREACH(const auto & buildID, toBuild)
  1112. {
  1113. const CBuilding *b = t->town->buildings[buildID];
  1114. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  1115. if(canBuild == EBuildingState::ALLOWED)
  1116. {
  1117. if(!containsSavedRes(b->resources))
  1118. {
  1119. BNLOG("Player %d will build %s in town of %s at %s", playerID % b->Name() % t->name % t->pos);
  1120. cb->buildBuilding(t, buildID);
  1121. return true;
  1122. }
  1123. continue;
  1124. }
  1125. else if(canBuild == EBuildingState::NO_RESOURCES)
  1126. {
  1127. TResources cost = t->town->buildings[buildID]->resources;
  1128. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1129. {
  1130. int diff = currentRes[i] - cost[i] + income[i];
  1131. if(diff < 0)
  1132. saving[i] = 1;
  1133. }
  1134. continue;
  1135. }
  1136. }
  1137. return false;
  1138. }
  1139. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  1140. {
  1141. BOOST_FOREACH(const auto & building, buildList)
  1142. {
  1143. if(t->hasBuilt(building))
  1144. continue;
  1145. if (tryBuildStructure(t, building, maxDays))
  1146. return true;
  1147. }
  1148. return false; //Can't build anything
  1149. }
  1150. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  1151. {
  1152. BOOST_FOREACH(const auto & building, buildList)
  1153. {
  1154. if(t->hasBuilt(building))
  1155. continue;
  1156. return tryBuildStructure(t, building, maxDays);
  1157. }
  1158. return false;//Nothing to build
  1159. }
  1160. void VCAI::buildStructure(const CGTownInstance * t)
  1161. {
  1162. //TODO make *real* town development system
  1163. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  1164. //TODO: build resource silo, defences when needed
  1165. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  1166. //Set of buildings for different goals. Does not include any prerequisites.
  1167. const BuildingID essential[] = {BuildingID::TAVERN, BuildingID::TOWN_HALL};
  1168. const BuildingID goldSource[] = {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL};
  1169. const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  1170. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  1171. const BuildingID unitsUpgrade[] = { BuildingID::DWELL_LVL_1_UP, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP,
  1172. BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP};
  1173. const BuildingID unitGrowth[] = { BuildingID::FORT, BuildingID::CITADEL, BuildingID::CASTLE, BuildingID::HORDE_1,
  1174. BuildingID::HORDE_1_UPGR, BuildingID::HORDE_2, BuildingID::HORDE_2_UPGR};
  1175. const BuildingID spells[] = {BuildingID::MAGES_GUILD_1, BuildingID::MAGES_GUILD_2, BuildingID::MAGES_GUILD_3,
  1176. BuildingID::MAGES_GUILD_4, BuildingID::MAGES_GUILD_5};
  1177. const BuildingID extra[] = {BuildingID::RESOURCE_SILO, BuildingID::SPECIAL_1, BuildingID::SPECIAL_2, BuildingID::SPECIAL_3,
  1178. BuildingID::SPECIAL_4, BuildingID::SHIPYARD}; // all remaining buildings
  1179. TResources currentRes = cb->getResourceAmount();
  1180. TResources income = estimateIncome();
  1181. if (tryBuildAnyStructure(t, std::vector<BuildingID>(essential, essential + ARRAY_COUNT(essential))))
  1182. return;
  1183. //we're running out of gold - try to build something gold-producing. Multiplier can be tweaked, 6 is minimum due to buildings costs
  1184. if (currentRes[Res::GOLD] < income[Res::GOLD] * 6)
  1185. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1186. return;
  1187. if (cb->getDate(Date::DAY_OF_WEEK) > 6)// last 2 days of week - try to focus on growth
  1188. {
  1189. if (tryBuildNextStructure(t, std::vector<BuildingID>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  1190. return;
  1191. }
  1192. // first in-game week or second half of any week: try build dwellings
  1193. if (cb->getDate(Date::DAY) < 7 || cb->getDate(Date::DAY_OF_WEEK) > 3)
  1194. if (tryBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK)))
  1195. return;
  1196. //try to upgrade dwelling
  1197. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  1198. {
  1199. if (t->hasBuilt(unitsSource[i]) && !t->hasBuilt(unitsUpgrade[i]))
  1200. {
  1201. if (tryBuildStructure(t, unitsUpgrade[i]))
  1202. return;
  1203. }
  1204. }
  1205. //remaining tasks
  1206. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1207. return;
  1208. if (tryBuildNextStructure(t, std::vector<BuildingID>(spells, spells + ARRAY_COUNT(spells))))
  1209. return;
  1210. if (tryBuildAnyStructure(t, std::vector<BuildingID>(extra, extra + ARRAY_COUNT(extra))))
  1211. return;
  1212. }
  1213. bool isSafeToVisit(HeroPtr h, crint3 tile)
  1214. {
  1215. const ui64 heroStrength = h->getTotalStrength(),
  1216. dangerStrength = evaluateDanger(tile, *h);
  1217. if(dangerStrength)
  1218. {
  1219. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  1220. {
  1221. BNLOG("It's, safe for %s to visit tile %s", h->name % tile);
  1222. return true;
  1223. }
  1224. else
  1225. return false;
  1226. }
  1227. return true; //there's no danger
  1228. }
  1229. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(HeroPtr h)
  1230. {
  1231. validateVisitableObjs();
  1232. std::vector<const CGObjectInstance *> possibleDestinations;
  1233. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1234. {
  1235. if(cb->getPathInfo(obj->visitablePos())->reachable() && !obj->wasVisited(playerID) &&
  1236. (obj->tempOwner != playerID || isWeeklyRevisitable(obj))) //flag or get weekly resources / creatures
  1237. possibleDestinations.push_back(obj);
  1238. }
  1239. boost::sort(possibleDestinations, isCloser);
  1240. possibleDestinations.erase(boost::remove_if(possibleDestinations, [&](const CGObjectInstance *obj) -> bool
  1241. {
  1242. const int3 pos = obj->visitablePos();
  1243. if(vstd::contains(alreadyVisited, obj))
  1244. return true;
  1245. if(!isSafeToVisit(h, pos))
  1246. return true;
  1247. if (!shouldVisit(h, obj))
  1248. return true;
  1249. if (vstd::contains(reservedObjs, obj)) //does checking for our own reserved objects make sense? here?
  1250. return true;
  1251. const CGObjectInstance *topObj = cb->getVisitableObjs(pos).back(); //it may be hero visiting this obj
  1252. //we don't try visiting object on which allied or owned hero stands
  1253. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1254. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  1255. return true;
  1256. return false;
  1257. }),possibleDestinations.end());
  1258. return possibleDestinations;
  1259. }
  1260. void VCAI::wander(HeroPtr h)
  1261. {
  1262. while(1)
  1263. {
  1264. std::vector <ObjectIdRef> dests;
  1265. range::copy(reservedHeroesMap[h], std::back_inserter(dests));
  1266. if (!dests.size())
  1267. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  1268. if(!dests.size())
  1269. {
  1270. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  1271. {
  1272. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1273. };
  1274. std::vector<const CGTownInstance *> townsReachable;
  1275. std::vector<const CGTownInstance *> townsNotReachable;
  1276. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1277. {
  1278. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  1279. {
  1280. if(isReachable(t))
  1281. townsReachable.push_back(t);
  1282. else
  1283. townsNotReachable.push_back(t);
  1284. }
  1285. }
  1286. if(townsReachable.size())
  1287. {
  1288. boost::sort(townsReachable, compareReinforcements);
  1289. dests.emplace_back(townsReachable.back());
  1290. }
  1291. else if(townsNotReachable.size())
  1292. {
  1293. boost::sort(townsNotReachable, compareReinforcements);
  1294. //TODO pick the truly best
  1295. const CGTownInstance *t = townsNotReachable.back();
  1296. BNLOG("%s can't reach any town, we'll try to make our way to %s at %s", h->name % t->name % t->visitablePos());
  1297. int3 pos1 = h->pos;
  1298. striveToGoal(CGoal(CLEAR_WAY_TO).settile(t->visitablePos()).sethero(h));
  1299. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  1300. {
  1301. if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size())
  1302. recruitHero(t);
  1303. }
  1304. break;
  1305. }
  1306. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  1307. {
  1308. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1309. erase_if(towns, [](const CGTownInstance *t) -> bool
  1310. {
  1311. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1312. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1313. return true;
  1314. return false;
  1315. });
  1316. boost::sort(towns, compareArmyStrength);
  1317. if(towns.size())
  1318. recruitHero(towns.back());
  1319. break;
  1320. }
  1321. else
  1322. {
  1323. PNLOG("Nowhere more to go...\n");
  1324. break;
  1325. }
  1326. }
  1327. const ObjectIdRef&dest = dests.front();
  1328. if(!goVisitObj(dest, h))
  1329. {
  1330. if(!dest)
  1331. {
  1332. BNLOG("Visit attempt made the object (id=%d) gone...", dest.id);
  1333. }
  1334. else
  1335. {
  1336. BNLOG("Hero %s apparently used all MPs (%d left)\n", h->name % h->movement);
  1337. reserveObject(h, dest); //reserve that object - we predict it will be reached soon
  1338. //removed - do not forget abstract goal so easily
  1339. //setGoal(h, CGoal(VISIT_TILE).sethero(h).settile(dest->visitablePos()));
  1340. }
  1341. break;
  1342. }
  1343. if(h->visitedTown)
  1344. {
  1345. townVisitsThisWeek[h].push_back(h->visitedTown);
  1346. buildArmyIn(h->visitedTown);
  1347. break;
  1348. }
  1349. }
  1350. }
  1351. void VCAI::setGoal(HeroPtr h, const CGoal goal)
  1352. { //TODO: check for presence?
  1353. if (goal.goalType == EGoals::INVALID)
  1354. remove_if_present(lockedHeroes, h);
  1355. else
  1356. lockedHeroes[h] = CGoal(goal).setisElementar(false); //always evaluate goals before realizing
  1357. }
  1358. void VCAI::setGoal(HeroPtr h, EGoals goalType)
  1359. {
  1360. if (goalType == EGoals::INVALID)
  1361. remove_if_present(lockedHeroes, h);
  1362. else
  1363. lockedHeroes[h] = CGoal(goalType).setisElementar(false); //always evaluate goals before realizing;
  1364. }
  1365. void VCAI::completeGoal (const CGoal goal)
  1366. {
  1367. if (const CGHeroInstance * h = goal.hero.get(true))
  1368. {
  1369. auto it = lockedHeroes.find(h);
  1370. if (it != lockedHeroes.end())
  1371. if (it->second.goalType == goal.goalType)
  1372. lockedHeroes.erase(it); //goal fulfilled, free hero
  1373. }
  1374. }
  1375. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1376. {
  1377. NET_EVENT_HANDLER;
  1378. assert(playerID > GameConstants::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1379. status.setBattle(ONGOING_BATTLE);
  1380. const CGObjectInstance *presumedEnemy = backOrNull(cb->getVisitableObjs(tile)); //may be NULL in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
  1381. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->hoverName : "unknown enemy") % tile);
  1382. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1383. }
  1384. void VCAI::battleEnd(const BattleResult *br)
  1385. {
  1386. NET_EVENT_HANDLER;
  1387. assert(status.getBattle() == ONGOING_BATTLE);
  1388. status.setBattle(ENDING_BATTLE);
  1389. bool won = br->winner == myCb->battleGetMySide();
  1390. BNLOG("Player %d: I %s the %s!", playerID % (won ? "won" : "lost") % battlename);
  1391. battlename.clear();
  1392. CAdventureAI::battleEnd(br);
  1393. }
  1394. void VCAI::waitTillFree()
  1395. {
  1396. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1397. status.waitTillFree();
  1398. }
  1399. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1400. {
  1401. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1402. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1403. (obj->ID == Obj::MONSTER))
  1404. return;
  1405. alreadyVisited.push_back(obj);
  1406. }
  1407. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj)
  1408. {
  1409. reservedObjs.push_back(obj);
  1410. reservedHeroesMap[h].push_back(obj);
  1411. }
  1412. void VCAI::validateVisitableObjs()
  1413. {
  1414. std::vector<const CGObjectInstance *> hlp;
  1415. retreiveVisitableObjs(hlp, true);
  1416. start:
  1417. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1418. if(!vstd::contains(hlp, obj))
  1419. {
  1420. tlog1 << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << " shouldn't be on list!\n";
  1421. remove_if_present(visitableObjs, obj);
  1422. goto start;
  1423. }
  1424. }
  1425. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1426. {
  1427. foreach_tile_pos([&](const int3 &pos)
  1428. {
  1429. BOOST_FOREACH(const CGObjectInstance *obj, myCb->getVisitableObjs(pos, false))
  1430. {
  1431. if(includeOwned || obj->tempOwner != playerID)
  1432. out.push_back(obj);
  1433. }
  1434. });
  1435. }
  1436. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1437. {
  1438. std::vector<const CGObjectInstance *> ret;
  1439. retreiveVisitableObjs(ret, true);
  1440. erase_if(ret, [](const CGObjectInstance *obj)
  1441. {
  1442. return obj->tempOwner != ai->playerID;
  1443. });
  1444. return ret;
  1445. }
  1446. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1447. {
  1448. visitableObjs.push_back(obj);
  1449. helperObjInfo[obj] = ObjInfo(obj);
  1450. }
  1451. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1452. {
  1453. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  1454. {
  1455. if(obj->ID == 5 && obj->subID == aid)
  1456. return obj;
  1457. }
  1458. return NULL;
  1459. //TODO what if more than one artifact is available? return them all or some slection criteria
  1460. }
  1461. bool VCAI::isAccessible(const int3 &pos)
  1462. {
  1463. //TODO precalculate for speed
  1464. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1465. {
  1466. if(isAccessibleForHero(pos, h))
  1467. return true;
  1468. }
  1469. return false;
  1470. }
  1471. HeroPtr VCAI::getHeroWithGrail() const
  1472. {
  1473. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1474. if(h->hasArt(2)) //grail
  1475. return h;
  1476. return NULL;
  1477. }
  1478. const CGObjectInstance * VCAI::getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate)
  1479. {
  1480. //TODO smarter definition of unvisited
  1481. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1482. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1483. return obj;
  1484. return NULL;
  1485. }
  1486. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies /*= false*/) const
  1487. {
  1488. cb->setSelection(*h);
  1489. if (!includeAllies)
  1490. { //don't visit tile occupied by allied hero
  1491. BOOST_FOREACH (auto obj, cb->getVisitableObjs(pos))
  1492. {
  1493. if (obj->ID == Obj::HERO && obj->tempOwner == h->tempOwner && obj != h)
  1494. return false;
  1495. }
  1496. }
  1497. return cb->getPathInfo(pos)->reachable();
  1498. }
  1499. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1500. {
  1501. visitedObject = NULL;
  1502. int3 startHpos = h->visitablePos();
  1503. bool ret = false;
  1504. if(startHpos == dst)
  1505. {
  1506. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1507. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1508. waitTillFree(); //movement may cause battle or blocking dialog
  1509. ret = true;
  1510. }
  1511. else
  1512. {
  1513. CGPath path;
  1514. cb->getPath2(dst, path);
  1515. if(path.nodes.empty())
  1516. {
  1517. tlog1 << "Hero " << h->name << " cannot reach " << dst << std::endl;
  1518. //setGoal(h, INVALID);
  1519. completeGoal (CGoal(VISIT_TILE).sethero(h));
  1520. cb->recalculatePaths();
  1521. throw std::runtime_error("Wrong move order!");
  1522. }
  1523. int i=path.nodes.size()-1;
  1524. for(; i>0; i--)
  1525. {
  1526. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1527. if(path.nodes[i-1].turns)
  1528. {
  1529. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1530. break;
  1531. }
  1532. int3 endpos = path.nodes[i-1].coord;
  1533. if(endpos == h->visitablePos())
  1534. //if (endpos == h->pos)
  1535. continue;
  1536. // if(i > 1)
  1537. // {
  1538. // int3 afterEndPos = path.nodes[i-2].coord;
  1539. // if(afterEndPos.z != endpos.z)
  1540. //
  1541. // }
  1542. //tlog0 << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos << std::endl;
  1543. cb->moveHero(*h, CGHeroInstance::convertPosition(endpos, true));
  1544. waitTillFree(); //movement may cause battle or blocking dialog
  1545. boost::this_thread::interruption_point();
  1546. if(!h) //we lost hero - remove all tasks assigned to him/her
  1547. {
  1548. lostHero(h);
  1549. //we need to throw, otherwise hero will be assigned to sth again
  1550. throw std::runtime_error("Hero was lost!");
  1551. break;
  1552. }
  1553. }
  1554. ret = !i;
  1555. }
  1556. if (visitedObject) //we step into something interesting
  1557. {
  1558. performObjectInteraction (visitedObject, h);
  1559. //BNLOG("Hero %s moved from %s to %s at %s", h->name % startHpos % visitedObject->hoverName % h->visitablePos());
  1560. //throw goalFulfilledException (CGoal(GET_OBJ).setobjid(visitedObject->id));
  1561. }
  1562. if(h) //we could have lost hero after last move
  1563. {
  1564. cb->recalculatePaths();
  1565. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1566. {
  1567. throw cannotFulfillGoalException("Invalid path found!");
  1568. }
  1569. }
  1570. BNLOG("Hero %s moved from %s to %s", h->name % startHpos % h->visitablePos());
  1571. return ret;
  1572. }
  1573. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  1574. { //TODO: do not explore dead-end boundaries
  1575. int ret = 0;
  1576. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  1577. {
  1578. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  1579. {
  1580. int3 npos = int3(x,y,pos.z);
  1581. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  1582. {
  1583. if (!boundaryBetweenTwoPoints (pos, npos))
  1584. ret++;
  1585. }
  1586. }
  1587. }
  1588. return ret;
  1589. }
  1590. bool boundaryBetweenTwoPoints (int3 pos1, int3 pos2) //determines if two points are separated by known barrier
  1591. {
  1592. int xMin = std::min (pos1.x, pos2.x);
  1593. int xMax = std::max (pos1.x, pos2.x);
  1594. int yMin = std::min (pos1.y, pos2.y);
  1595. int yMax = std::max (pos1.y, pos2.y);
  1596. for (int x = xMin; x <= xMax; ++x)
  1597. {
  1598. for (int y = yMin; y <= yMax; ++y)
  1599. {
  1600. int3 tile = int3(x, y, pos1.z); //use only on same level, ofc
  1601. if (abs(pos1.dist2d(tile) - pos2.dist2d(tile)) < 1.5)
  1602. {
  1603. if (!(cb->isVisible(tile) && cb->getTile(tile)->blocked)) //if there's invisible or unblocked tile inbetween, it's good
  1604. return false;
  1605. }
  1606. }
  1607. }
  1608. return true; //if all are visible and blocked, we're at dead end
  1609. }
  1610. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  1611. {
  1612. return howManyTilesWillBeDiscovered(pos + dir, radious);
  1613. }
  1614. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  1615. {
  1616. BOOST_FOREACH(const int3 &tile, tiles)
  1617. {
  1618. foreach_neighbour(tile, [&](int3 neighbour)
  1619. {
  1620. if(cb->isVisible(neighbour))
  1621. out.push_back(neighbour);
  1622. });
  1623. }
  1624. }
  1625. void VCAI::tryRealize(CGoal g)
  1626. {
  1627. BNLOG("Attempting realizing goal with code %s", g.name());
  1628. switch(g.goalType)
  1629. {
  1630. case EXPLORE:
  1631. {
  1632. throw cannotFulfillGoalException("EXPLORE is not a elementar goal!");
  1633. }
  1634. break;
  1635. case RECRUIT_HERO:
  1636. {
  1637. if(const CGTownInstance *t = findTownWithTavern())
  1638. {
  1639. recruitHero(t, true);
  1640. //TODO jezeli miasto jest zablokowane, sprobowac oczyscic wejscie
  1641. }
  1642. //TODO karkolomna alternatywa - tawerna na mapie przygod lub wiezienie (nie wiem, czy warto?)
  1643. }
  1644. break;
  1645. case VISIT_TILE:
  1646. {
  1647. //cb->recalculatePaths();
  1648. if(!g.hero->movement)
  1649. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1650. //if(!g.isBlockedBorderGate(g.tile))
  1651. //{
  1652. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1653. {
  1654. throw goalFulfilledException (g);
  1655. }
  1656. //}
  1657. //else
  1658. // throw cannotFulfillGoalException("There's a blocked gate!, we should never be here"); //CLEAR_WAY_TO should get keymaster tent
  1659. }
  1660. break;
  1661. case VISIT_HERO:
  1662. {
  1663. if(!g.hero->movement)
  1664. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1665. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1666. {
  1667. throw goalFulfilledException (g);
  1668. }
  1669. }
  1670. break;
  1671. case BUILD_STRUCTURE:
  1672. {
  1673. const CGTownInstance *t = g.town;
  1674. if(!t && g.hero)
  1675. t = g.hero->visitedTown;
  1676. if(!t)
  1677. {
  1678. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1679. {
  1680. switch(cb->canBuildStructure(t, BuildingID(g.bid)))
  1681. {
  1682. case EBuildingState::ALLOWED:
  1683. cb->buildBuilding(t, BuildingID(g.bid));
  1684. return;
  1685. default:
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. else if(cb->canBuildStructure(t, BuildingID(g.bid)) == EBuildingState::ALLOWED)
  1691. {
  1692. cb->buildBuilding(t, BuildingID(g.bid));
  1693. return;
  1694. }
  1695. throw cannotFulfillGoalException("Cannot build a given structure!");
  1696. }
  1697. break;
  1698. case DIG_AT_TILE:
  1699. {
  1700. assert(g.hero->visitablePos() == g.tile);
  1701. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1702. {
  1703. cb->dig(g.hero.get());
  1704. setGoal(g.hero, INVALID); // finished digging
  1705. }
  1706. else
  1707. {
  1708. ai->lockedHeroes[g.hero] = g; //hero who tries to dig shouldn't do anything else
  1709. throw cannotFulfillGoalException("A hero can't dig!\n");
  1710. }
  1711. }
  1712. break;
  1713. case COLLECT_RES: //TODO: use piles and mines?
  1714. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1715. throw cannotFulfillGoalException("Goal is already fulfilled!");
  1716. if(const CGObjectInstance *obj = cb->getObj(g.objid, false))
  1717. {
  1718. if(const IMarket *m = IMarket::castFrom(obj, false))
  1719. {
  1720. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1721. {
  1722. if(i == g.resID) continue;
  1723. int toGive, toGet;
  1724. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1725. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1726. //TODO trade only as much as needed
  1727. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1728. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1729. return;
  1730. }
  1731. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1732. }
  1733. else
  1734. {
  1735. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1736. }
  1737. }
  1738. else
  1739. {
  1740. saving[g.resID] = 1;
  1741. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1742. }
  1743. case CONQUER:
  1744. case GATHER_ARMY:
  1745. case BOOST_HERO:
  1746. // TODO: conquer??
  1747. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1748. case BUILD:
  1749. performTypicalActions(); //TODO: separate build and wander
  1750. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1751. case INVALID:
  1752. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1753. default:
  1754. throw cannotFulfillGoalException("Unknown type of goal !");
  1755. }
  1756. }
  1757. const CGTownInstance * VCAI::findTownWithTavern() const
  1758. {
  1759. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1760. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1761. return t;
  1762. return NULL;
  1763. }
  1764. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1765. {
  1766. std::vector<HeroPtr> ret;
  1767. boost::copy(cb->getHeroesInfo(), std::back_inserter(ret));
  1768. BOOST_FOREACH(auto h, lockedHeroes)
  1769. {
  1770. //if (!h.second.invalid()) //we can use heroes without valid goal
  1771. if (h.second.goalType == DIG_AT_TILE || !h.first->movement) //experiment: use all heroes that have movement left, TODO: unlock heroes that couldn't realize their goals
  1772. remove_if_present(ret, h.first);
  1773. }
  1774. return ret;
  1775. }
  1776. HeroPtr VCAI::primaryHero() const
  1777. {
  1778. auto hs = cb->getHeroesInfo();
  1779. boost::sort(hs, compareHeroStrength);
  1780. if(hs.empty())
  1781. return NULL;
  1782. return hs.back();
  1783. }
  1784. void VCAI::endTurn()
  1785. {
  1786. tlog4 << "Player " << playerID << " ends turn\n";
  1787. if(!status.haveTurn())
  1788. {
  1789. tlog1 << "Not having turn at the end of turn???\n";
  1790. }
  1791. do
  1792. {
  1793. cb->endTurn();
  1794. } 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
  1795. tlog4 << "Player " << playerID << " ended turn\n";
  1796. }
  1797. bool VCAI::fulfillsGoal (CGoal &goal, CGoal &mainGoal)
  1798. {
  1799. if (mainGoal.goalType == GET_OBJ && goal.goalType == VISIT_TILE) //deduce that GET_OBJ was completed by visiting object's tile
  1800. { //TODO: more universal mechanism
  1801. if (cb->getObj(mainGoal.objid)->visitablePos() == goal.tile)
  1802. return true;
  1803. }
  1804. return false;
  1805. }
  1806. bool VCAI::fulfillsGoal (CGoal &goal, const CGoal &mainGoal)
  1807. {
  1808. if (mainGoal.goalType == GET_OBJ && goal.goalType == VISIT_TILE) //deduce that GET_OBJ was completed by visiting object's tile
  1809. { //TODO: more universal mechanism
  1810. if (cb->getObj(mainGoal.objid)->visitablePos() == goal.tile)
  1811. return true;
  1812. }
  1813. return false;
  1814. }
  1815. void VCAI::striveToGoal(const CGoal &ultimateGoal)
  1816. {
  1817. if (ultimateGoal.invalid())
  1818. return;
  1819. CGoal abstractGoal;
  1820. while(1)
  1821. {
  1822. CGoal goal = ultimateGoal;
  1823. BNLOG("Striving to goal of type %s", ultimateGoal.name());
  1824. int maxGoals = 100; //preventing deadlock for mutually dependent goals
  1825. while(!goal.isElementar && !goal.isAbstract && maxGoals)
  1826. {
  1827. INDENT;
  1828. BNLOG("Considering goal %s", goal.name());
  1829. try
  1830. {
  1831. boost::this_thread::interruption_point();
  1832. goal = goal.whatToDoToAchieve();
  1833. --maxGoals;
  1834. }
  1835. catch(std::exception &e)
  1836. {
  1837. BNLOG("Goal %s decomposition failed: %s", goal.name() % e.what());
  1838. //setGoal (goal.hero, INVALID); //test: if we don't know how to realize goal, we should abandon it for now
  1839. return;
  1840. }
  1841. }
  1842. try
  1843. {
  1844. boost::this_thread::interruption_point();
  1845. if (goal.hero) //lock this hero to fulfill ultimate goal
  1846. {
  1847. if (maxGoals)
  1848. {
  1849. setGoal(goal.hero, goal);
  1850. }
  1851. else
  1852. {
  1853. setGoal(goal.hero, INVALID); // we seemingly don't know what to do with hero
  1854. }
  1855. }
  1856. if (goal.isAbstract)
  1857. {
  1858. abstractGoal = goal; //allow only one abstract goal per call
  1859. BNLOG("Choosing abstract goal %s", goal.name());
  1860. break;
  1861. }
  1862. else
  1863. tryRealize(goal);
  1864. boost::this_thread::interruption_point();
  1865. }
  1866. catch(boost::thread_interrupted &e)
  1867. {
  1868. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1869. throw; //rethrow, we want to truly end this thread
  1870. }
  1871. catch(goalFulfilledException &e)
  1872. {
  1873. completeGoal (goal);
  1874. if (fulfillsGoal (goal, ultimateGoal) || maxGoals > 98) //completed goal was main goal //TODO: find better condition
  1875. return;
  1876. }
  1877. catch(std::exception &e)
  1878. {
  1879. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goal.name() % ultimateGoal.name());
  1880. BNLOG("The error message was: %s", e.what());
  1881. break;
  1882. }
  1883. }
  1884. //TODO: save abstract goals not related to hero
  1885. if (!abstractGoal.invalid()) //try to realize our one goal
  1886. {
  1887. while (1)
  1888. {
  1889. CGoal goal = CGoal(abstractGoal).setisAbstract(false);
  1890. int maxGoals = 50;
  1891. while (!goal.isElementar && maxGoals) //find elementar goal and fulfill it
  1892. {
  1893. try
  1894. {
  1895. boost::this_thread::interruption_point();
  1896. goal = goal.whatToDoToAchieve();
  1897. --maxGoals;
  1898. }
  1899. catch(std::exception &e)
  1900. {
  1901. BNLOG("Goal %s decomposition failed: %s", goal.name() % e.what());
  1902. //setGoal (goal.hero, INVALID);
  1903. return;
  1904. }
  1905. }
  1906. try
  1907. {
  1908. boost::this_thread::interruption_point();
  1909. tryRealize(goal);
  1910. boost::this_thread::interruption_point();
  1911. }
  1912. catch(boost::thread_interrupted &e)
  1913. {
  1914. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1915. throw; //rethrow, we want to truly end this thread
  1916. }
  1917. catch(goalFulfilledException &e)
  1918. {
  1919. completeGoal (goal); //FIXME: deduce that we have realized GET_OBJ goal
  1920. if (fulfillsGoal (goal, abstractGoal) || maxGoals > 98) //completed goal was main goal
  1921. return;
  1922. }
  1923. catch(std::exception &e)
  1924. {
  1925. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goal.name() % ultimateGoal.name());
  1926. BNLOG("The error message was: %s", e.what());
  1927. break;
  1928. }
  1929. }
  1930. }
  1931. }
  1932. void VCAI::striveToQuest (const QuestInfo &q)
  1933. {
  1934. if (q.quest->missionType && q.quest->progress != CQuest::COMPLETE) //FIXME: quests are never synchronized. Pointer handling needed
  1935. {
  1936. MetaString ms;
  1937. q.quest->getRolloverText(ms, false);
  1938. BNLOG ("Trying to realize quest: %s", ms.toString());
  1939. auto heroes = cb->getHeroesInfo();
  1940. switch (q.quest->missionType)
  1941. {
  1942. case CQuest::MISSION_ART:
  1943. {
  1944. BOOST_FOREACH (auto hero, heroes) //TODO: remove duplicated code?
  1945. {
  1946. if (q.quest->checkQuest(hero))
  1947. {
  1948. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1949. return;
  1950. }
  1951. }
  1952. BOOST_FOREACH (auto art, q.quest->m5arts)
  1953. {
  1954. striveToGoal (CGoal(GET_ART_TYPE).setaid(art)); //TODO: transport?
  1955. }
  1956. break;
  1957. }
  1958. case CQuest::MISSION_HERO:
  1959. {
  1960. //striveToGoal (CGoal(RECRUIT_HERO));
  1961. BOOST_FOREACH (auto hero, heroes)
  1962. {
  1963. if (q.quest->checkQuest(hero))
  1964. {
  1965. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1966. return;
  1967. }
  1968. }
  1969. striveToGoal (CGoal(FIND_OBJ).setobjid(Obj::PRISON)); //rule of a thumb - quest heroes usually are locked in prisons
  1970. //BNLOG ("Don't know how to recruit hero with id %d\n", q.quest->m13489val);
  1971. break;
  1972. }
  1973. case CQuest::MISSION_ARMY:
  1974. {
  1975. BOOST_FOREACH (auto hero, heroes)
  1976. {
  1977. if (q.quest->checkQuest(hero)) //veyr bad info - stacks can be split between multiple heroes :(
  1978. {
  1979. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1980. return;
  1981. }
  1982. }
  1983. BOOST_FOREACH (auto creature, q.quest->m6creatures)
  1984. {
  1985. striveToGoal (CGoal(GATHER_TROOPS).setobjid(creature.type->idNumber).setvalue(creature.count));
  1986. }
  1987. //TODO: exchange armies... oh my
  1988. //BNLOG ("Don't know how to recruit %d of %s\n", (int)(creature.count) % creature.type->namePl);
  1989. break;
  1990. }
  1991. case CQuest::MISSION_RESOURCES:
  1992. {
  1993. if (heroes.size())
  1994. {
  1995. if (q.quest->checkQuest(heroes.front())) //it doesn't matter which hero it is
  1996. {
  1997. striveToGoal (CGoal(VISIT_TILE).settile(q.tile));
  1998. }
  1999. else
  2000. {
  2001. for (int i = 0; i < q.quest->m7resources.size(); ++i)
  2002. {
  2003. if (q.quest->m7resources[i])
  2004. striveToGoal (CGoal(COLLECT_RES).setresID(i).setvalue(q.quest->m7resources[i]));
  2005. }
  2006. }
  2007. }
  2008. else
  2009. striveToGoal (CGoal(RECRUIT_HERO)); //FIXME: checkQuest requires any hero belonging to player :(
  2010. break;
  2011. }
  2012. case CQuest::MISSION_KILL_HERO:
  2013. case CQuest::MISSION_KILL_CREATURE:
  2014. {
  2015. auto obj = cb->getObjByQuestIdentifier(q.quest->m13489val);
  2016. if (obj)
  2017. striveToGoal (CGoal(GET_OBJ).setobjid(obj->id));
  2018. else
  2019. striveToGoal (CGoal(VISIT_TILE).settile(q.tile)); //visit seer hut
  2020. break;
  2021. }
  2022. case CQuest::MISSION_PRIMARY_STAT:
  2023. {
  2024. auto heroes = cb->getHeroesInfo();
  2025. BOOST_FOREACH (auto hero, heroes)
  2026. {
  2027. if (q.quest->checkQuest(hero))
  2028. {
  2029. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  2030. return;
  2031. }
  2032. }
  2033. for (int i = 0; i < q.quest->m2stats.size(); ++i)
  2034. {
  2035. BNLOG ("Don't know how to increase primary stat %d\n", i);
  2036. }
  2037. break;
  2038. }
  2039. case CQuest::MISSION_LEVEL:
  2040. {
  2041. auto heroes = cb->getHeroesInfo();
  2042. BOOST_FOREACH (auto hero, heroes)
  2043. {
  2044. if (q.quest->checkQuest(hero))
  2045. {
  2046. striveToGoal (CGoal(VISIT_TILE).settile(q.tile).sethero(hero)); //TODO: causes infinite loop :/
  2047. return;
  2048. }
  2049. }
  2050. BNLOG ("Don't know how to reach hero level %d\n", q.quest->m13489val);
  2051. break;
  2052. }
  2053. case CQuest::MISSION_PLAYER:
  2054. {
  2055. if (playerID != q.quest->m13489val)
  2056. BNLOG ("Can't be player of color %d\n", q.quest->m13489val);
  2057. break;
  2058. }
  2059. case CQuest::MISSION_KEYMASTER:
  2060. {
  2061. striveToGoal (CGoal(FIND_OBJ).setobjid(Obj::KEYMASTER).setresID(q.obj->subID));
  2062. break;
  2063. }
  2064. }
  2065. }
  2066. }
  2067. void VCAI::performTypicalActions()
  2068. {
  2069. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2070. {
  2071. BNLOG("Looking into %s", t->name);
  2072. buildStructure(t);
  2073. buildArmyIn(t);
  2074. if(!ai->primaryHero() ||
  2075. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  2076. {
  2077. recruitHero(t);
  2078. buildArmyIn(t);
  2079. }
  2080. }
  2081. BOOST_FOREACH(auto h, getUnblockedHeroes())
  2082. {
  2083. BNLOG("Looking into %s, MP=%d", h->name.c_str() % h->movement);
  2084. INDENT;
  2085. makePossibleUpgrades(*h);
  2086. cb->setSelection(*h);
  2087. try
  2088. {
  2089. wander(h);
  2090. }
  2091. catch(std::exception &e)
  2092. {
  2093. BNLOG("Cannot use this hero anymore, received exception: %s", e.what());
  2094. continue;
  2095. }
  2096. }
  2097. }
  2098. void VCAI::buildArmyIn(const CGTownInstance * t)
  2099. {
  2100. makePossibleUpgrades(t->visitingHero);
  2101. makePossibleUpgrades(t);
  2102. recruitCreatures(t);
  2103. moveCreaturesToHero(t);
  2104. }
  2105. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  2106. {
  2107. TimeCheck tc("looking for best exploration neighbour");
  2108. std::map<int3, int> dstToRevealedTiles;
  2109. BOOST_FOREACH(crint3 dir, dirs)
  2110. if(cb->isInTheMap(hpos+dir))
  2111. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  2112. auto best = dstToRevealedTiles.begin();
  2113. best->second *= cb->getPathInfo(best->first)->reachable();
  2114. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  2115. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  2116. {
  2117. const CGPathNode *pn = cb->getPathInfo(i->first);
  2118. //const TerrainTile *t = cb->getTile(i->first);
  2119. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  2120. best = i;
  2121. }
  2122. if(best->second)
  2123. return best->first;
  2124. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2125. }
  2126. int3 VCAI::explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles)
  2127. {
  2128. TimeCheck tc("looking for new exploration point");
  2129. PNLOG("Looking for an another place for exploration...");
  2130. tiles.resize(radius);
  2131. foreach_tile_pos([&](const int3 &pos)
  2132. {
  2133. if(!cb->isVisible(pos))
  2134. tiles[0].push_back(pos);
  2135. });
  2136. for (int i = 1; i < radius; i++)
  2137. {
  2138. getVisibleNeighbours(tiles[i-1], tiles[i]);
  2139. removeDuplicates(tiles[i]);
  2140. BOOST_FOREACH(const int3 &tile, tiles[i])
  2141. {
  2142. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius) && !isBlockedBorderGate(tile))
  2143. {
  2144. return tile;
  2145. }
  2146. }
  2147. }
  2148. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  2149. }
  2150. TResources VCAI::estimateIncome() const
  2151. {
  2152. TResources ret;
  2153. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2154. {
  2155. ret[Res::GOLD] += t->dailyIncome();
  2156. //TODO duplikuje newturn
  2157. if(t->hasBuilt(BuildingID::RESOURCE_SILO)) //there is resource silo
  2158. {
  2159. if(t->town->primaryRes == 127) //we'll give wood and ore
  2160. {
  2161. ret[Res::WOOD] ++;
  2162. ret[Res::ORE] ++;
  2163. }
  2164. else
  2165. {
  2166. ret[t->town->primaryRes] ++;
  2167. }
  2168. }
  2169. }
  2170. BOOST_FOREACH(const CGObjectInstance *obj, getFlaggedObjects())
  2171. {
  2172. if(obj->ID == Obj::MINE)
  2173. {
  2174. switch(obj->subID)
  2175. {
  2176. case Res::WOOD:
  2177. case Res::ORE:
  2178. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  2179. break;
  2180. case Res::GOLD:
  2181. case 7: //abandoned mine -> also gold
  2182. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  2183. break;
  2184. default:
  2185. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  2186. break;
  2187. }
  2188. }
  2189. }
  2190. return ret;
  2191. }
  2192. bool VCAI::containsSavedRes(const TResources &cost) const
  2193. {
  2194. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  2195. {
  2196. if(saving[i] && cost[i])
  2197. return true;
  2198. }
  2199. return false;
  2200. }
  2201. void VCAI::checkHeroArmy (HeroPtr h)
  2202. {
  2203. auto it = lockedHeroes.find(h);
  2204. if (it != lockedHeroes.end())
  2205. {
  2206. if (it->second.goalType == GATHER_ARMY && it->second.value <= h->getArmyStrength())
  2207. completeGoal(CGoal (GATHER_ARMY).sethero(h));
  2208. }
  2209. }
  2210. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2211. {
  2212. BNLOG("Trying to recruit a hero in %s at %s", t->name % t->visitablePos())
  2213. if(auto availableHero = frontOrNull(cb->getAvailableHeroes(t)))
  2214. cb->recruitHero(t, availableHero);
  2215. else if(throwing)
  2216. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2217. }
  2218. void VCAI::finish()
  2219. {
  2220. if(makingTurn)
  2221. makingTurn->interrupt();
  2222. }
  2223. void VCAI::requestActionASAP(boost::function<void()> whatToDo)
  2224. {
  2225. // static boost::mutex m;
  2226. // boost::unique_lock<boost::mutex> mylock(m);
  2227. boost::barrier b(2);
  2228. boost::thread newThread([&b,this,whatToDo]()
  2229. {
  2230. setThreadName("VCAI::requestActionASAP::helper");
  2231. SET_GLOBAL_STATE(this);
  2232. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  2233. b.wait();
  2234. whatToDo();
  2235. });
  2236. b.wait();
  2237. }
  2238. void VCAI::lostHero(HeroPtr h)
  2239. {
  2240. BNLOG("I lost my hero %s. It's best to forget and move on.\n", h.name);
  2241. remove_if_present(lockedHeroes, h);
  2242. BOOST_FOREACH(auto obj, reservedHeroesMap[h])
  2243. {
  2244. remove_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2245. }
  2246. remove_if_present(reservedHeroesMap, h);
  2247. }
  2248. void VCAI::answerQuery(int queryID, int selection)
  2249. {
  2250. BNLOG("I'll answer the query %d giving the choice %d", queryID % selection);
  2251. if(queryID != -1)
  2252. {
  2253. cb->selectionMade(selection, queryID);
  2254. }
  2255. else
  2256. {
  2257. BNLOG("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2258. //do nothing
  2259. }
  2260. }
  2261. void VCAI::requestSent(const CPackForServer *pack, int requestID)
  2262. {
  2263. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2264. if(auto reply = dynamic_cast<const QueryReply*>(pack))
  2265. {
  2266. status.attemptedAnsweringQuery(reply->qid, requestID);
  2267. }
  2268. }
  2269. std::string VCAI::getBattleAIName() const
  2270. {
  2271. if(settings["server"]["neutralAI"].getType() == JsonNode::DATA_STRING)
  2272. return settings["server"]["neutralAI"].String();
  2273. else
  2274. return "StupidAI";
  2275. }
  2276. AIStatus::AIStatus()
  2277. {
  2278. battle = NO_BATTLE;
  2279. havingTurn = false;
  2280. }
  2281. AIStatus::~AIStatus()
  2282. {
  2283. }
  2284. void AIStatus::setBattle(BattleState BS)
  2285. {
  2286. boost::unique_lock<boost::mutex> lock(mx);
  2287. battle = BS;
  2288. cv.notify_all();
  2289. }
  2290. BattleState AIStatus::getBattle()
  2291. {
  2292. boost::unique_lock<boost::mutex> lock(mx);
  2293. return battle;
  2294. }
  2295. void AIStatus::addQuery(int ID, std::string description)
  2296. {
  2297. boost::unique_lock<boost::mutex> lock(mx);
  2298. if(ID == -1)
  2299. {
  2300. BNLOG("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID % description);
  2301. return;
  2302. }
  2303. assert(!vstd::contains(remainingQueries, ID));
  2304. assert(ID >= 0);
  2305. remainingQueries[ID] = description;
  2306. cv.notify_all();
  2307. BNLOG("Adding query %d - %s. Total queries count: %d", ID % description % remainingQueries.size());
  2308. }
  2309. void AIStatus::removeQuery(int ID)
  2310. {
  2311. boost::unique_lock<boost::mutex> lock(mx);
  2312. assert(vstd::contains(remainingQueries, ID));
  2313. std::string description = remainingQueries[ID];
  2314. remainingQueries.erase(ID);
  2315. cv.notify_all();
  2316. BNLOG("Removing query %d - %s. Total queries count: %d", ID % description % remainingQueries.size());
  2317. }
  2318. int AIStatus::getQueriesCount()
  2319. {
  2320. boost::unique_lock<boost::mutex> lock(mx);
  2321. return remainingQueries.size();
  2322. }
  2323. void AIStatus::startedTurn()
  2324. {
  2325. boost::unique_lock<boost::mutex> lock(mx);
  2326. havingTurn = true;
  2327. cv.notify_all();
  2328. }
  2329. void AIStatus::madeTurn()
  2330. {
  2331. boost::unique_lock<boost::mutex> lock(mx);
  2332. havingTurn = false;
  2333. cv.notify_all();
  2334. }
  2335. void AIStatus::waitTillFree()
  2336. {
  2337. boost::unique_lock<boost::mutex> lock(mx);
  2338. while(battle != NO_BATTLE || remainingQueries.size())
  2339. cv.wait(lock);
  2340. }
  2341. bool AIStatus::haveTurn()
  2342. {
  2343. boost::unique_lock<boost::mutex> lock(mx);
  2344. return havingTurn;
  2345. }
  2346. void AIStatus::attemptedAnsweringQuery(int queryID, int answerRequestID)
  2347. {
  2348. boost::unique_lock<boost::mutex> lock(mx);
  2349. assert(vstd::contains(remainingQueries, queryID));
  2350. std::string description = remainingQueries[queryID];
  2351. BNLOG("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID % description % answerRequestID);
  2352. requestToQueryID[answerRequestID] = queryID;
  2353. }
  2354. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2355. {
  2356. assert(vstd::contains(requestToQueryID, answerRequestID));
  2357. int query = requestToQueryID[answerRequestID];
  2358. assert(vstd::contains(remainingQueries, query));
  2359. requestToQueryID.erase(answerRequestID);
  2360. if(result)
  2361. {
  2362. removeQuery(query);
  2363. }
  2364. else
  2365. {
  2366. tlog1 << "Something went really wrong, failed to answer query " << query << ": " << remainingQueries[query];
  2367. //TODO safely retry
  2368. }
  2369. }
  2370. int3 whereToExplore(HeroPtr h)
  2371. {
  2372. //TODO it's stupid and ineffective, write sth better
  2373. cb->setSelection(*h);
  2374. int radius = h->getSightRadious();
  2375. int3 hpos = h->visitablePos();
  2376. //look for nearby objs -> visit them if they're close enouh
  2377. const int DIST_LIMIT = 3;
  2378. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  2379. BOOST_FOREACH(const CGObjectInstance *obj, ai->getPossibleDestinations(h))
  2380. {
  2381. int3 op = obj->visitablePos();
  2382. CGPath p;
  2383. cb->getPath2(op, p);
  2384. if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  2385. nearbyVisitableObjs.push_back(obj);
  2386. }
  2387. boost::sort(nearbyVisitableObjs, isCloser);
  2388. if(nearbyVisitableObjs.size())
  2389. return nearbyVisitableObjs.back()->visitablePos();
  2390. try
  2391. {
  2392. return ai->explorationBestNeighbour(hpos, radius, h);
  2393. }
  2394. catch(cannotFulfillGoalException &e)
  2395. {
  2396. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow]
  2397. try
  2398. {
  2399. return ai->explorationNewPoint(radius, h, tiles);
  2400. }
  2401. catch(cannotFulfillGoalException &e)
  2402. {
  2403. std::map<int, std::vector<int3> > profits;
  2404. {
  2405. TimeCheck tc("Evaluating exploration possibilities");
  2406. tiles[0].clear(); //we can't reach FoW anyway
  2407. BOOST_FOREACH(auto &vt, tiles)
  2408. BOOST_FOREACH(auto &tile, vt)
  2409. profits[howManyTilesWillBeDiscovered(tile, radius)].push_back(tile);
  2410. }
  2411. if(profits.empty())
  2412. return int3 (-1,-1,-1);
  2413. auto bestDest = profits.end();
  2414. bestDest--;
  2415. return bestDest->second.front(); //TODO which is the real best tile?
  2416. }
  2417. }
  2418. }
  2419. TSubgoal CGoal::whatToDoToAchieve()
  2420. {
  2421. BNLOG("Decomposing goal of type %s", name());
  2422. INDENT;
  2423. switch(goalType)
  2424. {
  2425. case WIN:
  2426. {
  2427. const VictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  2428. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  2429. if(!vc.appliesToAI)
  2430. {
  2431. //TODO deduce victory from human loss condition
  2432. cond = EVictoryConditionType::WINSTANDARD;
  2433. }
  2434. switch(cond)
  2435. {
  2436. case EVictoryConditionType::ARTIFACT:
  2437. return CGoal(GET_ART_TYPE).setaid(vc.objectId);
  2438. case EVictoryConditionType::BEATHERO:
  2439. return CGoal(GET_OBJ).setobjid(vc.obj->id);
  2440. case EVictoryConditionType::BEATMONSTER:
  2441. return CGoal(GET_OBJ).setobjid(vc.obj->id);
  2442. case EVictoryConditionType::BUILDCITY:
  2443. //TODO build castle/capitol
  2444. break;
  2445. case EVictoryConditionType::BUILDGRAIL:
  2446. {
  2447. if(auto h = ai->getHeroWithGrail())
  2448. {
  2449. //hero is in a town that can host Grail
  2450. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  2451. {
  2452. const CGTownInstance *t = h->visitedTown;
  2453. return CGoal(BUILD_STRUCTURE).setbid(BuildingID::GRAIL).settown(t);
  2454. }
  2455. else
  2456. {
  2457. auto towns = cb->getTownsInfo();
  2458. towns.erase(boost::remove_if(towns,
  2459. [](const CGTownInstance *t) -> bool
  2460. {
  2461. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  2462. }),
  2463. towns.end());
  2464. boost::sort(towns, isCloser);
  2465. if(towns.size())
  2466. {
  2467. return CGoal(VISIT_TILE).sethero(h).settile(towns.front()->visitablePos());
  2468. }
  2469. }
  2470. }
  2471. double ratio = 0;
  2472. int3 grailPos = cb->getGrailPos(ratio);
  2473. if(ratio > 0.99)
  2474. {
  2475. return CGoal(DIG_AT_TILE).settile(grailPos);
  2476. } //TODO: use FIND_OBJ
  2477. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  2478. {
  2479. return CGoal(GET_OBJ).setobjid(obj->id);
  2480. }
  2481. else
  2482. return CGoal(EXPLORE);
  2483. }
  2484. break;
  2485. case EVictoryConditionType::CAPTURECITY:
  2486. return CGoal(GET_OBJ).setobjid(vc.obj->id);
  2487. case EVictoryConditionType::GATHERRESOURCE:
  2488. return CGoal(COLLECT_RES).setresID(static_cast<Res::ERes>(vc.objectId)).setvalue(vc.count);
  2489. //TODO mines? piles? marketplace?
  2490. //save?
  2491. break;
  2492. case EVictoryConditionType::GATHERTROOP:
  2493. return CGoal(GATHER_TROOPS).setobjid(vc.objectId).setvalue(vc.count);
  2494. break;
  2495. case EVictoryConditionType::TAKEDWELLINGS:
  2496. break;
  2497. case EVictoryConditionType::TAKEMINES:
  2498. break;
  2499. case EVictoryConditionType::TRANSPORTITEM:
  2500. break;
  2501. case EVictoryConditionType::WINSTANDARD:
  2502. return CGoal(CONQUER);
  2503. default:
  2504. assert(0);
  2505. }
  2506. }
  2507. break;
  2508. case FIND_OBJ:
  2509. {
  2510. const CGObjectInstance * o = NULL;
  2511. if (resID > -1) //specified
  2512. {
  2513. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  2514. {
  2515. if(obj->ID == objid && obj->subID == resID)
  2516. {
  2517. o = obj;
  2518. break; //TODO: consider multiple objects and choose best
  2519. }
  2520. }
  2521. }
  2522. else
  2523. {
  2524. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  2525. {
  2526. if(obj->ID == objid)
  2527. {
  2528. o = obj;
  2529. break; //TODO: consider multiple objects and choose best
  2530. }
  2531. }
  2532. }
  2533. if (o && isReachable(o))
  2534. return CGoal(GET_OBJ).setobjid(o->id);
  2535. else
  2536. return CGoal(EXPLORE);
  2537. }
  2538. break;
  2539. case GET_OBJ:
  2540. {
  2541. const CGObjectInstance * obj = cb->getObj(objid);
  2542. if(!obj)
  2543. return CGoal(EXPLORE);
  2544. int3 pos = obj->visitablePos();
  2545. return CGoal(VISIT_TILE).settile(pos);
  2546. }
  2547. break;
  2548. case VISIT_HERO:
  2549. {
  2550. const CGObjectInstance * obj = cb->getObj(objid);
  2551. if(!obj)
  2552. return CGoal(EXPLORE);
  2553. int3 pos = obj->visitablePos();
  2554. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  2555. return CGoal(*this).settile(pos).setisElementar(true);
  2556. }
  2557. break;
  2558. case GET_ART_TYPE:
  2559. {
  2560. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  2561. if(alternativeWay.invalid())
  2562. return CGoal(FIND_OBJ).setobjid(Obj::ARTIFACT).setresID(aid);
  2563. }
  2564. break;
  2565. case CLEAR_WAY_TO:
  2566. {
  2567. assert(tile.x >= 0); //set tile
  2568. if(!cb->isVisible(tile))
  2569. {
  2570. tlog1 << "Clear way should be used with visible tiles!\n";
  2571. return CGoal(EXPLORE);
  2572. }
  2573. HeroPtr h = hero ? hero : ai->primaryHero();
  2574. if(!h)
  2575. return CGoal(RECRUIT_HERO);
  2576. cb->setSelection(*h);
  2577. SectorMap sm;
  2578. bool dropToFile = false;
  2579. if(dropToFile) //for debug purposes
  2580. sm.write("test.txt");
  2581. int3 tileToHit = sm.firstTileToGet(h, tile);
  2582. //if(isSafeToVisit(h, tileToHit))
  2583. if(isBlockedBorderGate(tileToHit))
  2584. { //FIXME: this way we'll not visit gate and activate quest :?
  2585. return CGoal(FIND_OBJ).setobjid(Obj::KEYMASTER).setresID(cb->getTile(tileToHit)->visitableObjects.back()->subID);
  2586. }
  2587. //FIXME: this code shouldn't be necessary
  2588. if(tileToHit == tile)
  2589. {
  2590. tlog1 << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  2591. % tileToHit % tile % h->name % h->visitablePos();
  2592. throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  2593. }
  2594. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  2595. if(topObj && topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  2596. {
  2597. std::string problem = boost::str(boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText());
  2598. throw cannotFulfillGoalException(problem);
  2599. }
  2600. return CGoal(VISIT_TILE).settile(tileToHit).sethero(h); //FIXME:: attempts to visit completely unreachable tile with hero results in stall
  2601. //TODO czy istnieje lepsza droga?
  2602. }
  2603. throw cannotFulfillGoalException("Cannot reach given tile!");
  2604. case EXPLORE:
  2605. {
  2606. auto objs = ai->visitableObjs; //try to use buildings that uncover map
  2607. erase_if(objs, [&](const CGObjectInstance *obj) -> bool
  2608. {
  2609. if (vstd::contains(ai->alreadyVisited, obj))
  2610. return true;
  2611. switch (obj->ID.num)
  2612. {
  2613. case Obj::REDWOOD_OBSERVATORY:
  2614. case Obj::PILLAR_OF_FIRE:
  2615. case Obj::CARTOGRAPHER:
  2616. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  2617. //case Obj::MONOLITH1:
  2618. //case obj::MONOLITH2:
  2619. //case obj::MONOLITH3:
  2620. //case Obj::WHIRLPOOL:
  2621. return false; //do not erase
  2622. break;
  2623. default:
  2624. return true;
  2625. }
  2626. });
  2627. if (objs.size())
  2628. {
  2629. if (hero.get(true))
  2630. {
  2631. BOOST_FOREACH (auto obj, objs)
  2632. {
  2633. auto pos = obj->visitablePos();
  2634. //FIXME: this confition fails if everything but guarded subterranen gate was explored. in this case we should gather army for hero
  2635. if (isSafeToVisit(hero, pos) && ai->isAccessibleForHero(pos, hero))
  2636. return CGoal(VISIT_TILE).settile(pos).sethero(hero);
  2637. }
  2638. }
  2639. else
  2640. {
  2641. BOOST_FOREACH (auto obj, objs)
  2642. {
  2643. auto pos = obj->visitablePos();
  2644. if (ai->isAccessible (pos)) //TODO: check safety?
  2645. return CGoal(VISIT_TILE).settile(pos).sethero(hero);
  2646. }
  2647. }
  2648. }
  2649. if (hero)
  2650. {
  2651. int3 t = whereToExplore(hero);
  2652. if (t.z == -1) //no safe tile to explore - we need to break!
  2653. {
  2654. erase_if (objs, [&](const CGObjectInstance *obj) -> bool
  2655. {
  2656. switch (obj->ID.num)
  2657. {
  2658. case Obj::CARTOGRAPHER:
  2659. case Obj::SUBTERRANEAN_GATE:
  2660. //case Obj::MONOLITH1:
  2661. //case obj::MONOLITH2:
  2662. //case obj::MONOLITH3:
  2663. //case Obj::WHIRLPOOL:
  2664. return false; //do not erase
  2665. break;
  2666. default:
  2667. return true;
  2668. }
  2669. });
  2670. if (objs.size())
  2671. {
  2672. return CGoal (VISIT_TILE).settile(objs.front()->visitablePos()).sethero(hero).setisAbstract(true);
  2673. }
  2674. else
  2675. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  2676. }
  2677. return CGoal(VISIT_TILE).settile(t).sethero(hero);
  2678. }
  2679. auto hs = cb->getHeroesInfo();
  2680. int howManyHeroes = hs.size();
  2681. erase(hs, [](const CGHeroInstance *h)
  2682. {
  2683. return contains(ai->lockedHeroes, h);
  2684. });
  2685. if(hs.empty()) //all heroes are busy. buy new one
  2686. {
  2687. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2688. return CGoal(RECRUIT_HERO);
  2689. else //find mobile hero with weakest army
  2690. {
  2691. hs = cb->getHeroesInfo();
  2692. erase_if(hs, [](const CGHeroInstance *h)
  2693. {
  2694. return !h->movement; //only hero with movement are of interest for us
  2695. });
  2696. if (hs.empty())
  2697. {
  2698. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2699. return CGoal(RECRUIT_HERO);
  2700. else
  2701. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2702. }
  2703. boost::sort(hs, compareMovement); //closer to what?
  2704. }
  2705. }
  2706. const CGHeroInstance *h = hs.front();
  2707. return (*this).sethero(h).setisAbstract(true);
  2708. }
  2709. I_AM_ELEMENTAR;
  2710. case RECRUIT_HERO:
  2711. {
  2712. const CGTownInstance *t = ai->findTownWithTavern();
  2713. if(!t)
  2714. return CGoal(BUILD_STRUCTURE).setbid(BuildingID::TAVERN);
  2715. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  2716. return CGoal(COLLECT_RES).setresID(Res::GOLD).setvalue(HERO_GOLD_COST);
  2717. I_AM_ELEMENTAR;
  2718. }
  2719. break;
  2720. case VISIT_TILE:
  2721. {
  2722. if(!cb->isVisible(tile))
  2723. return CGoal(EXPLORE);
  2724. if(hero && !ai->isAccessibleForHero(tile, hero))
  2725. hero = NULL;
  2726. if(!hero)
  2727. {
  2728. if(cb->getHeroesInfo().empty())
  2729. {
  2730. return CGoal(RECRUIT_HERO);
  2731. }
  2732. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  2733. {
  2734. if(ai->isAccessibleForHero(tile, h))
  2735. {
  2736. hero = h;
  2737. break;
  2738. }
  2739. }
  2740. }
  2741. if(hero)
  2742. {
  2743. if(isSafeToVisit(hero, tile))
  2744. return CGoal(*this).setisElementar(true);
  2745. else
  2746. {
  2747. return CGoal(GATHER_ARMY).sethero(hero).setvalue(evaluateDanger(tile, *hero) * SAFE_ATTACK_CONSTANT); //TODO: should it be abstract?
  2748. }
  2749. }
  2750. else //inaccessible for all heroes
  2751. {
  2752. return CGoal(CLEAR_WAY_TO).settile(tile);
  2753. }
  2754. }
  2755. break;
  2756. case DIG_AT_TILE:
  2757. {
  2758. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  2759. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  2760. {
  2761. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  2762. return CGoal(*this).sethero(h).setisElementar(true);
  2763. }
  2764. return CGoal(VISIT_TILE).settile(tile);
  2765. }
  2766. break;
  2767. case BUILD_STRUCTURE:
  2768. //TODO check res
  2769. //look for town
  2770. //prerequisites?
  2771. I_AM_ELEMENTAR;
  2772. case COLLECT_RES:
  2773. {
  2774. std::vector<const IMarket*> markets;
  2775. std::vector<const CGObjectInstance*> visObjs;
  2776. ai->retreiveVisitableObjs(visObjs, true);
  2777. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  2778. {
  2779. if(const IMarket *m = IMarket::castFrom(obj, false))
  2780. {
  2781. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  2782. markets.push_back(m);
  2783. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  2784. markets.push_back(m);
  2785. }
  2786. }
  2787. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  2788. {
  2789. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  2790. });
  2791. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  2792. {
  2793. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  2794. && !ai->isAccessible(market->o->visitablePos());
  2795. }),markets.end());
  2796. if(!markets.size())
  2797. {
  2798. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2799. {
  2800. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  2801. return CGoal(BUILD_STRUCTURE).settown(t).setbid(BuildingID::MARKETPLACE);
  2802. }
  2803. }
  2804. else
  2805. {
  2806. const IMarket *m = markets.back();
  2807. //attempt trade at back (best prices)
  2808. int howManyCanWeBuy = 0;
  2809. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  2810. {
  2811. if(i == resID) continue;
  2812. int toGive = -1, toReceive = -1;
  2813. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  2814. assert(toGive > 0 && toReceive > 0);
  2815. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  2816. }
  2817. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  2818. {
  2819. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  2820. assert(backObj);
  2821. if(backObj->tempOwner != ai->playerID)
  2822. return CGoal(GET_OBJ).setobjid(m->o->id);
  2823. return setobjid(m->o->id).setisElementar(true);
  2824. }
  2825. }
  2826. }
  2827. return CGoal(INVALID);
  2828. case GATHER_TROOPS:
  2829. {
  2830. std::vector<const CGDwelling *> dwellings;
  2831. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2832. {
  2833. auto creature = VLC->creh->creatures[objid];
  2834. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  2835. {
  2836. auto creatures = t->town->creatures[creature->level];
  2837. int upgradeNumber = std::find(creatures.begin(), creatures.end(), creature->idNumber) - creatures.begin();
  2838. BuildingID bid(BuildingID::DWELL_FIRST + creature->level + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  2839. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  2840. {
  2841. dwellings.push_back(t);
  2842. }
  2843. else
  2844. {
  2845. return CGoal (BUILD_STRUCTURE).settown(t).setbid(bid);
  2846. }
  2847. }
  2848. }
  2849. BOOST_FOREACH (auto obj, ai->visitableObjs)
  2850. {
  2851. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  2852. continue;
  2853. auto d = dynamic_cast<const CGDwelling *>(obj);
  2854. BOOST_FOREACH (auto creature, d->creatures)
  2855. {
  2856. if (creature.first) //there are more than 0 creatures avaliabe
  2857. {
  2858. BOOST_FOREACH (auto type, creature.second)
  2859. {
  2860. if (type == objid)
  2861. dwellings.push_back(d);
  2862. }
  2863. }
  2864. }
  2865. }
  2866. if (dwellings.size())
  2867. {
  2868. boost::sort(dwellings, isCloser);
  2869. return CGoal(GET_OBJ).setobjid (dwellings.front()->id); //TODO: consider needed resources
  2870. }
  2871. else
  2872. return CGoal(EXPLORE);
  2873. //TODO: exchange troops between heroes
  2874. }
  2875. break;
  2876. case CONQUER: //TODO: put it into a function?
  2877. {
  2878. auto hs = cb->getHeroesInfo();
  2879. int howManyHeroes = hs.size();
  2880. erase(hs, [](const CGHeroInstance *h)
  2881. {
  2882. return contains(ai->lockedHeroes, h);
  2883. });
  2884. if(hs.empty()) //all heroes are busy. buy new one
  2885. {
  2886. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2887. return CGoal(RECRUIT_HERO);
  2888. else //find mobile hero with weakest army
  2889. {
  2890. hs = cb->getHeroesInfo();
  2891. erase_if(hs, [](const CGHeroInstance *h)
  2892. {
  2893. return !h->movement; //only hero with movement are of interest for us
  2894. });
  2895. if (hs.empty())
  2896. {
  2897. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2898. return CGoal(RECRUIT_HERO);
  2899. else
  2900. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2901. }
  2902. boost::sort(hs, compareHeroStrength);
  2903. }
  2904. }
  2905. const CGHeroInstance *h = hs.back();
  2906. cb->setSelection(h);
  2907. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  2908. ai->retreiveVisitableObjs(objs);
  2909. erase_if(objs, [&](const CGObjectInstance *obj)
  2910. {
  2911. return (obj->ID != Obj::TOWN && obj->ID != Obj::HERO) //not town/hero
  2912. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  2913. });
  2914. if (objs.empty()) //experiment - try to conquer dwellings and mines, it should pay off
  2915. {
  2916. ai->retreiveVisitableObjs(objs);
  2917. erase_if(objs, [&](const CGObjectInstance *obj)
  2918. {
  2919. return (obj->ID != Obj::CREATURE_GENERATOR1 && obj->ID != Obj::MINE) //not dwelling or mine
  2920. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  2921. });
  2922. }
  2923. if(objs.empty())
  2924. return CGoal(EXPLORE); //we need to find an enemy
  2925. erase_if(objs, [&](const CGObjectInstance *obj)
  2926. {
  2927. return !isSafeToVisit(h, obj->visitablePos()) || vstd::contains (ai->reservedObjs, obj); //no need to capture same object twice
  2928. });
  2929. if(objs.empty())
  2930. I_AM_ELEMENTAR;
  2931. boost::sort(objs, isCloser);
  2932. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  2933. {
  2934. if (ai->isAccessibleForHero(obj->visitablePos(), h))
  2935. {
  2936. ai->reserveObject(h, obj); //no one else will capture same object until we fail
  2937. if (obj->ID == Obj::HERO)
  2938. return CGoal(VISIT_HERO).sethero(h).setobjid(obj->id).setisAbstract(true); //track enemy hero
  2939. else
  2940. return CGoal(VISIT_TILE).sethero(h).settile(obj->visitablePos());
  2941. }
  2942. }
  2943. return CGoal(EXPLORE); //enemy is inaccessible
  2944. }
  2945. break;
  2946. case BUILD:
  2947. I_AM_ELEMENTAR;
  2948. case INVALID:
  2949. I_AM_ELEMENTAR;
  2950. case GATHER_ARMY:
  2951. {
  2952. //TODO: find hero if none set
  2953. assert(hero);
  2954. cb->setSelection(*hero);
  2955. auto compareReinforcements = [this](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  2956. {
  2957. return howManyReinforcementsCanGet(hero, lhs) < howManyReinforcementsCanGet(hero, rhs);
  2958. };
  2959. std::vector<const CGTownInstance *> townsReachable;
  2960. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2961. {
  2962. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  2963. {
  2964. if(isReachable(t) && !vstd::contains (ai->townVisitsThisWeek[hero], t))
  2965. townsReachable.push_back(t);
  2966. }
  2967. }
  2968. if(townsReachable.size()) //try towns first
  2969. {
  2970. boost::sort(townsReachable, compareReinforcements);
  2971. return CGoal(VISIT_TILE).sethero(hero).settile(townsReachable.back()->visitablePos());
  2972. }
  2973. else
  2974. {
  2975. if (hero == ai->primaryHero()) //we can get army from other heroes
  2976. {
  2977. auto otherHeroes = cb->getHeroesInfo();
  2978. auto heroDummy = hero;
  2979. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  2980. {
  2981. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true) || !ai->canGetArmy(heroDummy.h, h));
  2982. });
  2983. if (otherHeroes.size())
  2984. {
  2985. boost::sort(otherHeroes, compareArmyStrength); //TODO: check if hero has at least one stack more powerful than ours? not likely to fail
  2986. int primaryPath, secondaryPath;
  2987. auto h = otherHeroes.back();
  2988. cb->setSelection(hero.h);
  2989. primaryPath = cb->getPathInfo(h->visitablePos())->turns;
  2990. cb->setSelection(h);
  2991. secondaryPath = cb->getPathInfo(hero->visitablePos())->turns;
  2992. if (primaryPath < secondaryPath)
  2993. return CGoal(VISIT_HERO).setisAbstract(true).setobjid(h->id).sethero(hero); //go to the other hero if we are faster
  2994. else
  2995. return CGoal(VISIT_HERO).setisAbstract(true).setobjid(hero->id).sethero(h); //let the other hero come to us
  2996. }
  2997. }
  2998. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  2999. ai->retreiveVisitableObjs(objs);
  3000. erase_if(objs, [&](const CGObjectInstance *obj)
  3001. {
  3002. return (obj->ID != Obj::CREATURE_GENERATOR1);
  3003. });
  3004. if(objs.empty()) //no possible objects, we did eveyrthing already
  3005. return CGoal(EXPLORE).sethero(hero);
  3006. //TODO: check if we can recruit any creatures there, evaluate army
  3007. else
  3008. {
  3009. boost::sort(objs, isCloser);
  3010. HeroPtr h = NULL;
  3011. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  3012. { //find safe dwelling
  3013. auto pos = obj->visitablePos();
  3014. if (shouldVisit (hero, obj)) //creatures fit in army
  3015. h = hero;
  3016. else
  3017. {
  3018. BOOST_FOREACH(auto ourHero, cb->getHeroesInfo()) //make use of multiple heroes
  3019. {
  3020. if (shouldVisit(ourHero, obj))
  3021. h = ourHero;
  3022. }
  3023. }
  3024. if (h && isSafeToVisit(h, pos) && ai->isAccessibleForHero(pos, h))
  3025. return CGoal(VISIT_TILE).sethero(h).settile(pos);
  3026. }
  3027. }
  3028. }
  3029. return CGoal(EXPLORE).sethero(hero); //find dwelling. use current hero to prevent him from doing nothing.
  3030. }
  3031. break;
  3032. default:
  3033. assert(0);
  3034. }
  3035. return CGoal(EXPLORE);
  3036. }
  3037. TSubgoal CGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  3038. {
  3039. if(obj)
  3040. return CGoal(GET_OBJ).setobjid(obj->id);
  3041. else
  3042. return CGoal(EXPLORE);
  3043. }
  3044. TSubgoal CGoal::lookForArtSmart(int aid)
  3045. {
  3046. return CGoal(INVALID);
  3047. }
  3048. bool CGoal::invalid() const
  3049. {
  3050. return goalType == INVALID;
  3051. }
  3052. bool isBlockedBorderGate(int3 tileToHit)
  3053. {
  3054. return cb->getTile(tileToHit)->topVisitableId() == Obj::BORDER_GATE
  3055. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  3056. }
  3057. SectorMap::SectorMap()
  3058. {
  3059. // int3 sizes = cb->getMapSize();
  3060. // sector.resize(sizes.x);
  3061. // BOOST_FOREACH(auto &i, sector)
  3062. // i.resize(sizes.y);
  3063. //
  3064. // BOOST_FOREACH(auto &i, sector)
  3065. // BOOST_FOREACH(auto &j, i)
  3066. // j.resize(sizes.z, 0);
  3067. update();
  3068. }
  3069. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  3070. {
  3071. if(t->blocked && !t->visitable)
  3072. {
  3073. sec = NOT_AVAILABLE;
  3074. return true;
  3075. }
  3076. return false;
  3077. }
  3078. bool markIfBlocked(ui8 &sec, crint3 pos)
  3079. {
  3080. return markIfBlocked(sec, pos, cb->getTile(pos));
  3081. }
  3082. void SectorMap::update()
  3083. {
  3084. clear();
  3085. int curSector = 3; //0 is invisible, 1 is not explored
  3086. foreach_tile_pos([&](crint3 pos)
  3087. {
  3088. if(retreiveTile(pos) == NOT_CHECKED)
  3089. {
  3090. if(!markIfBlocked(retreiveTile(pos), pos))
  3091. exploreNewSector(pos, curSector++);
  3092. }
  3093. });
  3094. valid = true;
  3095. }
  3096. void SectorMap::clear()
  3097. {
  3098. sector = cb->getVisibilityMap();
  3099. valid = false;
  3100. }
  3101. bool canBeEmbarkmentPoint(const TerrainTile *t)
  3102. {
  3103. //tile must be free of with unoccupied boat
  3104. return !t->blocked
  3105. || (t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT);
  3106. }
  3107. void SectorMap::exploreNewSector(crint3 pos, int num)
  3108. {
  3109. Sector &s = infoOnSectors[num];
  3110. s.id = num;
  3111. s.water = cb->getTile(pos)->isWater();
  3112. std::queue<int3> toVisit;
  3113. toVisit.push(pos);
  3114. while(toVisit.size())
  3115. {
  3116. int3 curPos = toVisit.front();
  3117. toVisit.pop();
  3118. ui8 &sec = retreiveTile(curPos);
  3119. if(sec == NOT_CHECKED)
  3120. {
  3121. const TerrainTile *t = cb->getTile(curPos);
  3122. if(!markIfBlocked(sec, curPos, t))
  3123. {
  3124. if(t->isWater() == s.water) //sector is only-water or only-land
  3125. {
  3126. sec = num;
  3127. s.tiles.push_back(curPos);
  3128. foreach_neighbour(curPos, [&](crint3 neighPos)
  3129. {
  3130. if(retreiveTile(neighPos) == NOT_CHECKED)
  3131. {
  3132. toVisit.push(neighPos);
  3133. //parent[neighPos] = curPos;
  3134. }
  3135. const TerrainTile *nt = cb->getTile(neighPos, false);
  3136. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  3137. {
  3138. s.embarkmentPoints.push_back(neighPos);
  3139. }
  3140. });
  3141. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  3142. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->visitablePos());
  3143. }
  3144. }
  3145. }
  3146. }
  3147. removeDuplicates(s.embarkmentPoints);
  3148. }
  3149. void SectorMap::write(crstring fname)
  3150. {
  3151. std::ofstream out(fname);
  3152. for(int k = 0; k < cb->getMapSize().z; k++)
  3153. {
  3154. for(int j = 0; j < cb->getMapSize().y; j++)
  3155. {
  3156. for(int i = 0; i < cb->getMapSize().x; i++)
  3157. {
  3158. out << (int)sector[i][j][k] << '\t';
  3159. }
  3160. out << std::endl;
  3161. }
  3162. out << std::endl;
  3163. }
  3164. }
  3165. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  3166. { //TODO: allow polling of remaining creatures in dwelling
  3167. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  3168. dynamic_cast<const CGDwelling *>(obj) ||
  3169. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  3170. return true;
  3171. switch (obj->ID)
  3172. {
  3173. case Obj::STABLES:
  3174. case Obj::MAGIC_WELL:
  3175. case Obj::HILL_FORT:
  3176. return true;
  3177. break;
  3178. case Obj::BORDER_GATE:
  3179. case Obj::BORDERGUARD:
  3180. return (dynamic_cast <const CGKeys *>(obj))->wasMyColorVisited (ai->playerID); //FIXME: they could be revisited sooner than in a week
  3181. break;
  3182. }
  3183. return false;
  3184. }
  3185. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  3186. {
  3187. switch (obj->ID)
  3188. {
  3189. case Obj::BORDERGUARD:
  3190. case Obj::BORDER_GATE:
  3191. {
  3192. BOOST_FOREACH (auto q, ai->myCb->getMyQuests())
  3193. {
  3194. if (q.obj == obj)
  3195. {
  3196. return false; // do not visit guards or gates when wandering
  3197. }
  3198. }
  3199. return true; //we don't have this quest yet
  3200. break;
  3201. }
  3202. case Obj::SEER_HUT:
  3203. case Obj::QUEST_GUARD:
  3204. {
  3205. BOOST_FOREACH (auto q, ai->myCb->getMyQuests())
  3206. {
  3207. if (q.obj == obj)
  3208. {
  3209. if (q.quest->checkQuest(*h))
  3210. return true; //we completed the quest
  3211. else
  3212. return false; //we can't complete this quest
  3213. }
  3214. }
  3215. return true; //we don't have this quest yet
  3216. break;
  3217. }
  3218. case Obj::CREATURE_GENERATOR1:
  3219. {
  3220. if (obj->tempOwner != h->tempOwner)
  3221. return true; //flag just in case
  3222. bool canRecruitCreatures = false;
  3223. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  3224. BOOST_FOREACH(auto level, d->creatures)
  3225. {
  3226. BOOST_FOREACH(auto c, level.second)
  3227. {
  3228. if (h->getSlotFor(c) != -1)
  3229. canRecruitCreatures = true;
  3230. }
  3231. }
  3232. return canRecruitCreatures;
  3233. break;
  3234. }
  3235. case Obj::HILL_FORT:
  3236. {
  3237. BOOST_FOREACH (auto slot, h->Slots())
  3238. {
  3239. if (slot.second->type->upgrades.size())
  3240. return true; //TODO: check price?
  3241. }
  3242. return false;
  3243. break;
  3244. }
  3245. case Obj::MONOLITH1:
  3246. case Obj::MONOLITH2:
  3247. case Obj::MONOLITH3:
  3248. case Obj::WHIRLPOOL:
  3249. //TODO: mechanism for handling monoliths
  3250. return false;
  3251. break;
  3252. case Obj::SCHOOL_OF_MAGIC:
  3253. case Obj::SCHOOL_OF_WAR:
  3254. {
  3255. TResources myRes = ai->myCb->getResourceAmount();
  3256. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  3257. return false;
  3258. }
  3259. break;
  3260. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  3261. if (h->level < 12)
  3262. return false;
  3263. break;
  3264. case Obj::TREE_OF_KNOWLEDGE:
  3265. {
  3266. TResources myRes = ai->myCb->getResourceAmount();
  3267. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  3268. return false;
  3269. }
  3270. break;
  3271. case Obj::MAGIC_WELL:
  3272. return h->mana < h->manaLimit();
  3273. break;
  3274. case Obj::PRISON:
  3275. return ai->myCb->getHeroesInfo().size() < GameConstants::MAX_HEROES_PER_PLAYER;
  3276. break;
  3277. case Obj::BOAT:
  3278. return false;
  3279. //Boats are handled by pathfinder
  3280. }
  3281. if (obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  3282. return false;
  3283. return true;
  3284. }
  3285. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  3286. {
  3287. int sourceSector = retreiveTile(h->visitablePos()),
  3288. destinationSector = retreiveTile(dst);
  3289. if(sourceSector != destinationSector)
  3290. {
  3291. const Sector *src = &infoOnSectors[sourceSector],
  3292. *dst = &infoOnSectors[destinationSector];
  3293. std::map<const Sector*, const Sector*> preds;
  3294. std::queue<const Sector *> sq;
  3295. sq.push(src);
  3296. while(!sq.empty())
  3297. {
  3298. const Sector *s = sq.front();
  3299. sq.pop();
  3300. BOOST_FOREACH(int3 ep, s->embarkmentPoints)
  3301. {
  3302. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  3303. //preds[s].push_back(neigh);
  3304. if(!preds[neigh])
  3305. {
  3306. preds[neigh] = s;
  3307. sq.push(neigh);
  3308. }
  3309. }
  3310. //TODO consider other types of connections between sectors?
  3311. }
  3312. if(!preds[dst])
  3313. {
  3314. write("test.txt");
  3315. ai->completeGoal (CGoal(EXPLORE).sethero(h)); //if we can't find the way, seemingly all tiles were explored
  3316. //TODO: more organized way?
  3317. throw cannotFulfillGoalException(str(format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  3318. }
  3319. std::vector<const Sector*> toTraverse;
  3320. toTraverse.push_back(dst);
  3321. while(toTraverse.back() != src)
  3322. {
  3323. toTraverse.push_back(preds[toTraverse.back()]);
  3324. }
  3325. if(preds[dst])
  3326. {
  3327. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  3328. if(!src->water && sectorToReach->water) //embark
  3329. {
  3330. //embark on ship -> look for an EP with a boat
  3331. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  3332. {
  3333. const TerrainTile *t = cb->getTile(pos);
  3334. return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT
  3335. && retreiveTile(pos) == sectorToReach->id;
  3336. });
  3337. if(firstEP != src->embarkmentPoints.end())
  3338. {
  3339. return *firstEP;
  3340. }
  3341. else
  3342. {
  3343. //we need to find a shipyard with an access to the desired sector's EP
  3344. //TODO what about Summon Boat spell?
  3345. std::vector<const IShipyard *> shipyards;
  3346. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  3347. {
  3348. if(t->hasBuilt(BuildingID::SHIPYARD))
  3349. shipyards.push_back(t);
  3350. }
  3351. std::vector<const CGObjectInstance*> visObjs;
  3352. ai->retreiveVisitableObjs(visObjs, true);
  3353. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  3354. {
  3355. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  3356. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  3357. shipyards.push_back(shipyard);
  3358. }
  3359. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  3360. {
  3361. return shipyard->state() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  3362. }),shipyards.end());
  3363. if(!shipyards.size())
  3364. {
  3365. //TODO consider possibility of building shipyard in a town
  3366. throw cannotFulfillGoalException("There is no known shipyard!");
  3367. }
  3368. //we have only shipyards that possibly can build ships onto the appropriate EP
  3369. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  3370. {
  3371. return s->o->tempOwner == ai->playerID;
  3372. });
  3373. if(ownedGoodShipyard != shipyards.end())
  3374. {
  3375. const IShipyard *s = *ownedGoodShipyard;
  3376. TResources shipCost;
  3377. s->getBoatCost(shipCost);
  3378. if(cb->getResourceAmount().canAfford(shipCost))
  3379. {
  3380. int3 ret = s->bestLocation();
  3381. cb->buildBoat(s);
  3382. return ret;
  3383. }
  3384. else
  3385. {
  3386. //TODO gather res
  3387. throw cannotFulfillGoalException("Not enough resources to build a boat");
  3388. }
  3389. }
  3390. else
  3391. {
  3392. //TODO pick best shipyard to take over
  3393. return shipyards.front()->o->visitablePos();
  3394. }
  3395. }
  3396. }
  3397. else if(src->water && !sectorToReach->water)
  3398. {
  3399. //TODO
  3400. //disembark
  3401. }
  3402. else
  3403. {
  3404. //TODO
  3405. //transition between two land/water sectors. Monolith? Whirlpool? ...
  3406. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  3407. }
  3408. }
  3409. else
  3410. {
  3411. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  3412. }
  3413. }
  3414. else
  3415. {
  3416. makeParentBFS(h->visitablePos());
  3417. int3 curtile = dst;
  3418. while(curtile != h->visitablePos())
  3419. {
  3420. if(cb->getPathInfo(curtile)->reachable())
  3421. {
  3422. return curtile;
  3423. }
  3424. else
  3425. {
  3426. auto i = parent.find(curtile);
  3427. if(i != parent.end())
  3428. {
  3429. assert(curtile != i->second);
  3430. curtile = i->second;
  3431. }
  3432. else
  3433. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  3434. }
  3435. }
  3436. }
  3437. throw cannotFulfillGoalException("Impossible happened.");
  3438. }
  3439. void SectorMap::makeParentBFS(crint3 source)
  3440. {
  3441. parent.clear();
  3442. int mySector = retreiveTile(source);
  3443. std::queue<int3> toVisit;
  3444. toVisit.push(source);
  3445. while(toVisit.size())
  3446. {
  3447. int3 curPos = toVisit.front();
  3448. toVisit.pop();
  3449. ui8 &sec = retreiveTile(curPos);
  3450. assert(sec == mySector); //consider only tiles from the same sector
  3451. //const TerrainTile *t = cb->getTile(curPos);
  3452. foreach_neighbour(curPos, [&](crint3 neighPos)
  3453. {
  3454. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  3455. {
  3456. toVisit.push(neighPos);
  3457. parent[neighPos] = curPos;
  3458. }
  3459. });
  3460. }
  3461. }
  3462. unsigned char & SectorMap::retreiveTile(crint3 pos)
  3463. {
  3464. return retreiveTileN(sector, pos);
  3465. }
  3466. const CGObjectInstance * ObjectIdRef::operator->() const
  3467. {
  3468. return cb->getObj(id, false);
  3469. }
  3470. ObjectIdRef::operator const CGObjectInstance*() const
  3471. {
  3472. return cb->getObj(id, false);
  3473. }
  3474. ObjectIdRef::ObjectIdRef(int _id) : id(_id)
  3475. {
  3476. }
  3477. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  3478. {
  3479. }
  3480. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  3481. {
  3482. return id < rhs.id;
  3483. }
  3484. HeroPtr::HeroPtr(const CGHeroInstance *H)
  3485. {
  3486. if(!H)
  3487. {
  3488. //init from nullptr should equal to default init
  3489. *this = HeroPtr();
  3490. return;
  3491. }
  3492. h = H;
  3493. name = h->name;
  3494. hid = H->id;
  3495. // infosCount[ai->playerID][hid]++;
  3496. }
  3497. HeroPtr::HeroPtr()
  3498. {
  3499. h = nullptr;
  3500. hid = -1;
  3501. }
  3502. HeroPtr::~HeroPtr()
  3503. {
  3504. // if(hid >= 0)
  3505. // infosCount[ai->playerID][hid]--;
  3506. }
  3507. bool HeroPtr::operator<(const HeroPtr &rhs) const
  3508. {
  3509. return hid < rhs.hid;
  3510. }
  3511. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
  3512. {
  3513. //TODO? check if these all assertions every time we get info about hero affect efficiency
  3514. //
  3515. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  3516. assert(doWeExpectNull || h);
  3517. if(h)
  3518. {
  3519. auto obj = cb->getObj(hid);
  3520. const bool owned = obj && obj->tempOwner == ai->playerID;
  3521. if(doWeExpectNull && !owned)
  3522. {
  3523. return nullptr;
  3524. }
  3525. else
  3526. {
  3527. assert(obj);
  3528. assert(owned);
  3529. }
  3530. }
  3531. return h;
  3532. }
  3533. const CGHeroInstance * HeroPtr::operator->() const
  3534. {
  3535. return get();
  3536. }
  3537. bool HeroPtr::validAndSet() const
  3538. {
  3539. return get(true);
  3540. }
  3541. const CGHeroInstance * HeroPtr::operator*() const
  3542. {
  3543. return get();
  3544. }