VCAI.cpp 81 KB

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