VCAI.cpp 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291
  1. #include "StdInc.h"
  2. #include "VCAI.h"
  3. #include "Goals.h"
  4. #include "Fuzzy.h"
  5. #include "../../lib/UnlockGuard.h"
  6. #include "../../lib/mapObjects/MapObjects.h"
  7. #include "../../lib/CConfigHandler.h"
  8. #include "../../lib/CHeroHandler.h"
  9. #include "../../lib/CModHandler.h"
  10. /*
  11. * CCreatureHandler.h, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. extern FuzzyHelper *fh;
  20. class CGVisitableOPW;
  21. const double SAFE_ATTACK_CONSTANT = 1.5;
  22. 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)
  23. using namespace vstd;
  24. //one thread may be turn of AI and another will be handling a side effect for AI2
  25. boost::thread_specific_ptr<CCallback> cb;
  26. boost::thread_specific_ptr<VCAI> ai;
  27. //std::map<int, std::map<int, int> > HeroView::infosCount;
  28. //helper RAII to manage global ai/cb ptrs
  29. struct SetGlobalState
  30. {
  31. SetGlobalState(VCAI * AI)
  32. {
  33. assert(!ai.get());
  34. assert(!cb.get());
  35. ai.reset(AI);
  36. cb.reset(AI->myCb.get());
  37. }
  38. ~SetGlobalState()
  39. {
  40. ai.release();
  41. cb.release();
  42. }
  43. };
  44. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  45. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  46. #define MAKING_TURN SET_GLOBAL_STATE(this)
  47. unsigned char &retreiveTileN(std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  48. {
  49. return vectors[pos.x][pos.y][pos.z];
  50. }
  51. const unsigned char &retreiveTileN(const std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  52. {
  53. return vectors[pos.x][pos.y][pos.z];
  54. }
  55. void foreach_tile(std::vector< std::vector< std::vector<unsigned char> > > &vectors, std::function<void(unsigned char &in)> foo)
  56. {
  57. for(auto & vector : vectors)
  58. for(auto j = vector.begin(); j != vector.end(); j++)
  59. for(auto & elem : *j)
  60. foo(elem);
  61. }
  62. struct ObjInfo
  63. {
  64. int3 pos;
  65. std::string name;
  66. ObjInfo(){}
  67. ObjInfo(const CGObjectInstance *obj):
  68. pos(obj->pos),
  69. name(obj->getObjectName())
  70. {
  71. }
  72. };
  73. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  74. VCAI::VCAI(void)
  75. {
  76. LOG_TRACE(logAi);
  77. makingTurn = nullptr;
  78. destinationTeleport = ObjectInstanceID();
  79. }
  80. VCAI::~VCAI(void)
  81. {
  82. LOG_TRACE(logAi);
  83. }
  84. void VCAI::availableCreaturesChanged(const CGDwelling *town)
  85. {
  86. LOG_TRACE(logAi);
  87. NET_EVENT_HANDLER;
  88. }
  89. void VCAI::heroMoved(const TryMoveHero & details)
  90. {
  91. LOG_TRACE(logAi);
  92. NET_EVENT_HANDLER;
  93. validateObject(details.id); //enemy hero may have left visible area
  94. if(details.result == TryMoveHero::TELEPORTATION)
  95. {
  96. const int3 from = CGHeroInstance::convertPosition(details.start, false),
  97. to = CGHeroInstance::convertPosition(details.end, false);
  98. const CGObjectInstance *o1 = frontOrNull(cb->getVisitableObjs(from)),
  99. *o2 = frontOrNull(cb->getVisitableObjs(to));
  100. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  101. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  102. if(t1 && t2)
  103. {
  104. if(cb->isTeleportChannelBidirectional(t1->channel))
  105. {
  106. if(o1->ID == Obj::SUBTERRANEAN_GATE && o1->ID == o2->ID) // We need to only add subterranean gates in knownSubterraneanGates. Used for features not yet ported to use teleport channels
  107. {
  108. knownSubterraneanGates[o1] = o2;
  109. knownSubterraneanGates[o2] = o1;
  110. logAi->debugStream() << boost::format("Found a pair of subterranean gates between %s and %s!") % from % to;
  111. }
  112. }
  113. }
  114. }
  115. }
  116. void VCAI::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  117. {
  118. LOG_TRACE_PARAMS(logAi, "isAbsolute '%i'", isAbsolute);
  119. NET_EVENT_HANDLER;
  120. }
  121. void VCAI::heroInGarrisonChange(const CGTownInstance *town)
  122. {
  123. LOG_TRACE(logAi);
  124. NET_EVENT_HANDLER;
  125. }
  126. void VCAI::centerView(int3 pos, int focusTime)
  127. {
  128. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  129. NET_EVENT_HANDLER;
  130. }
  131. void VCAI::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  132. {
  133. LOG_TRACE(logAi);
  134. NET_EVENT_HANDLER;
  135. }
  136. void VCAI::artifactAssembled(const ArtifactLocation &al)
  137. {
  138. LOG_TRACE(logAi);
  139. NET_EVENT_HANDLER;
  140. }
  141. void VCAI::showTavernWindow(const CGObjectInstance *townOrTavern)
  142. {
  143. LOG_TRACE(logAi);
  144. NET_EVENT_HANDLER;
  145. }
  146. void VCAI::showThievesGuildWindow (const CGObjectInstance * obj)
  147. {
  148. LOG_TRACE(logAi);
  149. NET_EVENT_HANDLER;
  150. }
  151. void VCAI::playerBlocked(int reason, bool start)
  152. {
  153. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  154. NET_EVENT_HANDLER;
  155. if (start && reason == PlayerBlocked::UPCOMING_BATTLE)
  156. status.setBattle(UPCOMING_BATTLE);
  157. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  158. status.setMove(start);
  159. }
  160. void VCAI::showPuzzleMap()
  161. {
  162. LOG_TRACE(logAi);
  163. NET_EVENT_HANDLER;
  164. }
  165. void VCAI::showShipyardDialog(const IShipyard *obj)
  166. {
  167. LOG_TRACE(logAi);
  168. NET_EVENT_HANDLER;
  169. }
  170. void VCAI::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  171. {
  172. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf);
  173. NET_EVENT_HANDLER;
  174. logAi->debugStream() << boost::format("Player %d: I heard that player %d %s.") % playerID % player.getNum() % (victoryLossCheckResult.victory() ? "won" : "lost");
  175. if(player == playerID)
  176. {
  177. if(victoryLossCheckResult.victory())
  178. {
  179. logAi->debugStream() << "VCAI: I won! Incredible!";
  180. logAi->debugStream() << "Turn nr " << myCb->getDate();
  181. }
  182. else
  183. {
  184. logAi->debugStream() << "VCAI: Player " << player << " lost. It's me. What a disappointment! :(";
  185. }
  186. finish();
  187. }
  188. }
  189. void VCAI::artifactPut(const ArtifactLocation &al)
  190. {
  191. LOG_TRACE(logAi);
  192. NET_EVENT_HANDLER;
  193. }
  194. void VCAI::artifactRemoved(const ArtifactLocation &al)
  195. {
  196. LOG_TRACE(logAi);
  197. NET_EVENT_HANDLER;
  198. }
  199. void VCAI::stacksErased(const StackLocation &location)
  200. {
  201. LOG_TRACE(logAi);
  202. NET_EVENT_HANDLER;
  203. }
  204. void VCAI::artifactDisassembled(const ArtifactLocation &al)
  205. {
  206. LOG_TRACE(logAi);
  207. NET_EVENT_HANDLER;
  208. }
  209. void VCAI::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  210. {
  211. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
  212. NET_EVENT_HANDLER;
  213. if(start)
  214. {
  215. markObjectVisited (visitedObj);
  216. unreserveObject(visitor, visitedObj);
  217. completeGoal (sptr(Goals::GetObj(visitedObj->id.getNum()).sethero(visitor))); //we don't need to visit it anymore
  218. //TODO: what if we visited one-time visitable object that was reserved by another hero (shouldn't, but..)
  219. }
  220. status.heroVisit(visitedObj, start);
  221. }
  222. void VCAI::availableArtifactsChanged(const CGBlackMarket *bm /*= nullptr*/)
  223. {
  224. LOG_TRACE(logAi);
  225. NET_EVENT_HANDLER;
  226. }
  227. void VCAI::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  228. {
  229. LOG_TRACE(logAi);
  230. NET_EVENT_HANDLER;
  231. //buildArmyIn(town);
  232. //moveCreaturesToHero(town);
  233. }
  234. void VCAI::tileHidden(const std::unordered_set<int3, ShashInt3> &pos)
  235. {
  236. LOG_TRACE(logAi);
  237. NET_EVENT_HANDLER;
  238. validateVisitableObjs();
  239. }
  240. void VCAI::tileRevealed(const std::unordered_set<int3, ShashInt3> &pos)
  241. {
  242. LOG_TRACE(logAi);
  243. NET_EVENT_HANDLER;
  244. for(int3 tile : pos)
  245. for(const CGObjectInstance *obj : myCb->getVisitableObjs(tile))
  246. addVisitableObj(obj);
  247. clearHeroesUnableToExplore();
  248. }
  249. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  250. {
  251. LOG_TRACE(logAi);
  252. NET_EVENT_HANDLER;
  253. auto firstHero = cb->getHero(hero1);
  254. auto secondHero = cb->getHero(hero2);
  255. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s and %s") % firstHero->name % secondHero->name));
  256. requestActionASAP([=]()
  257. {
  258. float goalpriority1 = 0, goalpriority2 = 0;
  259. auto firstGoal = getGoal(firstHero);
  260. if (firstGoal->goalType == Goals::GATHER_ARMY)
  261. goalpriority1 = firstGoal->priority;
  262. auto secondGoal = getGoal(secondHero);
  263. if (secondGoal->goalType == Goals::GATHER_ARMY)
  264. goalpriority2 = secondGoal->priority;
  265. if (goalpriority1 > goalpriority2)
  266. pickBestCreatures (firstHero, secondHero);
  267. else if (goalpriority1 < goalpriority2)
  268. pickBestCreatures (secondHero, firstHero);
  269. else //regular criteria
  270. {
  271. if (firstHero->getFightingStrength() > secondHero->getFightingStrength() && canGetArmy (firstHero, secondHero))
  272. pickBestCreatures (firstHero, secondHero);
  273. else if (canGetArmy (secondHero, firstHero))
  274. pickBestCreatures (secondHero, firstHero);
  275. completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
  276. completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
  277. //TODO: exchange artifacts
  278. }
  279. answerQuery(query, 0);
  280. });
  281. }
  282. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  283. {
  284. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  285. NET_EVENT_HANDLER;
  286. }
  287. void VCAI::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  288. {
  289. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  290. NET_EVENT_HANDLER;
  291. }
  292. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  293. {
  294. LOG_TRACE(logAi);
  295. NET_EVENT_HANDLER;
  296. }
  297. void VCAI::stackChangedType(const StackLocation &location, const CCreature &newType)
  298. {
  299. LOG_TRACE(logAi);
  300. NET_EVENT_HANDLER;
  301. }
  302. void VCAI::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  303. {
  304. LOG_TRACE(logAi);
  305. NET_EVENT_HANDLER;
  306. }
  307. void VCAI::newObject(const CGObjectInstance * obj)
  308. {
  309. LOG_TRACE(logAi);
  310. NET_EVENT_HANDLER;
  311. if(obj->isVisitable())
  312. addVisitableObj(obj);
  313. clearHeroesUnableToExplore();
  314. }
  315. void VCAI::objectRemoved(const CGObjectInstance *obj)
  316. {
  317. LOG_TRACE(logAi);
  318. NET_EVENT_HANDLER;
  319. erase_if_present(visitableObjs, obj);
  320. erase_if_present(alreadyVisited, obj);
  321. for (auto h : cb->getHeroesInfo())
  322. unreserveObject(h, obj);
  323. //TODO
  324. //there are other places where CGObjectinstance ptrs are stored...
  325. //
  326. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  327. {
  328. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  329. }
  330. }
  331. void VCAI::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  332. {
  333. LOG_TRACE(logAi);
  334. NET_EVENT_HANDLER;
  335. requestActionASAP([=]()
  336. {
  337. makePossibleUpgrades(visitor);
  338. });
  339. }
  340. void VCAI::playerBonusChanged(const Bonus &bonus, bool gain)
  341. {
  342. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  343. NET_EVENT_HANDLER;
  344. }
  345. void VCAI::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  346. {
  347. LOG_TRACE(logAi);
  348. NET_EVENT_HANDLER;
  349. }
  350. void VCAI::heroCreated(const CGHeroInstance* h)
  351. {
  352. LOG_TRACE(logAi);
  353. if (h->visitedTown)
  354. townVisitsThisWeek[HeroPtr(h)].insert(h->visitedTown);
  355. NET_EVENT_HANDLER;
  356. }
  357. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  358. {
  359. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  360. NET_EVENT_HANDLER;
  361. }
  362. void VCAI::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  363. {
  364. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  365. NET_EVENT_HANDLER;
  366. }
  367. void VCAI::requestRealized(PackageApplied *pa)
  368. {
  369. LOG_TRACE(logAi);
  370. NET_EVENT_HANDLER;
  371. if(status.haveTurn())
  372. {
  373. if(pa->packType == typeList.getTypeID<EndTurn>())
  374. if(pa->result)
  375. status.madeTurn();
  376. }
  377. if(pa->packType == typeList.getTypeID<QueryReply>())
  378. {
  379. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  380. }
  381. }
  382. void VCAI::receivedResource(int type, int val)
  383. {
  384. LOG_TRACE_PARAMS(logAi, "type '%i', val '%i'", type % val);
  385. NET_EVENT_HANDLER;
  386. }
  387. void VCAI::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  388. {
  389. LOG_TRACE(logAi);
  390. NET_EVENT_HANDLER;
  391. }
  392. void VCAI::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  393. {
  394. LOG_TRACE(logAi);
  395. NET_EVENT_HANDLER;
  396. }
  397. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  398. {
  399. LOG_TRACE(logAi);
  400. NET_EVENT_HANDLER;
  401. }
  402. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  403. {
  404. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  405. NET_EVENT_HANDLER;
  406. }
  407. void VCAI::battleResultsApplied()
  408. {
  409. LOG_TRACE(logAi);
  410. NET_EVENT_HANDLER;
  411. assert(status.getBattle() == ENDING_BATTLE);
  412. status.setBattle(NO_BATTLE);
  413. }
  414. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  415. {
  416. LOG_TRACE(logAi);
  417. NET_EVENT_HANDLER;
  418. if(sop->what == ObjProperty::OWNER)
  419. {
  420. //we don't want to visit know object twice (do we really?)
  421. if(sop->val == playerID.getNum())
  422. erase_if_present(visitableObjs, myCb->getObj(sop->id));
  423. else if (myCb->getPlayerRelations(playerID, (PlayerColor)sop->val) == PlayerRelations::ENEMIES)
  424. {
  425. //we want to visit objects owned by oppponents
  426. auto obj = myCb->getObj(sop->id, false);
  427. if (obj)
  428. {
  429. addVisitableObj(obj);
  430. erase_if_present(alreadyVisited, obj);
  431. }
  432. }
  433. }
  434. }
  435. void VCAI::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what)
  436. {
  437. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  438. NET_EVENT_HANDLER;
  439. }
  440. void VCAI::heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain)
  441. {
  442. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  443. NET_EVENT_HANDLER;
  444. }
  445. void VCAI::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  446. {
  447. LOG_TRACE(logAi);
  448. NET_EVENT_HANDLER;
  449. }
  450. void VCAI::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions)
  451. {
  452. //TODO: AI support for ViewXXX spell
  453. LOG_TRACE(logAi);
  454. NET_EVENT_HANDLER;
  455. }
  456. void VCAI::init(shared_ptr<CCallback> CB)
  457. {
  458. LOG_TRACE(logAi);
  459. myCb = CB;
  460. cbc = CB;
  461. NET_EVENT_HANDLER;
  462. playerID = *myCb->getMyColor();
  463. myCb->waitTillRealize = true;
  464. myCb->unlockGsWhenWaiting = true;
  465. if(!fh)
  466. fh = new FuzzyHelper();
  467. retreiveVisitableObjs();
  468. }
  469. void VCAI::yourTurn()
  470. {
  471. LOG_TRACE(logAi);
  472. NET_EVENT_HANDLER;
  473. status.startedTurn();
  474. makingTurn = make_unique<boost::thread>(&VCAI::makeTurn, this);
  475. }
  476. void VCAI::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID)
  477. {
  478. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  479. NET_EVENT_HANDLER;
  480. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  481. requestActionASAP([=]{ answerQuery(queryID, 0); });
  482. }
  483. void VCAI::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  484. {
  485. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  486. NET_EVENT_HANDLER;
  487. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  488. requestActionASAP([=]{ answerQuery(queryID, 0); });
  489. }
  490. void VCAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel)
  491. {
  492. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  493. NET_EVENT_HANDLER;
  494. int sel = 0;
  495. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  496. % components.size() % text));
  497. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  498. sel = components.size();
  499. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  500. sel = 1;
  501. requestActionASAP([=]()
  502. {
  503. answerQuery(askID, sel);
  504. });
  505. }
  506. void VCAI::showTeleportDialog(TeleportChannelID channel, std::vector<ObjectInstanceID> exits, bool impassable, QueryID askID)
  507. {
  508. LOG_TRACE_PARAMS(logAi, "askID '%i', exits '%s'", askID % exits);
  509. NET_EVENT_HANDLER;
  510. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits")
  511. % exits.size()));
  512. ObjectInstanceID choosenExit;
  513. if(impassable)
  514. knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  515. else
  516. {
  517. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, destinationTeleport))
  518. choosenExit = destinationTeleport;
  519. if(!status.channelProbing())
  520. {
  521. vstd::copy_if(exits, vstd::set_inserter(teleportChannelProbingList), [&](ObjectInstanceID id) -> bool
  522. {
  523. return !(vstd::contains(visitableObjs, cb->getObj(id)) || id == choosenExit);
  524. });
  525. }
  526. }
  527. requestActionASAP([=]()
  528. {
  529. answerQuery(askID, choosenExit.getNum());
  530. });
  531. }
  532. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  533. {
  534. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  535. NET_EVENT_HANDLER;
  536. std::string s1 = up ? up->nodeName() : "NONE";
  537. std::string s2 = down ? down->nodeName() : "NONE";
  538. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  539. //you can't request action from action-response thread
  540. requestActionASAP([=]()
  541. {
  542. pickBestCreatures (down, up);
  543. answerQuery(queryID, 0);
  544. });
  545. }
  546. void VCAI::saveGame(COSer & h, const int version)
  547. {
  548. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  549. NET_EVENT_HANDLER;
  550. validateVisitableObjs();
  551. registerGoals(h);
  552. CAdventureAI::saveGame(h, version);
  553. serializeInternal(h, version);
  554. }
  555. void VCAI::loadGame(CISer & h, const int version)
  556. {
  557. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  558. NET_EVENT_HANDLER;
  559. registerGoals(h);
  560. CAdventureAI::loadGame(h, version);
  561. serializeInternal(h, version);
  562. }
  563. void makePossibleUpgrades(const CArmedInstance *obj)
  564. {
  565. if(!obj)
  566. return;
  567. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  568. {
  569. if(const CStackInstance *s = obj->getStackPtr(SlotID(i)))
  570. {
  571. UpgradeInfo ui;
  572. cb->getUpgradeInfo(obj, SlotID(i), ui);
  573. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  574. {
  575. cb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  576. }
  577. }
  578. }
  579. }
  580. void VCAI::makeTurn()
  581. {
  582. MAKING_TURN;
  583. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  584. setThreadName("VCAI::makeTurn");
  585. logGlobal->infoStream() << boost::format("Player %d starting turn") % static_cast<int>(playerID.getNum());
  586. switch(cb->getDate(Date::DAY_OF_WEEK))
  587. {
  588. case 1:
  589. {
  590. townVisitsThisWeek.clear();
  591. std::vector<const CGObjectInstance *> objs;
  592. retreiveVisitableObjs(objs, true);
  593. for(const CGObjectInstance *obj : objs)
  594. {
  595. if (isWeeklyRevisitable(obj))
  596. {
  597. addVisitableObj(obj);
  598. erase_if_present (alreadyVisited, obj);
  599. }
  600. }
  601. }
  602. break;
  603. }
  604. markHeroAbleToExplore (primaryHero());
  605. makeTurnInternal();
  606. makingTurn.reset();
  607. return;
  608. }
  609. void VCAI::makeTurnInternal()
  610. {
  611. saving = 0;
  612. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  613. for(const CGTownInstance *t : cb->getTownsInfo())
  614. moveCreaturesToHero(t);
  615. try
  616. {
  617. //Pick objects reserved in previous turn - we expect only nerby objects there
  618. auto reservedHeroesCopy = reservedHeroesMap; //work on copy => the map may be changed while iterating (eg because hero died when attempting a goal)
  619. for (auto hero : reservedHeroesCopy)
  620. {
  621. if(reservedHeroesMap.count(hero.first))
  622. continue; //hero might have been removed while we were in this loop
  623. if(!hero.first.validAndSet())
  624. {
  625. logAi->errorStream() << "Hero " << hero.first.name << " present on reserved map. Shouldn't be. ";
  626. continue;
  627. }
  628. std::vector<const CGObjectInstance *> vec(hero.second.begin(), hero.second.end());
  629. boost::sort (vec, CDistanceSorter(hero.first.get()));
  630. for (auto obj : vec)
  631. {
  632. if(!obj || !cb->getObj(obj->id))
  633. {
  634. logAi->errorStream() << "Error: there is wrong object on list for hero " << hero.first->name;
  635. continue;
  636. }
  637. striveToGoal (sptr(Goals::VisitTile(obj->visitablePos()).sethero(hero.first)));
  638. }
  639. }
  640. //now try to win
  641. striveToGoal(sptr(Goals::Win()));
  642. //finally, continue our abstract long-term goals
  643. int oldMovement = 0;
  644. int newMovement = 0;
  645. while (true)
  646. {
  647. oldMovement = newMovement; //remember old value
  648. newMovement = 0;
  649. std::vector<std::pair<HeroPtr, Goals::TSubgoal> > safeCopy;
  650. for (auto mission : lockedHeroes)
  651. {
  652. fh->setPriority (mission.second); //re-evaluate
  653. if (canAct(mission.first))
  654. {
  655. newMovement += mission.first->movement;
  656. safeCopy.push_back (mission);
  657. }
  658. }
  659. if (newMovement == oldMovement) //means our heroes didn't move or didn't re-assign their goals
  660. {
  661. logAi->warnStream() << "Our heroes don't move anymore, exhaustive decomposition failed";
  662. break;
  663. }
  664. if (safeCopy.empty())
  665. break; //all heroes exhausted their locked goals
  666. else
  667. {
  668. typedef std::pair<HeroPtr, Goals::TSubgoal> TItrType;
  669. auto lockedHeroesSorter = [](TItrType m1, TItrType m2) -> bool
  670. {
  671. return m1.second->priority < m2.second->priority;
  672. };
  673. boost::sort(safeCopy, lockedHeroesSorter);
  674. striveToGoal (safeCopy.back().second);
  675. }
  676. }
  677. auto quests = myCb->getMyQuests();
  678. for (auto quest : quests)
  679. {
  680. striveToQuest (quest);
  681. }
  682. striveToGoal(sptr(Goals::Build())); //TODO: smarter building management
  683. performTypicalActions();
  684. //for debug purpose
  685. for (auto h : cb->getHeroesInfo())
  686. {
  687. if (h->movement)
  688. logAi->warnStream() << boost::format("hero %s has %d MP left") % h->name % h->movement;
  689. }
  690. }
  691. catch(boost::thread_interrupted &e)
  692. {
  693. logAi->debugStream() << "Making turn thread has been interrupted. We'll end without calling endTurn.";
  694. return;
  695. }
  696. catch(std::exception &e)
  697. {
  698. logAi->debugStream() << "Making turn thread has caught an exception: " << e.what();
  699. }
  700. endTurn();
  701. }
  702. bool VCAI::goVisitObj(const CGObjectInstance * obj, HeroPtr h)
  703. {
  704. int3 dst = obj->visitablePos();
  705. logAi->debugStream() << boost::format("%s will try to visit %s at (%s)") % h->name % obj->getObjectName() % strFromInt3(dst);
  706. return moveHeroToTile(dst, h);
  707. }
  708. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  709. {
  710. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->name % obj->getObjectName() % obj->pos);
  711. switch (obj->ID)
  712. {
  713. case Obj::CREATURE_GENERATOR1:
  714. recruitCreatures (dynamic_cast<const CGDwelling *>(obj), h.get());
  715. checkHeroArmy (h);
  716. break;
  717. case Obj::TOWN:
  718. moveCreaturesToHero (dynamic_cast<const CGTownInstance *>(obj));
  719. if (h->visitedTown) //we are inside, not just attacking
  720. {
  721. townVisitsThisWeek[h].insert(h->visitedTown);
  722. if (!h->hasSpellbook() && cb->getResourceAmount(Res::GOLD) >= GameConstants::SPELLBOOK_GOLD_COST + saving[Res::GOLD] &&
  723. h->visitedTown->hasBuilt (BuildingID::MAGES_GUILD_1))
  724. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  725. }
  726. break;
  727. }
  728. completeGoal (sptr(Goals::GetObj(obj->id.getNum()).sethero(h)));
  729. }
  730. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  731. {
  732. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  733. {
  734. pickBestCreatures (t->visitingHero, t);
  735. }
  736. }
  737. bool VCAI::canGetArmy (const CGHeroInstance * army, const CGHeroInstance * source)
  738. { //TODO: merge with pickBestCreatures
  739. //if (ai->primaryHero().h == source)
  740. if(army->tempOwner != source->tempOwner)
  741. {
  742. logAi->errorStream() << "Why are we even considering exchange between heroes from different players?";
  743. return false;
  744. }
  745. const CArmedInstance *armies[] = {army, source};
  746. //we calculate total strength for each creature type available in armies
  747. std::map<const CCreature*, int> creToPower;
  748. for(auto armyPtr : armies)
  749. for(auto &i : armyPtr->Slots())
  750. {
  751. //TODO: allow splitting stacks?
  752. creToPower[i.second->type] += i.second->getPower();
  753. }
  754. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  755. int armySize = creToPower.size();
  756. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  757. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  758. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  759. {
  760. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  761. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  762. {
  763. return lhs.second < rhs.second;
  764. });
  765. bestArmy.push_back(creIt->first);
  766. creToPower.erase(creIt);
  767. if(creToPower.empty())
  768. break;
  769. }
  770. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  771. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  772. {
  773. for(auto armyPtr : armies)
  774. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  775. {
  776. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && armyPtr != army) //it's a searched creature not in dst ARMY
  777. {
  778. //FIXME: line below is useless when simulating exchange between two non-singular armies
  779. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1)) //can't take away last creature
  780. return true; //at least one exchange will be performed
  781. else
  782. return false; //no further exchange possible
  783. }
  784. }
  785. }
  786. return false;
  787. }
  788. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  789. {
  790. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  791. const CArmedInstance *armies[] = {army, source};
  792. //we calculate total strength for each creature type available in armies
  793. std::map<const CCreature*, int> creToPower;
  794. for(auto armyPtr : armies)
  795. for(auto &i : armyPtr->Slots())
  796. {//TODO: allow splitting stacks?
  797. creToPower[i.second->type] += i.second->getPower();
  798. }
  799. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  800. int armySize = creToPower.size();
  801. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  802. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  803. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  804. {
  805. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  806. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  807. {
  808. return lhs.second < rhs.second;
  809. });
  810. bestArmy.push_back(creIt->first);
  811. creToPower.erase(creIt);
  812. if(creToPower.empty())
  813. break;
  814. }
  815. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  816. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  817. {
  818. for(auto armyPtr : armies)
  819. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  820. {
  821. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst SLOT
  822. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1)) //can't take away last creature
  823. cb->mergeOrSwapStacks(armyPtr, army, SlotID(j), SlotID(i));
  824. }
  825. }
  826. //TODO - having now strongest possible army, we may want to think about arranging stacks
  827. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  828. if (hero)
  829. {
  830. checkHeroArmy (hero);
  831. }
  832. }
  833. void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  834. {
  835. for(int i = 0; i < d->creatures.size(); i++)
  836. {
  837. if(!d->creatures[i].second.size())
  838. continue;
  839. int count = d->creatures[i].first;
  840. CreatureID creID = d->creatures[i].second.back();
  841. // const CCreature *c = VLC->creh->creatures[creID];
  842. // if(containsSavedRes(c->cost))
  843. // continue;
  844. amin(count, freeResources() / VLC->creh->creatures[creID]->cost);
  845. if(count > 0)
  846. cb->recruitCreatures(d, recruiter, creID, count, i);
  847. }
  848. }
  849. bool VCAI::tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays)
  850. {
  851. if (maxDays == 0)
  852. {
  853. logAi->warnStream() << "Request to build building " << building << " in 0 days!";
  854. return false;
  855. }
  856. if (!vstd::contains(t->town->buildings, building))
  857. return false; // no such building in town
  858. if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  859. return true;
  860. const CBuilding * buildPtr = t->town->buildings.at(building);
  861. auto toBuild = buildPtr->requirements.getFulfillmentCandidates([&](const BuildingID & buildID)
  862. {
  863. return t->hasBuilt(buildID);
  864. });
  865. toBuild.push_back(building);
  866. for(BuildingID buildID : toBuild)
  867. {
  868. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  869. if (canBuild == EBuildingState::HAVE_CAPITAL
  870. || canBuild == EBuildingState::FORBIDDEN
  871. || canBuild == EBuildingState::NO_WATER)
  872. return false; //we won't be able to build this
  873. }
  874. if (maxDays && toBuild.size() > maxDays)
  875. return false;
  876. TResources currentRes = cb->getResourceAmount();
  877. //TODO: calculate if we have enough resources to build it in maxDays
  878. for(const auto & buildID : toBuild)
  879. {
  880. const CBuilding *b = t->town->buildings.at(buildID);
  881. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  882. if(canBuild == EBuildingState::ALLOWED)
  883. {
  884. if(!containsSavedRes(b->resources))
  885. {
  886. logAi->debugStream() << boost::format("Player %d will build %s in town of %s at %s") % playerID % b->Name() % t->name % t->pos;
  887. cb->buildBuilding(t, buildID);
  888. return true;
  889. }
  890. continue;
  891. }
  892. else if(canBuild == EBuildingState::NO_RESOURCES)
  893. {
  894. //TResources income = estimateIncome();
  895. TResources cost = t->town->buildings.at(buildID)->resources;
  896. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  897. {
  898. //int diff = currentRes[i] - cost[i] + income[i];
  899. int diff = currentRes[i] - cost[i];
  900. if(diff < 0)
  901. saving[i] = 1;
  902. }
  903. continue;
  904. }
  905. else if (canBuild == EBuildingState::PREREQUIRES)
  906. {
  907. // can happen when dependencies have their own missing dependencies
  908. if (tryBuildStructure(t, buildID, maxDays - 1))
  909. return true;
  910. }
  911. else if (canBuild == EBuildingState::MISSING_BASE)
  912. {
  913. if (tryBuildStructure(t, b->upgrade, maxDays - 1))
  914. return true;
  915. }
  916. }
  917. return false;
  918. }
  919. //bool VCAI::canBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=7)
  920. //{
  921. // if (maxDays == 0)
  922. // {
  923. // logAi->warnStream() << "Request to build building " << building << " in 0 days!";
  924. // return false;
  925. // }
  926. //
  927. // if (!vstd::contains(t->town->buildings, building))
  928. // return false; // no such building in town
  929. //
  930. // if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  931. // return true;
  932. //
  933. // const CBuilding * buildPtr = t->town->buildings.at(building);
  934. //
  935. // auto toBuild = buildPtr->requirements.getFulfillmentCandidates([&](const BuildingID & buildID)
  936. // {
  937. // return t->hasBuilt(buildID);
  938. // });
  939. // toBuild.push_back(building);
  940. //
  941. // for(BuildingID buildID : toBuild)
  942. // {
  943. // EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  944. // if (canBuild == EBuildingState::HAVE_CAPITAL
  945. // || canBuild == EBuildingState::FORBIDDEN
  946. // || canBuild == EBuildingState::NO_WATER)
  947. // return false; //we won't be able to build this
  948. // }
  949. //
  950. // if (maxDays && toBuild.size() > maxDays)
  951. // return false;
  952. //
  953. // TResources currentRes = cb->getResourceAmount();
  954. // TResources income = estimateIncome();
  955. // //TODO: calculate if we have enough resources to build it in maxDays
  956. //
  957. // for(const auto & buildID : toBuild)
  958. // {
  959. // const CBuilding *b = t->town->buildings.at(buildID);
  960. //
  961. // EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  962. // if(canBuild == EBuildingState::ALLOWED)
  963. // {
  964. // if(!containsSavedRes(b->resources))
  965. // {
  966. // logAi->debugStream() << boost::format("Player %d will build %s in town of %s at %s") % playerID % b->Name() % t->name % t->pos;
  967. // return true;
  968. // }
  969. // continue;
  970. // }
  971. // else if(canBuild == EBuildingState::NO_RESOURCES)
  972. // {
  973. // TResources cost = t->town->buildings.at(buildID)->resources;
  974. // for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  975. // {
  976. // int diff = currentRes[i] - cost[i] + income[i];
  977. // if(diff < 0)
  978. // saving[i] = 1;
  979. // }
  980. // continue;
  981. // }
  982. // else if (canBuild == EBuildingState::PREREQUIRES)
  983. // {
  984. // // can happen when dependencies have their own missing dependencies
  985. // if (canBuildStructure(t, buildID, maxDays - 1))
  986. // return true;
  987. // }
  988. // else if (canBuild == EBuildingState::MISSING_BASE)
  989. // {
  990. // if (canBuildStructure(t, b->upgrade, maxDays - 1))
  991. // return true;
  992. // }
  993. // }
  994. // return false;
  995. //}
  996. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  997. {
  998. for(const auto & building : buildList)
  999. {
  1000. if(t->hasBuilt(building))
  1001. continue;
  1002. if (tryBuildStructure(t, building, maxDays))
  1003. return true;
  1004. }
  1005. return false; //Can't build anything
  1006. }
  1007. BuildingID VCAI::canBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  1008. {
  1009. for(const auto & building : buildList)
  1010. {
  1011. if(t->hasBuilt(building))
  1012. continue;
  1013. if (cb->canBuildStructure(t, building))
  1014. return building;
  1015. }
  1016. return BuildingID::NONE; //Can't build anything
  1017. }
  1018. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  1019. {
  1020. for(const auto & building : buildList)
  1021. {
  1022. if(t->hasBuilt(building))
  1023. continue;
  1024. return tryBuildStructure(t, building, maxDays);
  1025. }
  1026. return false;//Nothing to build
  1027. }
  1028. void VCAI::buildStructure(const CGTownInstance * t)
  1029. {
  1030. //TODO make *real* town development system
  1031. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  1032. //TODO: build resource silo, defences when needed
  1033. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  1034. TResources currentRes = cb->getResourceAmount();
  1035. TResources currentIncome = t->dailyIncome();
  1036. int townIncome = currentIncome[Res::GOLD];
  1037. if (tryBuildAnyStructure(t, std::vector<BuildingID>(essential, essential + ARRAY_COUNT(essential))))
  1038. return;
  1039. //we're running out of gold - try to build something gold-producing. Multiplier can be tweaked, 6 is minimum due to buildings costs
  1040. if (currentRes[Res::GOLD] < townIncome * 6)
  1041. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1042. return;
  1043. if (cb->getDate(Date::DAY_OF_WEEK) > 6)// last 2 days of week - try to focus on growth
  1044. {
  1045. if (tryBuildNextStructure(t, std::vector<BuildingID>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  1046. return;
  1047. }
  1048. // first in-game week or second half of any week: try build dwellings
  1049. if (cb->getDate(Date::DAY) < 7 || cb->getDate(Date::DAY_OF_WEEK) > 3)
  1050. if (tryBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK)))
  1051. return;
  1052. //try to upgrade dwelling
  1053. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  1054. {
  1055. if (t->hasBuilt(unitsSource[i]) && !t->hasBuilt(unitsUpgrade[i]))
  1056. {
  1057. if (tryBuildStructure(t, unitsUpgrade[i]))
  1058. return;
  1059. }
  1060. }
  1061. //remaining tasks
  1062. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1063. return;
  1064. if (tryBuildNextStructure(t, std::vector<BuildingID>(spells, spells + ARRAY_COUNT(spells))))
  1065. return;
  1066. if (tryBuildAnyStructure(t, std::vector<BuildingID>(extra, extra + ARRAY_COUNT(extra))))
  1067. return;
  1068. }
  1069. bool VCAI::isGoodForVisit(const CGObjectInstance *obj, HeroPtr h)
  1070. {
  1071. const int3 pos = obj->visitablePos();
  1072. if (isAccessibleForHero(obj->visitablePos(), h) &&
  1073. !obj->wasVisited(playerID) &&
  1074. (cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES || isWeeklyRevisitable(obj)) && //flag or get weekly resources / creatures
  1075. isSafeToVisit(h, pos) &&
  1076. shouldVisit(h, obj) &&
  1077. !vstd::contains(alreadyVisited, obj) &&
  1078. !vstd::contains(reservedObjs, obj))
  1079. {
  1080. const CGObjectInstance *topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
  1081. //we don't try visiting object on which allied or owned hero stands
  1082. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1083. if (topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  1084. return false;
  1085. else
  1086. return true; //all of the following is met
  1087. }
  1088. return false;
  1089. }
  1090. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(HeroPtr h)
  1091. {
  1092. validateVisitableObjs();
  1093. std::vector<const CGObjectInstance *> possibleDestinations;
  1094. for(const CGObjectInstance *obj : visitableObjs)
  1095. {
  1096. if (isGoodForVisit(obj, h))
  1097. {
  1098. possibleDestinations.push_back(obj);
  1099. }
  1100. }
  1101. boost::sort(possibleDestinations, CDistanceSorter(h.get()));
  1102. return possibleDestinations;
  1103. }
  1104. bool VCAI::canReachTile (const CGHeroInstance * h, int3 t)
  1105. {
  1106. if (t.valid())
  1107. {
  1108. auto obj = cb->getTopObj(t);
  1109. if (obj && vstd::contains(ai->reservedObjs, obj) && !vstd::contains(reservedHeroesMap[h], obj))
  1110. return false; //do not capture object reserved by another hero
  1111. else
  1112. return true;
  1113. }
  1114. else
  1115. return false;
  1116. }
  1117. bool VCAI::canRecruitAnyHero (const CGTownInstance * t) const
  1118. {
  1119. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  1120. if (!t)
  1121. t = findTownWithTavern();
  1122. if (t)
  1123. return cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST &&
  1124. cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES &&
  1125. cb->getAvailableHeroes(t).size();
  1126. else
  1127. return false;
  1128. }
  1129. void VCAI::wander(HeroPtr h)
  1130. {
  1131. //unclaim objects that are now dangerous for us
  1132. auto reservedObjsSetCopy = reservedHeroesMap[h];
  1133. for (auto obj : reservedObjsSetCopy)
  1134. {
  1135. if (!isSafeToVisit(h, obj->visitablePos()))
  1136. unreserveObject(h, obj);
  1137. }
  1138. TimeCheck tc("looking for wander destination");
  1139. while (h->movement)
  1140. {
  1141. validateVisitableObjs();
  1142. std::vector <ObjectIdRef> dests, tmp;
  1143. range::copy(reservedHeroesMap[h], std::back_inserter(tmp)); //visit our reserved objects first
  1144. for (auto obj : tmp)
  1145. {
  1146. if (isAccessibleForHero (obj->visitablePos(), h)) //even nearby objects could be blocked by other heroes :(
  1147. dests.push_back(obj); //can't use lambda for member function :(
  1148. }
  1149. if (!dests.size())
  1150. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  1151. if(!dests.size())
  1152. {
  1153. if (cb->getVisitableObjs(h->visitablePos()).size() > 1)
  1154. moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
  1155. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  1156. {
  1157. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1158. };
  1159. std::vector<const CGTownInstance *> townsReachable;
  1160. std::vector<const CGTownInstance *> townsNotReachable;
  1161. for(const CGTownInstance *t : cb->getTownsInfo())
  1162. {
  1163. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  1164. {
  1165. if (isAccessibleForHero (t->visitablePos(), h))
  1166. townsReachable.push_back(t);
  1167. else
  1168. townsNotReachable.push_back(t);
  1169. }
  1170. }
  1171. if(townsReachable.size())
  1172. {
  1173. boost::sort(townsReachable, compareReinforcements);
  1174. dests.push_back(townsReachable.back());
  1175. }
  1176. else if(townsNotReachable.size())
  1177. {
  1178. boost::sort(townsNotReachable, compareReinforcements);
  1179. //TODO pick the truly best
  1180. const CGTownInstance *t = townsNotReachable.back();
  1181. 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();
  1182. int3 pos1 = h->pos;
  1183. striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h)));
  1184. //if out hero is stuck, we may need to request another hero to clear the way we see
  1185. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  1186. {
  1187. if (canRecruitAnyHero(t))
  1188. recruitHero(t);
  1189. }
  1190. break;
  1191. }
  1192. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  1193. {
  1194. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1195. erase_if(towns, [](const CGTownInstance *t) -> bool
  1196. {
  1197. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1198. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1199. return true;
  1200. return false;
  1201. });
  1202. boost::sort(towns, compareArmyStrength);
  1203. if(towns.size())
  1204. recruitHero(towns.back());
  1205. break;
  1206. }
  1207. else
  1208. {
  1209. logAi->debugStream() << "Nowhere more to go...";
  1210. break;
  1211. }
  1212. }
  1213. //end of objs empty
  1214. while (dests.size()) //performance improvement
  1215. {
  1216. //wander should not cause heroes to be reserved - they are always considered free
  1217. const ObjectIdRef&dest = dests.front();
  1218. logAi->debugStream() << boost::format("Of all %d destinations, object oid=%d seems nice") % dests.size() % dest.id.getNum();
  1219. if(!goVisitObj(dest, h))
  1220. {
  1221. if(!dest)
  1222. {
  1223. logAi->debugStream() << boost::format("Visit attempt made the object (id=%d) gone...") % dest.id.getNum();
  1224. }
  1225. else
  1226. {
  1227. logAi->debugStream() << boost::format("Hero %s apparently used all MPs (%d left)") % h->name % h->movement;
  1228. return;
  1229. }
  1230. }
  1231. //TODO: refactor removing deleted objects from the list
  1232. std::vector<const CGObjectInstance *> hlp;
  1233. retreiveVisitableObjs(hlp, true);
  1234. auto shouldBeErased = [&](const CGObjectInstance *obj) -> bool
  1235. {
  1236. if(!vstd::contains(hlp, obj))
  1237. {
  1238. return true;
  1239. }
  1240. return false;
  1241. };
  1242. erase_if(dests, shouldBeErased);
  1243. erase_if_present(dests, dest); //why that fails sometimes when removing monsters?
  1244. boost::sort(dests, CDistanceSorter(h.get())); //find next closest one
  1245. }
  1246. if (h->visitedTown)
  1247. {
  1248. townVisitsThisWeek[h].insert(h->visitedTown);
  1249. buildArmyIn(h->visitedTown);
  1250. }
  1251. }
  1252. }
  1253. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1254. { //TODO: check for presence?
  1255. if (goal->invalid())
  1256. erase_if_present(lockedHeroes, h);
  1257. else
  1258. {
  1259. lockedHeroes[h] = goal;
  1260. goal->setisElementar(false); //always evaluate goals before realizing
  1261. }
  1262. }
  1263. void VCAI::completeGoal (Goals::TSubgoal goal)
  1264. {
  1265. logAi->traceStream() << boost::format("Completing goal: %s") % goal->name();
  1266. if (const CGHeroInstance * h = goal->hero.get(true))
  1267. {
  1268. auto it = lockedHeroes.find(h);
  1269. if (it != lockedHeroes.end())
  1270. if (it->second == goal)
  1271. {
  1272. logAi->debugStream() << boost::format("%s") % goal->completeMessage();
  1273. lockedHeroes.erase(it); //goal fulfilled, free hero
  1274. }
  1275. }
  1276. else //complete goal for all heroes maybe?
  1277. {
  1278. vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
  1279. {
  1280. if (*(p.second) == *goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1281. {
  1282. logAi->debugStream() << boost::format("%s") % p.second->completeMessage();
  1283. return true;
  1284. }
  1285. return false;
  1286. });
  1287. }
  1288. }
  1289. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1290. {
  1291. NET_EVENT_HANDLER;
  1292. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1293. status.setBattle(ONGOING_BATTLE);
  1294. 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
  1295. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile);
  1296. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1297. }
  1298. void VCAI::battleEnd(const BattleResult *br)
  1299. {
  1300. NET_EVENT_HANDLER;
  1301. assert(status.getBattle() == ONGOING_BATTLE);
  1302. status.setBattle(ENDING_BATTLE);
  1303. bool won = br->winner == myCb->battleGetMySide();
  1304. logAi->debugStream() << boost::format("Player %d: I %s the %s!") % playerID % (won ? "won" : "lost") % battlename;
  1305. battlename.clear();
  1306. CAdventureAI::battleEnd(br);
  1307. }
  1308. void VCAI::waitTillFree()
  1309. {
  1310. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1311. status.waitTillFree();
  1312. }
  1313. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1314. {
  1315. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1316. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1317. (obj->ID == Obj::MONSTER))
  1318. return;
  1319. alreadyVisited.insert(obj);
  1320. }
  1321. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj)
  1322. {
  1323. reservedObjs.insert(obj);
  1324. reservedHeroesMap[h].insert(obj);
  1325. logAi->debugStream() << "reserved object id=" << obj->id << "; address=" << (intptr_t)obj << "; name=" << obj->getObjectName();
  1326. }
  1327. void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance *obj)
  1328. {
  1329. erase_if_present(reservedObjs, obj); //unreserve objects
  1330. erase_if_present(reservedHeroesMap[h], obj);
  1331. }
  1332. void VCAI::markHeroUnableToExplore (HeroPtr h)
  1333. {
  1334. heroesUnableToExplore.insert(h);
  1335. }
  1336. void VCAI::markHeroAbleToExplore (HeroPtr h)
  1337. {
  1338. erase_if_present(heroesUnableToExplore, h);
  1339. }
  1340. bool VCAI::isAbleToExplore (HeroPtr h)
  1341. {
  1342. return !vstd::contains (heroesUnableToExplore, h);
  1343. }
  1344. void VCAI::clearHeroesUnableToExplore()
  1345. {
  1346. heroesUnableToExplore.clear();
  1347. }
  1348. void VCAI::validateVisitableObjs()
  1349. {
  1350. std::vector<const CGObjectInstance *> hlp;
  1351. retreiveVisitableObjs(hlp, true);
  1352. std::string errorMsg;
  1353. auto shouldBeErased = [&](const CGObjectInstance *obj) -> bool
  1354. {
  1355. if(!vstd::contains(hlp, obj))
  1356. {
  1357. logAi->errorStream() << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << errorMsg;
  1358. return true;
  1359. }
  1360. return false;
  1361. };
  1362. //errorMsg is captured by ref so lambda will take the new text
  1363. errorMsg = " shouldn't be on the visitable objects list!";
  1364. erase_if(visitableObjs, shouldBeErased);
  1365. //FIXME: how comes our own heroes become inaccessible?
  1366. erase_if(reservedHeroesMap, [](std::pair<HeroPtr, std::set<const CGObjectInstance *>> hp) -> bool
  1367. {
  1368. return !hp.first.get(true);
  1369. });
  1370. for(auto &p : reservedHeroesMap)
  1371. {
  1372. errorMsg = " shouldn't be on list for hero " + p.first->name + "!";
  1373. erase_if(p.second, shouldBeErased);
  1374. }
  1375. errorMsg = " shouldn't be on the reserved objs list!";
  1376. erase_if(reservedObjs, shouldBeErased);
  1377. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1378. errorMsg = " shouldn't be on the already visited objs list!";
  1379. erase_if(alreadyVisited, shouldBeErased);
  1380. }
  1381. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1382. {
  1383. foreach_tile_pos([&](const int3 &pos)
  1384. {
  1385. for(const CGObjectInstance *obj : myCb->getVisitableObjs(pos, false))
  1386. {
  1387. if(includeOwned || obj->tempOwner != playerID)
  1388. out.push_back(obj);
  1389. }
  1390. });
  1391. }
  1392. void VCAI::retreiveVisitableObjs()
  1393. {
  1394. foreach_tile_pos([&](const int3 &pos)
  1395. {
  1396. for(const CGObjectInstance *obj : myCb->getVisitableObjs(pos, false))
  1397. {
  1398. if(obj->tempOwner != playerID)
  1399. addVisitableObj(obj);
  1400. }
  1401. });
  1402. }
  1403. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1404. {
  1405. std::vector<const CGObjectInstance *> ret;
  1406. retreiveVisitableObjs(ret, true);
  1407. erase_if(ret, [](const CGObjectInstance *obj)
  1408. {
  1409. return obj->tempOwner != ai->playerID;
  1410. });
  1411. return ret;
  1412. }
  1413. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1414. {
  1415. visitableObjs.insert(obj);
  1416. helperObjInfo[obj] = ObjInfo(obj);
  1417. // All teleport objects seen automatically assigned to appropriate channels
  1418. auto teleportObj = dynamic_cast<const CGTeleport *>(obj);
  1419. if(teleportObj)
  1420. CGTeleport::addToChannel(knownTeleportChannels, teleportObj);
  1421. }
  1422. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1423. {
  1424. for(const CGObjectInstance *obj : ai->visitableObjs)
  1425. {
  1426. if(obj->ID == 5 && obj->subID == aid)
  1427. return obj;
  1428. }
  1429. return nullptr;
  1430. //TODO what if more than one artifact is available? return them all or some slection criteria
  1431. }
  1432. bool VCAI::isAccessible(const int3 &pos)
  1433. {
  1434. //TODO precalculate for speed
  1435. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1436. {
  1437. if(isAccessibleForHero(pos, h))
  1438. return true;
  1439. }
  1440. return false;
  1441. }
  1442. HeroPtr VCAI::getHeroWithGrail() const
  1443. {
  1444. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1445. if(h->hasArt(2)) //grail
  1446. return h;
  1447. return nullptr;
  1448. }
  1449. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> &predicate)
  1450. {
  1451. //TODO smarter definition of unvisited
  1452. for(const CGObjectInstance *obj : visitableObjs)
  1453. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1454. return obj;
  1455. return nullptr;
  1456. }
  1457. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies /*= false*/) const
  1458. {
  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 &&
  1464. cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES &&
  1465. obj != h.get())
  1466. return false;
  1467. }
  1468. }
  1469. return cb->getPathsInfo(h.get())->getPathInfo(pos)->reachable();
  1470. }
  1471. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1472. {
  1473. auto afterMovementCheck = [&]() -> void
  1474. {
  1475. waitTillFree(); //movement may cause battle or blocking dialog
  1476. if(!h)
  1477. {
  1478. lostHero(h);
  1479. teleportChannelProbingList.clear();
  1480. if (status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  1481. status.setChannelProbing(false);
  1482. throw cannotFulfillGoalException("Hero was lost!");
  1483. }
  1484. };
  1485. logAi->debugStream() << boost::format("Moving hero %s to tile %s") % h->name % dst;
  1486. int3 startHpos = h->visitablePos();
  1487. bool ret = false;
  1488. if(startHpos == dst)
  1489. {
  1490. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1491. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1492. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1493. afterMovementCheck();// TODO: is it feasible to hero get killed there if game work properly?
  1494. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1495. ret = true;
  1496. }
  1497. else
  1498. {
  1499. CGPath path;
  1500. cb->getPathsInfo(h.get())->getPath(dst, path);
  1501. if(path.nodes.empty())
  1502. {
  1503. logAi->errorStream() << "Hero " << h->name << " cannot reach " << dst;
  1504. throw goalFulfilledException (sptr(Goals::VisitTile(dst).sethero(h)));
  1505. }
  1506. auto getObj = [&](int3 coord, bool ignoreHero)
  1507. {
  1508. return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
  1509. };
  1510. auto doMovement = [&](int3 dst, bool transit)
  1511. {
  1512. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true), transit);
  1513. };
  1514. auto doTeleportMovement = [&](int3 dst, ObjectInstanceID exitId)
  1515. {
  1516. destinationTeleport = exitId;
  1517. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1518. destinationTeleport = ObjectInstanceID();
  1519. afterMovementCheck();
  1520. };
  1521. auto doChannelProbing = [&]() -> void
  1522. {
  1523. auto currentExit = getObj(CGHeroInstance::convertPosition(h->pos,false), false);
  1524. assert(currentExit);
  1525. status.setChannelProbing(true);
  1526. for(auto exit : teleportChannelProbingList)
  1527. doTeleportMovement(CGHeroInstance::convertPosition(h->pos,false), exit);
  1528. teleportChannelProbingList.clear();
  1529. doTeleportMovement(CGHeroInstance::convertPosition(h->pos,false), currentExit->id);
  1530. status.setChannelProbing(false);
  1531. };
  1532. int i=path.nodes.size()-1;
  1533. for(; i>0; i--)
  1534. {
  1535. int3 currentCoord = path.nodes[i].coord;
  1536. int3 nextCoord = path.nodes[i-1].coord;
  1537. auto currentObject = getObj(currentCoord, currentCoord == CGHeroInstance::convertPosition(h->pos,false));
  1538. auto nextObject = getObj(nextCoord, false);
  1539. if(CGTeleport::isConnected(currentObject, nextObject))
  1540. { //we use special login if hero standing on teleporter it's mean we need
  1541. doTeleportMovement(currentCoord, nextObject->id);
  1542. if(teleportChannelProbingList.size())
  1543. doChannelProbing();
  1544. continue;
  1545. }
  1546. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1547. if(path.nodes[i-1].turns)
  1548. {
  1549. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1550. break;
  1551. }
  1552. int3 endpos = path.nodes[i-1].coord;
  1553. if(endpos == h->visitablePos())
  1554. continue;
  1555. if((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless
  1556. && (CGTeleport::isConnected(nextObject, getObj(path.nodes[i-2].coord, false))
  1557. || CGTeleport::isTeleport(nextObject)))
  1558. { // Hero should be able to go through object if it's allow transit
  1559. doMovement(endpos, true);
  1560. }
  1561. else
  1562. doMovement(endpos, false);
  1563. afterMovementCheck();
  1564. if(teleportChannelProbingList.size())
  1565. doChannelProbing();
  1566. }
  1567. ret = !i;
  1568. }
  1569. if (h)
  1570. {
  1571. if (auto visitedObject = frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1572. {
  1573. if (visitedObject != *h)
  1574. performObjectInteraction (visitedObject, h);
  1575. }
  1576. }
  1577. if(h) //we could have lost hero after last move
  1578. {
  1579. completeGoal (sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
  1580. if (!ret) //reserve object we are heading towards
  1581. {
  1582. auto obj = frontOrNull(cb->getVisitableObjs(dst));
  1583. if (obj && obj != *h)
  1584. reserveObject(h, obj);
  1585. }
  1586. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1587. {
  1588. erase_if_present (lockedHeroes, h); //hero seemingly is confused
  1589. throw cannotFulfillGoalException("Invalid path found!"); //FIXME: should never happen
  1590. }
  1591. logAi->debugStream() << boost::format("Hero %s moved from %s to %s. Returning %d.") % h->name % startHpos % h->visitablePos() % ret;
  1592. }
  1593. return ret;
  1594. }
  1595. void VCAI::tryRealize(Goals::Explore & g)
  1596. {
  1597. throw cannotFulfillGoalException("EXPLORE is not a elementar goal!");
  1598. }
  1599. void VCAI::tryRealize(Goals::RecruitHero & g)
  1600. {
  1601. if(const CGTownInstance *t = findTownWithTavern())
  1602. {
  1603. recruitHero(t, true);
  1604. //TODO try to free way to blocked town
  1605. //TODO: adventure map tavern or prison?
  1606. }
  1607. }
  1608. void VCAI::tryRealize(Goals::VisitTile & g)
  1609. {
  1610. if(!g.hero->movement)
  1611. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1612. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1613. {
  1614. logAi->warnStream() << boost::format("Why do I want to move hero %s to tile %s? Already standing on that tile! ")
  1615. % g.hero->name % g.tile;
  1616. throw goalFulfilledException (sptr(g));
  1617. }
  1618. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1619. {
  1620. throw goalFulfilledException (sptr(g));
  1621. }
  1622. }
  1623. void VCAI::tryRealize(Goals::VisitHero & g)
  1624. {
  1625. if(!g.hero->movement)
  1626. throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
  1627. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
  1628. if (obj)
  1629. {
  1630. if (ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
  1631. {
  1632. throw goalFulfilledException (sptr(g));
  1633. }
  1634. }
  1635. else
  1636. throw cannotFulfillGoalException("Cannot visit hero: object not found!");
  1637. }
  1638. void VCAI::tryRealize(Goals::BuildThis & g)
  1639. {
  1640. const CGTownInstance *t = g.town;
  1641. if(!t && g.hero)
  1642. t = g.hero->visitedTown;
  1643. if(!t)
  1644. {
  1645. for(const CGTownInstance *t : cb->getTownsInfo())
  1646. {
  1647. switch(cb->canBuildStructure(t, BuildingID(g.bid)))
  1648. {
  1649. case EBuildingState::ALLOWED:
  1650. cb->buildBuilding(t, BuildingID(g.bid));
  1651. return;
  1652. default:
  1653. break;
  1654. }
  1655. }
  1656. }
  1657. else if(cb->canBuildStructure(t, BuildingID(g.bid)) == EBuildingState::ALLOWED)
  1658. {
  1659. cb->buildBuilding(t, BuildingID(g.bid));
  1660. return;
  1661. }
  1662. throw cannotFulfillGoalException("Cannot build a given structure!");
  1663. }
  1664. void VCAI::tryRealize(Goals::DigAtTile & g)
  1665. {
  1666. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1667. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1668. {
  1669. cb->dig(g.hero.get());
  1670. completeGoal(sptr(g)); // finished digging
  1671. }
  1672. else
  1673. {
  1674. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1675. throw cannotFulfillGoalException("A hero can't dig!\n");
  1676. }
  1677. }
  1678. void VCAI::tryRealize(Goals::CollectRes & g)
  1679. {
  1680. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1681. throw cannotFulfillGoalException("Goal is already fulfilled!");
  1682. if(const CGObjectInstance *obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1683. {
  1684. if(const IMarket *m = IMarket::castFrom(obj, false))
  1685. {
  1686. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1687. {
  1688. if(i == g.resID) continue;
  1689. int toGive, toGet;
  1690. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1691. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1692. //TODO trade only as much as needed
  1693. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1694. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1695. return;
  1696. }
  1697. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1698. }
  1699. else
  1700. {
  1701. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1702. }
  1703. }
  1704. else
  1705. {
  1706. saving[g.resID] = 1;
  1707. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1708. }
  1709. }
  1710. void VCAI::tryRealize(Goals::Build & g)
  1711. {
  1712. for(const CGTownInstance *t : cb->getTownsInfo())
  1713. {
  1714. logAi->debugStream() << boost::format("Looking into %s") % t->name;
  1715. buildStructure(t);
  1716. buildArmyIn(t);
  1717. if(!ai->primaryHero() ||
  1718. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  1719. {
  1720. recruitHero(t);
  1721. buildArmyIn(t);
  1722. }
  1723. }
  1724. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1725. }
  1726. void VCAI::tryRealize(Goals::Invalid & g)
  1727. {
  1728. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1729. }
  1730. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1731. {
  1732. logAi->debugStream() << boost::format("Attempting realizing goal with code %s") % g.name();
  1733. throw cannotFulfillGoalException("Unknown type of goal !");
  1734. }
  1735. const CGTownInstance * VCAI::findTownWithTavern() const
  1736. {
  1737. for(const CGTownInstance *t : cb->getTownsInfo())
  1738. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1739. return t;
  1740. return nullptr;
  1741. }
  1742. Goals::TSubgoal VCAI::getGoal (HeroPtr h) const
  1743. {
  1744. auto it = lockedHeroes.find(h);
  1745. if (it != lockedHeroes.end())
  1746. return it->second;
  1747. else
  1748. return sptr(Goals::Invalid());
  1749. }
  1750. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1751. {
  1752. std::vector<HeroPtr> ret;
  1753. for (auto h : cb->getHeroesInfo())
  1754. {
  1755. //&& !vstd::contains(lockedHeroes, h)
  1756. //at this point we assume heroes exhausted their locked goals
  1757. if (canAct(h))
  1758. ret.push_back(h);
  1759. }
  1760. return ret;
  1761. }
  1762. bool VCAI::canAct (HeroPtr h) const
  1763. {
  1764. auto mission = lockedHeroes.find(h);
  1765. if (mission != lockedHeroes.end())
  1766. {
  1767. //FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
  1768. if (mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
  1769. return false;
  1770. }
  1771. return h->movement;
  1772. }
  1773. HeroPtr VCAI::primaryHero() const
  1774. {
  1775. auto hs = cb->getHeroesInfo();
  1776. boost::sort(hs, compareHeroStrength);
  1777. if(hs.empty())
  1778. return nullptr;
  1779. return hs.back();
  1780. }
  1781. void VCAI::endTurn()
  1782. {
  1783. logAi->infoStream() << "Player " << static_cast<int>(playerID.getNum()) << " ends turn";
  1784. if(!status.haveTurn())
  1785. {
  1786. logAi->errorStream() << "Not having turn at the end of turn???";
  1787. }
  1788. logAi->debugStream() << "Resources at the end of turn: " << cb->getResourceAmount();
  1789. do
  1790. {
  1791. cb->endTurn();
  1792. } 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
  1793. logGlobal->infoStream() << "Player " << static_cast<int>(playerID.getNum()) << " ended turn";
  1794. }
  1795. void VCAI::striveToGoal(Goals::TSubgoal ultimateGoal)
  1796. {
  1797. if (ultimateGoal->invalid())
  1798. return;
  1799. //we are looking for abstract goals
  1800. auto abstractGoal = striveToGoalInternal (ultimateGoal, false);
  1801. if (abstractGoal->invalid())
  1802. return;
  1803. //we received abstract goal, need to find concrete goals
  1804. striveToGoalInternal (abstractGoal, true);
  1805. //TODO: save abstract goals not related to hero
  1806. }
  1807. Goals::TSubgoal VCAI::striveToGoalInternal(Goals::TSubgoal ultimateGoal, bool onlyAbstract)
  1808. {
  1809. const int searchDepth = 30;
  1810. const int searchDepth2 = searchDepth-2;
  1811. Goals::TSubgoal abstractGoal = sptr(Goals::Invalid());
  1812. while(1)
  1813. {
  1814. Goals::TSubgoal goal = ultimateGoal;
  1815. logAi->debugStream() << boost::format("Striving to goal of type %s") % ultimateGoal->name();
  1816. int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
  1817. while(!goal->isElementar && maxGoals && (onlyAbstract || !goal->isAbstract))
  1818. {
  1819. logAi->debugStream() << boost::format("Considering goal %s") % goal->name();
  1820. try
  1821. {
  1822. boost::this_thread::interruption_point();
  1823. goal = goal->whatToDoToAchieve();
  1824. --maxGoals;
  1825. if (*goal == *ultimateGoal) //compare objects by value
  1826. throw cannotFulfillGoalException("Goal dependency loop detected!");
  1827. }
  1828. catch(goalFulfilledException &e)
  1829. {
  1830. //it is impossible to continue some goals (like exploration, for example)
  1831. completeGoal (goal);
  1832. logAi->debugStream() << boost::format("Goal %s decomposition failed: goal was completed as much as possible") % goal->name();
  1833. return sptr(Goals::Invalid());
  1834. }
  1835. catch(std::exception &e)
  1836. {
  1837. logAi->debugStream() << boost::format("Goal %s decomposition failed: %s") % goal->name() % e.what();
  1838. return sptr(Goals::Invalid());
  1839. }
  1840. }
  1841. try
  1842. {
  1843. boost::this_thread::interruption_point();
  1844. if (!maxGoals)
  1845. {
  1846. std::runtime_error e("Too many subgoals, don't know what to do");
  1847. throw (e);
  1848. }
  1849. if (goal->hero) //lock this hero to fulfill ultimate goal
  1850. {
  1851. if (maxGoals)
  1852. {
  1853. setGoal(goal->hero, goal);
  1854. }
  1855. else
  1856. {
  1857. erase_if_present (lockedHeroes, goal->hero); // we seemingly don't know what to do with hero
  1858. }
  1859. }
  1860. if (goal->isAbstract)
  1861. {
  1862. abstractGoal = goal; //allow only one abstract goal per call
  1863. logAi->debugStream() << boost::format("Choosing abstract goal %s") % goal->name();
  1864. break;
  1865. }
  1866. else
  1867. {
  1868. logAi->debugStream() << boost::format("Trying to realize %s (value %2.3f)") % goal->name() % goal->priority;
  1869. goal->accept(this);
  1870. }
  1871. boost::this_thread::interruption_point();
  1872. }
  1873. catch(boost::thread_interrupted &e)
  1874. {
  1875. logAi->debugStream() << boost::format("Player %d: Making turn thread received an interruption!") % playerID;
  1876. throw; //rethrow, we want to truly end this thread
  1877. }
  1878. catch(goalFulfilledException &e)
  1879. {
  1880. //the goal was completed successfully
  1881. completeGoal (goal);
  1882. //completed goal was main goal //TODO: find better condition
  1883. if (ultimateGoal->fulfillsMe(goal) || maxGoals > searchDepth2)
  1884. return sptr(Goals::Invalid());
  1885. }
  1886. catch(std::exception &e)
  1887. {
  1888. logAi->debugStream() << boost::format("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.") % goal->name() % ultimateGoal->name();
  1889. logAi->debugStream() << boost::format("The error message was: %s") % e.what();
  1890. break;
  1891. }
  1892. }
  1893. return abstractGoal;
  1894. }
  1895. void VCAI::striveToQuest (const QuestInfo &q)
  1896. {
  1897. if (q.quest->missionType && q.quest->progress != CQuest::COMPLETE)
  1898. {
  1899. MetaString ms;
  1900. q.quest->getRolloverText(ms, false);
  1901. logAi->debugStream() << boost::format("Trying to realize quest: %s") % ms.toString();
  1902. auto heroes = cb->getHeroesInfo();
  1903. switch (q.quest->missionType)
  1904. {
  1905. case CQuest::MISSION_ART:
  1906. {
  1907. for (auto hero : heroes) //TODO: remove duplicated code?
  1908. {
  1909. if (q.quest->checkQuest(hero))
  1910. {
  1911. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1912. return;
  1913. }
  1914. }
  1915. for (auto art : q.quest->m5arts)
  1916. {
  1917. striveToGoal (sptr(Goals::GetArtOfType(art))); //TODO: transport?
  1918. }
  1919. break;
  1920. }
  1921. case CQuest::MISSION_HERO:
  1922. {
  1923. //striveToGoal (CGoal(RECRUIT_HERO));
  1924. for (auto hero : heroes)
  1925. {
  1926. if (q.quest->checkQuest(hero))
  1927. {
  1928. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1929. return;
  1930. }
  1931. }
  1932. striveToGoal (sptr(Goals::FindObj(Obj::PRISON))); //rule of a thumb - quest heroes usually are locked in prisons
  1933. //BNLOG ("Don't know how to recruit hero with id %d\n", q.quest->m13489val);
  1934. break;
  1935. }
  1936. case CQuest::MISSION_ARMY:
  1937. {
  1938. for (auto hero : heroes)
  1939. {
  1940. if (q.quest->checkQuest(hero)) //very bad info - stacks can be split between multiple heroes :(
  1941. {
  1942. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1943. return;
  1944. }
  1945. }
  1946. for (auto creature : q.quest->m6creatures)
  1947. {
  1948. striveToGoal (sptr(Goals::GatherTroops(creature.type->idNumber, creature.count)));
  1949. }
  1950. //TODO: exchange armies... oh my
  1951. //BNLOG ("Don't know how to recruit %d of %s\n", (int)(creature.count) % creature.type->namePl);
  1952. break;
  1953. }
  1954. case CQuest::MISSION_RESOURCES:
  1955. {
  1956. if (heroes.size())
  1957. {
  1958. if (q.quest->checkQuest(heroes.front())) //it doesn't matter which hero it is
  1959. {
  1960. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum())));
  1961. }
  1962. else
  1963. {
  1964. for (int i = 0; i < q.quest->m7resources.size(); ++i)
  1965. {
  1966. if (q.quest->m7resources[i])
  1967. striveToGoal (sptr(Goals::CollectRes(i, q.quest->m7resources[i])));
  1968. }
  1969. }
  1970. }
  1971. else
  1972. striveToGoal (sptr(Goals::RecruitHero())); //FIXME: checkQuest requires any hero belonging to player :(
  1973. break;
  1974. }
  1975. case CQuest::MISSION_KILL_HERO:
  1976. case CQuest::MISSION_KILL_CREATURE:
  1977. {
  1978. auto obj = cb->getObjByQuestIdentifier(q.quest->m13489val);
  1979. if (obj)
  1980. striveToGoal (sptr(Goals::GetObj(obj->id.getNum())));
  1981. else
  1982. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()))); //visit seer hut
  1983. break;
  1984. }
  1985. case CQuest::MISSION_PRIMARY_STAT:
  1986. {
  1987. auto heroes = cb->getHeroesInfo();
  1988. for (auto hero : heroes)
  1989. {
  1990. if (q.quest->checkQuest(hero))
  1991. {
  1992. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1993. return;
  1994. }
  1995. }
  1996. for (int i = 0; i < q.quest->m2stats.size(); ++i)
  1997. {
  1998. logAi->debugStream() << boost::format("Don't know how to increase primary stat %d") % i;
  1999. }
  2000. break;
  2001. }
  2002. case CQuest::MISSION_LEVEL:
  2003. {
  2004. auto heroes = cb->getHeroesInfo();
  2005. for (auto hero : heroes)
  2006. {
  2007. if (q.quest->checkQuest(hero))
  2008. {
  2009. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero))); //TODO: causes infinite loop :/
  2010. return;
  2011. }
  2012. }
  2013. logAi->debugStream() << boost::format("Don't know how to reach hero level %d") % q.quest->m13489val;
  2014. break;
  2015. }
  2016. case CQuest::MISSION_PLAYER:
  2017. {
  2018. if (playerID.getNum() != q.quest->m13489val)
  2019. logAi->debugStream() << boost::format("Can't be player of color %d") % q.quest->m13489val;
  2020. break;
  2021. }
  2022. case CQuest::MISSION_KEYMASTER:
  2023. {
  2024. striveToGoal (sptr(Goals::FindObj(Obj::KEYMASTER, q.obj->subID)));
  2025. break;
  2026. }
  2027. }
  2028. }
  2029. }
  2030. void VCAI::performTypicalActions()
  2031. {
  2032. for(auto h : getUnblockedHeroes())
  2033. {
  2034. logAi->debugStream() << boost::format("Looking into %s, MP=%d") % h->name.c_str() % h->movement;
  2035. makePossibleUpgrades(*h);
  2036. try
  2037. {
  2038. wander(h);
  2039. }
  2040. catch(std::exception &e)
  2041. {
  2042. logAi->debugStream() << boost::format("Cannot use this hero anymore, received exception: %s") % e.what();
  2043. continue;
  2044. }
  2045. }
  2046. }
  2047. void VCAI::buildArmyIn(const CGTownInstance * t)
  2048. {
  2049. makePossibleUpgrades(t->visitingHero);
  2050. makePossibleUpgrades(t);
  2051. recruitCreatures(t, t->getUpperArmy());
  2052. moveCreaturesToHero(t);
  2053. }
  2054. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  2055. {
  2056. std::map<int3, int> dstToRevealedTiles;
  2057. for(crint3 dir : dirs)
  2058. if(cb->isInTheMap(hpos+dir))
  2059. if (isSafeToVisit(h, hpos + dir) && isAccessibleForHero (hpos + dir, h))
  2060. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir);
  2061. if (dstToRevealedTiles.empty()) //yes, it DID happen!
  2062. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2063. auto best = dstToRevealedTiles.begin();
  2064. for (auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  2065. {
  2066. const CGPathNode *pn = cb->getPathsInfo(h.get())->getPathInfo(i->first);
  2067. //const TerrainTile *t = cb->getTile(i->first);
  2068. if(best->second < i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  2069. best = i;
  2070. }
  2071. if(best->second)
  2072. return best->first;
  2073. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2074. }
  2075. int3 VCAI::explorationNewPoint(HeroPtr h)
  2076. {
  2077. //logAi->debugStream() << "Looking for an another place for exploration...";
  2078. int radius = h->getSightRadious();
  2079. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow]
  2080. tiles.resize(radius);
  2081. CCallback * cbp = cb.get();
  2082. foreach_tile_pos([&](const int3 &pos)
  2083. {
  2084. if(!cbp->isVisible(pos))
  2085. tiles[0].push_back(pos);
  2086. });
  2087. float bestValue = 0; //discovered tile to node distance ratio
  2088. int3 bestTile(-1,-1,-1);
  2089. for (int i = 1; i < radius; i++)
  2090. {
  2091. getVisibleNeighbours(tiles[i-1], tiles[i]);
  2092. removeDuplicates(tiles[i]);
  2093. for(const int3 &tile : tiles[i])
  2094. {
  2095. if (!cb->getPathsInfo(h.get())->getPathInfo(tile)->reachable()) //this will remove tiles that are guarded by monsters (or removable objects)
  2096. continue;
  2097. CGPath path;
  2098. cb->getPathsInfo(h.get())->getPath(tile, path);
  2099. float ourValue = (float)howManyTilesWillBeDiscovered(tile, radius, cbp) / (path.nodes.size() + 1); //+1 prevents erratic jumps
  2100. if (ourValue > bestValue) //avoid costly checks of tiles that don't reveal much
  2101. {
  2102. if(isSafeToVisit(h, tile) && !isBlockedBorderGate(tile))
  2103. {
  2104. bestTile = tile;
  2105. bestValue = ourValue;
  2106. }
  2107. }
  2108. }
  2109. }
  2110. return bestTile;
  2111. }
  2112. int3 VCAI::explorationDesperate(HeroPtr h)
  2113. {
  2114. //logAi->debugStream() << "Looking for an another place for exploration...";
  2115. SectorMap sm(h);
  2116. int radius = h->getSightRadious();
  2117. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow]
  2118. tiles.resize(radius);
  2119. CCallback * cbp = cb.get();
  2120. foreach_tile_pos([&](const int3 &pos)
  2121. {
  2122. if(!cbp->isVisible(pos))
  2123. tiles[0].push_back(pos);
  2124. });
  2125. ui64 lowestDanger = -1;
  2126. int3 bestTile(-1,-1,-1);
  2127. for (int i = 1; i < radius; i++)
  2128. {
  2129. getVisibleNeighbours(tiles[i-1], tiles[i]);
  2130. removeDuplicates(tiles[i]);
  2131. for(const int3 &tile : tiles[i])
  2132. {
  2133. if (cbp->getTile(tile)->blocked) //does it shorten the time?
  2134. continue;
  2135. if (!howManyTilesWillBeDiscovered(tile, radius, cbp)) //avoid costly checks of tiles that don't reveal much
  2136. continue;
  2137. auto t = sm.firstTileToGet(h, tile);
  2138. if (t.valid())
  2139. {
  2140. ui64 ourDanger = evaluateDanger(t, h.h);
  2141. if (ourDanger < lowestDanger)
  2142. {
  2143. if(!isBlockedBorderGate(t))
  2144. {
  2145. if (!ourDanger) //at least one safe place found
  2146. return t;
  2147. bestTile = t;
  2148. lowestDanger = ourDanger;
  2149. }
  2150. }
  2151. }
  2152. }
  2153. }
  2154. return bestTile;
  2155. }
  2156. TResources VCAI::estimateIncome() const
  2157. {
  2158. TResources ret;
  2159. for(const CGTownInstance *t : cb->getTownsInfo())
  2160. {
  2161. ret += t->dailyIncome();
  2162. }
  2163. for(const CGObjectInstance *obj : getFlaggedObjects())
  2164. {
  2165. if(obj->ID == Obj::MINE)
  2166. {
  2167. switch(obj->subID)
  2168. {
  2169. case Res::WOOD:
  2170. case Res::ORE:
  2171. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  2172. break;
  2173. case Res::GOLD:
  2174. case 7: //abandoned mine -> also gold
  2175. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  2176. break;
  2177. default:
  2178. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  2179. break;
  2180. }
  2181. }
  2182. }
  2183. return ret;
  2184. }
  2185. bool VCAI::containsSavedRes(const TResources &cost) const
  2186. {
  2187. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  2188. {
  2189. if(saving[i] && cost[i])
  2190. return true;
  2191. }
  2192. return false;
  2193. }
  2194. void VCAI::checkHeroArmy (HeroPtr h)
  2195. {
  2196. auto it = lockedHeroes.find(h);
  2197. if (it != lockedHeroes.end())
  2198. {
  2199. if (it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  2200. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  2201. }
  2202. }
  2203. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2204. {
  2205. logAi->debugStream() << boost::format("Trying to recruit a hero in %s at %s") % t->name % t->visitablePos();
  2206. auto heroes = cb->getAvailableHeroes(t);
  2207. if(heroes.size())
  2208. {
  2209. auto hero = heroes[0];
  2210. if (heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
  2211. {
  2212. if (heroes[1]->getTotalStrength() > hero->getTotalStrength())
  2213. hero = heroes[1];
  2214. }
  2215. cb->recruitHero(t, hero);
  2216. }
  2217. else if(throwing)
  2218. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2219. }
  2220. void VCAI::finish()
  2221. {
  2222. if(makingTurn)
  2223. makingTurn->interrupt();
  2224. }
  2225. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  2226. {
  2227. // static boost::mutex m;
  2228. // boost::unique_lock<boost::mutex> mylock(m);
  2229. boost::barrier b(2);
  2230. boost::thread newThread([&b,this,whatToDo]()
  2231. {
  2232. setThreadName("VCAI::requestActionASAP::helper");
  2233. SET_GLOBAL_STATE(this);
  2234. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  2235. b.wait();
  2236. whatToDo();
  2237. });
  2238. b.wait();
  2239. }
  2240. void VCAI::lostHero(HeroPtr h)
  2241. {
  2242. logAi->debugStream() << boost::format("I lost my hero %s. It's best to forget and move on.") % h.name;
  2243. erase_if_present(lockedHeroes, h);
  2244. for(auto obj : reservedHeroesMap[h])
  2245. {
  2246. erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2247. }
  2248. erase_if_present(reservedHeroesMap, h);
  2249. }
  2250. void VCAI::answerQuery(QueryID queryID, int selection)
  2251. {
  2252. logAi->debugStream() << boost::format("I'll answer the query %d giving the choice %d") % queryID % selection;
  2253. if(queryID != QueryID(-1))
  2254. {
  2255. cb->selectionMade(selection, queryID);
  2256. }
  2257. else
  2258. {
  2259. logAi->debugStream() << boost::format("Since the query ID is %d, the answer won't be sent. This is not a real query!") % queryID;
  2260. //do nothing
  2261. }
  2262. }
  2263. void VCAI::requestSent(const CPackForServer *pack, int requestID)
  2264. {
  2265. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2266. if(auto reply = dynamic_cast<const QueryReply*>(pack))
  2267. {
  2268. status.attemptedAnsweringQuery(reply->qid, requestID);
  2269. }
  2270. }
  2271. std::string VCAI::getBattleAIName() const
  2272. {
  2273. if(settings["server"]["neutralAI"].getType() == JsonNode::DATA_STRING)
  2274. return settings["server"]["neutralAI"].String();
  2275. else
  2276. return "StupidAI";
  2277. }
  2278. void VCAI::validateObject(const CGObjectInstance *obj)
  2279. {
  2280. validateObject(obj->id);
  2281. }
  2282. void VCAI::validateObject(ObjectIdRef obj)
  2283. {
  2284. auto matchesId = [&] (const CGObjectInstance *hlpObj) -> bool { return hlpObj->id == obj.id; };
  2285. if(!obj)
  2286. {
  2287. erase_if(visitableObjs, matchesId);
  2288. for(auto &p : reservedHeroesMap)
  2289. erase_if(p.second, matchesId);
  2290. erase_if(reservedObjs, matchesId);
  2291. }
  2292. }
  2293. TResources VCAI::freeResources() const
  2294. {
  2295. TResources myRes = cb->getResourceAmount();
  2296. myRes[Res::GOLD] -= GOLD_RESERVE;
  2297. vstd::amax(myRes[Res::GOLD], 0);
  2298. return myRes;
  2299. }
  2300. AIStatus::AIStatus()
  2301. {
  2302. battle = NO_BATTLE;
  2303. havingTurn = false;
  2304. ongoingHeroMovement = false;
  2305. ongoingChannelProbing = false;
  2306. }
  2307. AIStatus::~AIStatus()
  2308. {
  2309. }
  2310. void AIStatus::setBattle(BattleState BS)
  2311. {
  2312. boost::unique_lock<boost::mutex> lock(mx);
  2313. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2314. battle = BS;
  2315. cv.notify_all();
  2316. }
  2317. BattleState AIStatus::getBattle()
  2318. {
  2319. boost::unique_lock<boost::mutex> lock(mx);
  2320. return battle;
  2321. }
  2322. void AIStatus::addQuery(QueryID ID, std::string description)
  2323. {
  2324. boost::unique_lock<boost::mutex> lock(mx);
  2325. if(ID == QueryID(-1))
  2326. {
  2327. logAi->debugStream() << boost::format("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s") % ID % description;
  2328. return;
  2329. }
  2330. assert(!vstd::contains(remainingQueries, ID));
  2331. assert(ID.getNum() >= 0);
  2332. remainingQueries[ID] = description;
  2333. cv.notify_all();
  2334. logAi->debugStream() << boost::format("Adding query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  2335. }
  2336. void AIStatus::removeQuery(QueryID ID)
  2337. {
  2338. boost::unique_lock<boost::mutex> lock(mx);
  2339. assert(vstd::contains(remainingQueries, ID));
  2340. std::string description = remainingQueries[ID];
  2341. remainingQueries.erase(ID);
  2342. cv.notify_all();
  2343. logAi->debugStream() << boost::format("Removing query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  2344. }
  2345. int AIStatus::getQueriesCount()
  2346. {
  2347. boost::unique_lock<boost::mutex> lock(mx);
  2348. return remainingQueries.size();
  2349. }
  2350. void AIStatus::startedTurn()
  2351. {
  2352. boost::unique_lock<boost::mutex> lock(mx);
  2353. havingTurn = true;
  2354. cv.notify_all();
  2355. }
  2356. void AIStatus::madeTurn()
  2357. {
  2358. boost::unique_lock<boost::mutex> lock(mx);
  2359. havingTurn = false;
  2360. cv.notify_all();
  2361. }
  2362. void AIStatus::waitTillFree()
  2363. {
  2364. boost::unique_lock<boost::mutex> lock(mx);
  2365. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2366. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  2367. }
  2368. bool AIStatus::haveTurn()
  2369. {
  2370. boost::unique_lock<boost::mutex> lock(mx);
  2371. return havingTurn;
  2372. }
  2373. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2374. {
  2375. boost::unique_lock<boost::mutex> lock(mx);
  2376. assert(vstd::contains(remainingQueries, queryID));
  2377. std::string description = remainingQueries[queryID];
  2378. logAi->debugStream() << boost::format("Attempted answering query %d - %s. Request id=%d. Waiting for results...") % queryID % description % answerRequestID;
  2379. requestToQueryID[answerRequestID] = queryID;
  2380. }
  2381. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2382. {
  2383. assert(vstd::contains(requestToQueryID, answerRequestID));
  2384. QueryID query = requestToQueryID[answerRequestID];
  2385. assert(vstd::contains(remainingQueries, query));
  2386. requestToQueryID.erase(answerRequestID);
  2387. if(result)
  2388. {
  2389. removeQuery(query);
  2390. }
  2391. else
  2392. {
  2393. logAi->errorStream() << "Something went really wrong, failed to answer query " << query << ": " << remainingQueries[query];
  2394. //TODO safely retry
  2395. }
  2396. }
  2397. void AIStatus::heroVisit(const CGObjectInstance *obj, bool started)
  2398. {
  2399. boost::unique_lock<boost::mutex> lock(mx);
  2400. if(started)
  2401. objectsBeingVisited.push_back(obj);
  2402. else
  2403. {
  2404. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2405. // causing visit to hero on the other side.
  2406. // However, we are guaranteed that start/end visit notification maintain stack order.
  2407. assert(!objectsBeingVisited.empty());
  2408. objectsBeingVisited.pop_back();
  2409. }
  2410. cv.notify_all();
  2411. }
  2412. void AIStatus::setMove(bool ongoing)
  2413. {
  2414. boost::unique_lock<boost::mutex> lock(mx);
  2415. ongoingHeroMovement = ongoing;
  2416. cv.notify_all();
  2417. }
  2418. void AIStatus::setChannelProbing(bool ongoing)
  2419. {
  2420. boost::unique_lock<boost::mutex> lock(mx);
  2421. ongoingHeroMovement = ongoing;
  2422. cv.notify_all();
  2423. }
  2424. bool AIStatus::channelProbing()
  2425. {
  2426. return ongoingChannelProbing;
  2427. }
  2428. SectorMap::SectorMap()
  2429. {
  2430. update();
  2431. }
  2432. SectorMap::SectorMap(HeroPtr h)
  2433. {
  2434. update();
  2435. makeParentBFS(h->visitablePos());
  2436. }
  2437. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  2438. {
  2439. if(t->blocked && !t->visitable)
  2440. {
  2441. sec = NOT_AVAILABLE;
  2442. return true;
  2443. }
  2444. return false;
  2445. }
  2446. bool markIfBlocked(ui8 &sec, crint3 pos)
  2447. {
  2448. return markIfBlocked(sec, pos, cb->getTile(pos));
  2449. }
  2450. void SectorMap::update()
  2451. {
  2452. clear();
  2453. int curSector = 3; //0 is invisible, 1 is not explored
  2454. CCallback * cbp = cb.get(); //optimization
  2455. foreach_tile_pos([&](crint3 pos)
  2456. {
  2457. if(retreiveTile(pos) == NOT_CHECKED)
  2458. {
  2459. if(!markIfBlocked(retreiveTile(pos), pos))
  2460. exploreNewSector(pos, curSector++, cbp);
  2461. }
  2462. });
  2463. valid = true;
  2464. }
  2465. void SectorMap::clear()
  2466. {
  2467. sector = cb->getVisibilityMap();
  2468. valid = false;
  2469. }
  2470. void SectorMap::exploreNewSector(crint3 pos, int num, CCallback * cbp)
  2471. {
  2472. Sector &s = infoOnSectors[num];
  2473. s.id = num;
  2474. s.water = cbp->getTile(pos)->isWater();
  2475. std::queue<int3> toVisit;
  2476. toVisit.push(pos);
  2477. while(!toVisit.empty())
  2478. {
  2479. int3 curPos = toVisit.front();
  2480. toVisit.pop();
  2481. ui8 &sec = retreiveTile(curPos);
  2482. if(sec == NOT_CHECKED)
  2483. {
  2484. const TerrainTile *t = cbp->getTile(curPos);
  2485. if(!markIfBlocked(sec, curPos, t))
  2486. {
  2487. if(t->isWater() == s.water) //sector is only-water or only-land
  2488. {
  2489. sec = num;
  2490. s.tiles.push_back(curPos);
  2491. foreach_neighbour(cbp, curPos, [&](CCallback * cbp, crint3 neighPos)
  2492. {
  2493. if(retreiveTile(neighPos) == NOT_CHECKED)
  2494. {
  2495. toVisit.push(neighPos);
  2496. //parent[neighPos] = curPos;
  2497. }
  2498. const TerrainTile *nt = cbp->getTile(neighPos, false);
  2499. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt, s.water))
  2500. {
  2501. s.embarkmentPoints.push_back(neighPos);
  2502. }
  2503. });
  2504. if(t->visitable)
  2505. {
  2506. auto obj = t->visitableObjects.front();
  2507. if (vstd::contains(ai->knownSubterraneanGates, obj))
  2508. {
  2509. s.subterraneanGates.push_back (obj);
  2510. }
  2511. }
  2512. }
  2513. }
  2514. }
  2515. }
  2516. removeDuplicates(s.embarkmentPoints);
  2517. }
  2518. void SectorMap::write(crstring fname)
  2519. {
  2520. std::ofstream out(fname);
  2521. for(int k = 0; k < cb->getMapSize().z; k++)
  2522. {
  2523. for(int j = 0; j < cb->getMapSize().y; j++)
  2524. {
  2525. for(int i = 0; i < cb->getMapSize().x; i++)
  2526. {
  2527. out << (int)sector[i][j][k] << '\t';
  2528. }
  2529. out << std::endl;
  2530. }
  2531. out << std::endl;
  2532. }
  2533. }
  2534. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  2535. { //TODO: allow polling of remaining creatures in dwelling
  2536. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  2537. dynamic_cast<const CGDwelling *>(obj) ||
  2538. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2539. return true;
  2540. switch (obj->ID)
  2541. {
  2542. case Obj::STABLES:
  2543. case Obj::MAGIC_WELL:
  2544. case Obj::HILL_FORT:
  2545. return true;
  2546. case Obj::BORDER_GATE:
  2547. case Obj::BORDERGUARD:
  2548. return (dynamic_cast <const CGKeys *>(obj))->wasMyColorVisited (ai->playerID); //FIXME: they could be revisited sooner than in a week
  2549. }
  2550. return false;
  2551. }
  2552. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2553. {
  2554. switch (obj->ID)
  2555. {
  2556. case Obj::TOWN:
  2557. case Obj::HERO: //never visit our heroes at random
  2558. return obj->tempOwner != h->tempOwner; //do not visit our towns at random
  2559. break;
  2560. case Obj::BORDER_GATE:
  2561. {
  2562. for (auto q : ai->myCb->getMyQuests())
  2563. {
  2564. if (q.obj == obj)
  2565. {
  2566. return false; // do not visit guards or gates when wandering
  2567. }
  2568. }
  2569. return true; //we don't have this quest yet
  2570. }
  2571. break;
  2572. case Obj::BORDERGUARD: //open borderguard if possible
  2573. case Obj::SEER_HUT:
  2574. case Obj::QUEST_GUARD:
  2575. {
  2576. for (auto q : ai->myCb->getMyQuests())
  2577. {
  2578. if (q.obj == obj)
  2579. {
  2580. if (q.quest->checkQuest(h.h))
  2581. return true; //we completed the quest
  2582. else
  2583. return false; //we can't complete this quest
  2584. }
  2585. }
  2586. return true; //we don't have this quest yet
  2587. }
  2588. break;
  2589. case Obj::CREATURE_GENERATOR1:
  2590. {
  2591. if (obj->tempOwner != h->tempOwner)
  2592. return true; //flag just in case
  2593. bool canRecruitCreatures = false;
  2594. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2595. for(auto level : d->creatures)
  2596. {
  2597. for(auto c : level.second)
  2598. {
  2599. if (h->getSlotFor(CreatureID(c)) != SlotID())
  2600. canRecruitCreatures = true;
  2601. }
  2602. }
  2603. return canRecruitCreatures;
  2604. }
  2605. case Obj::HILL_FORT:
  2606. {
  2607. for (auto slot : h->Slots())
  2608. {
  2609. if (slot.second->type->upgrades.size())
  2610. return true; //TODO: check price?
  2611. }
  2612. return false;
  2613. }
  2614. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2615. case Obj::MONOLITH_ONE_WAY_EXIT:
  2616. case Obj::MONOLITH_TWO_WAY:
  2617. case Obj::WHIRLPOOL:
  2618. //TODO: mechanism for handling monoliths
  2619. return false;
  2620. case Obj::SCHOOL_OF_MAGIC:
  2621. case Obj::SCHOOL_OF_WAR:
  2622. {
  2623. TResources myRes = ai->myCb->getResourceAmount();
  2624. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  2625. return false;
  2626. }
  2627. break;
  2628. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2629. if (h->level < 12)
  2630. return false;
  2631. break;
  2632. case Obj::TREE_OF_KNOWLEDGE:
  2633. {
  2634. TResources myRes = ai->myCb->getResourceAmount();
  2635. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  2636. return false;
  2637. }
  2638. break;
  2639. case Obj::MAGIC_WELL:
  2640. return h->mana < h->manaLimit();
  2641. case Obj::PRISON:
  2642. return ai->myCb->getHeroesInfo().size() < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER;// GameConstants::MAX_HEROES_PER_PLAYER;
  2643. case Obj::BOAT:
  2644. return false;
  2645. //Boats are handled by pathfinder
  2646. }
  2647. if (obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2648. return false;
  2649. return true;
  2650. }
  2651. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  2652. /*
  2653. this functions returns one target tile or invalid tile. We will use it to poll possible destinations
  2654. For ship construction etc, another function (goal?) is needed
  2655. */
  2656. {
  2657. int3 ret(-1,-1,-1);
  2658. int sourceSector = retreiveTile(h->visitablePos()),
  2659. destinationSector = retreiveTile(dst);
  2660. const Sector *src = &infoOnSectors[sourceSector],
  2661. *dest = &infoOnSectors[destinationSector];
  2662. if(sourceSector != destinationSector) //use ships, shipyards etc..
  2663. {
  2664. if (ai->isAccessibleForHero(dst, h)) //pathfinder can find a way using ships and gates if tile is not blocked by objects
  2665. return dst;
  2666. std::map<const Sector*, const Sector*> preds;
  2667. std::queue<const Sector *> sectorQueue;
  2668. sectorQueue.push(src);
  2669. while(!sectorQueue.empty())
  2670. {
  2671. const Sector *s = sectorQueue.front();
  2672. sectorQueue.pop();
  2673. for(int3 ep : s->embarkmentPoints)
  2674. {
  2675. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  2676. //preds[s].push_back(neigh);
  2677. if(!preds[neigh])
  2678. {
  2679. preds[neigh] = s;
  2680. sectorQueue.push(neigh);
  2681. }
  2682. }
  2683. for (auto gate : s->subterraneanGates)
  2684. {
  2685. auto gatePair = ai->knownSubterraneanGates.find(gate);
  2686. if (gatePair != ai->knownSubterraneanGates.end())
  2687. {
  2688. //check the other side of gate
  2689. Sector *neigh = &infoOnSectors[retreiveTile(gatePair->second->visitablePos())];
  2690. if(!preds[neigh]) //if we didn't come into this sector yet
  2691. {
  2692. preds[neigh] = s; //it becomes our new target sector
  2693. sectorQueue.push(neigh);
  2694. }
  2695. }
  2696. }
  2697. }
  2698. if(!preds[dest])
  2699. {
  2700. //write("test.txt");
  2701. return ret;
  2702. //throw cannotFulfillGoalException(boost::str(boost::format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  2703. }
  2704. std::vector<const Sector*> toTraverse;
  2705. toTraverse.push_back(dest);
  2706. while(toTraverse.back() != src)
  2707. {
  2708. toTraverse.push_back(preds[toTraverse.back()]);
  2709. }
  2710. if(preds[dest])
  2711. {
  2712. //TODO: would be nice to find sectors in loop
  2713. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  2714. if(!src->water && sectorToReach->water) //embark
  2715. {
  2716. //embark on ship -> look for an EP with a boat
  2717. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  2718. {
  2719. const TerrainTile *t = cb->getTile(pos);
  2720. return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT
  2721. && retreiveTile(pos) == sectorToReach->id;
  2722. });
  2723. if(firstEP != src->embarkmentPoints.end())
  2724. {
  2725. return *firstEP;
  2726. }
  2727. else
  2728. {
  2729. //we need to find a shipyard with an access to the desired sector's EP
  2730. //TODO what about Summon Boat spell?
  2731. std::vector<const IShipyard *> shipyards;
  2732. for(const CGTownInstance *t : cb->getTownsInfo())
  2733. {
  2734. if(t->hasBuilt(BuildingID::SHIPYARD))
  2735. shipyards.push_back(t);
  2736. }
  2737. for(const CGObjectInstance *obj : ai->visitableObjs)
  2738. {
  2739. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  2740. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  2741. shipyards.push_back(shipyard);
  2742. }
  2743. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  2744. {
  2745. return shipyard->shipyardStatus() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  2746. }),shipyards.end());
  2747. if(!shipyards.size())
  2748. {
  2749. //TODO consider possibility of building shipyard in a town
  2750. return ret;
  2751. //throw cannotFulfillGoalException("There is no known shipyard!");
  2752. }
  2753. //we have only shipyards that possibly can build ships onto the appropriate EP
  2754. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  2755. {
  2756. return s->o->tempOwner == ai->playerID;
  2757. });
  2758. if(ownedGoodShipyard != shipyards.end())
  2759. {
  2760. const IShipyard *s = *ownedGoodShipyard;
  2761. TResources shipCost;
  2762. s->getBoatCost(shipCost);
  2763. if(cb->getResourceAmount().canAfford(shipCost))
  2764. {
  2765. int3 ret = s->bestLocation();
  2766. cb->buildBoat(s); //TODO: move actions elsewhere
  2767. return ret;
  2768. }
  2769. else
  2770. {
  2771. //TODO gather res
  2772. return ret;
  2773. //throw cannotFulfillGoalException("Not enough resources to build a boat");
  2774. }
  2775. }
  2776. else
  2777. {
  2778. //TODO pick best shipyard to take over
  2779. return shipyards.front()->o->visitablePos();
  2780. }
  2781. }
  2782. }
  2783. else if(src->water && !sectorToReach->water)
  2784. {
  2785. //TODO
  2786. //disembark
  2787. return ret;
  2788. }
  2789. else //use subterranean gates
  2790. {
  2791. //auto t = findFirstVisitableTile (h, dst);
  2792. //if (t.valid())
  2793. // return t;
  2794. //TODO: pop sectors linked by Subterranean Gate in loop
  2795. auto firstGate = boost::find_if(src->subterraneanGates, [=](const CGObjectInstance * gate) -> bool
  2796. {
  2797. //make sure no hero block the way
  2798. auto pos = ai->knownSubterraneanGates[gate]->visitablePos();
  2799. const TerrainTile *t = cb->getTile(pos);
  2800. return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::SUBTERRANEAN_GATE
  2801. && retreiveTile(pos) == sectorToReach->id;
  2802. });
  2803. if(firstGate != src->subterraneanGates.end())
  2804. {
  2805. //TODO: pahtfinder can find path through subterranean gates, but this function only reaches closest gate
  2806. return (*firstGate)->visitablePos();
  2807. }
  2808. //TODO
  2809. //Monolith? Whirlpool? ...
  2810. return ret;
  2811. //throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  2812. }
  2813. }
  2814. else
  2815. {
  2816. return ret;
  2817. //throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  2818. }
  2819. }
  2820. else
  2821. {
  2822. return findFirstVisitableTile(h, dst);
  2823. }
  2824. //FIXME: find out why this line is reached
  2825. logAi->errorStream() << ("Impossible happened at SectorMap::firstTileToGet");
  2826. return ret;
  2827. }
  2828. int3 SectorMap::findFirstVisitableTile (HeroPtr h, crint3 dst)
  2829. {
  2830. int3 ret(-1,-1,-1);
  2831. int3 curtile = dst;
  2832. while(curtile != h->visitablePos())
  2833. {
  2834. auto topObj = cb->getTopObj(curtile);
  2835. if (topObj && topObj->ID == Obj::HERO && topObj != h.h)
  2836. {
  2837. logAi->warnStream() << ("Another allied hero stands in our way");
  2838. return ret;
  2839. }
  2840. if(ai->myCb->getPathsInfo(h.get())->getPathInfo(curtile)->reachable())
  2841. {
  2842. return curtile;
  2843. }
  2844. else
  2845. {
  2846. auto i = parent.find(curtile);
  2847. if(i != parent.end())
  2848. {
  2849. assert(curtile != i->second);
  2850. curtile = i->second;
  2851. }
  2852. else
  2853. {
  2854. return ret;
  2855. //throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  2856. }
  2857. }
  2858. }
  2859. return ret;
  2860. }
  2861. void SectorMap::makeParentBFS(crint3 source)
  2862. {
  2863. parent.clear();
  2864. int mySector = retreiveTile(source);
  2865. std::queue<int3> toVisit;
  2866. toVisit.push(source);
  2867. while(!toVisit.empty())
  2868. {
  2869. int3 curPos = toVisit.front();
  2870. toVisit.pop();
  2871. ui8 &sec = retreiveTile(curPos);
  2872. assert(sec == mySector); //consider only tiles from the same sector
  2873. UNUSED(sec);
  2874. foreach_neighbour(curPos, [&](crint3 neighPos)
  2875. {
  2876. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  2877. {
  2878. if (cb->canMoveBetween(curPos, neighPos))
  2879. {
  2880. toVisit.push(neighPos);
  2881. parent[neighPos] = curPos;
  2882. }
  2883. }
  2884. });
  2885. }
  2886. }
  2887. unsigned char & SectorMap::retreiveTile(crint3 pos)
  2888. {
  2889. return retreiveTileN(sector, pos);
  2890. }