VCAI.cpp 112 KB

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